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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1173  ! foxr        4: # $Id: lonnet.pm,v 1.1172 2012/05/21 18:35:30 bisitz Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.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'};
                   1242:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1243:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1244:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1245:     my $serverhomedom = &host_domain($lonhost);
                   1246: 
                   1247:     my $cachetime = 60*60*24;
                   1248: 
                   1249:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1250:         $dom_in_use = $udom;
                   1251:         $homeintdom = 1;
                   1252:     } else {
                   1253:         $dom_in_use = $serverhomedom;
                   1254:     }
                   1255:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1256:     unless (defined($cached)) {
                   1257:         my %domconfig =
                   1258:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1259:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1260:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1261:         }
                   1262:     }
                   1263:     if (ref($result) eq 'HASH') {
                   1264:         my $currbalancer = $result->{'lonhost'};
                   1265:         my $currtargets = $result->{'targets'};
                   1266:         my $currrules = $result->{'rules'};
                   1267:         if ($currbalancer ne '') {
                   1268:             my @hosts = &current_machine_ids();
                   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:     }
                   1384:     return ($is_balancer,$otherserver);
                   1385: }
                   1386: 
                   1387: sub get_loadbalancer_targets {
                   1388:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1389:     my $offloadto;
                   1390:     if ($rule_in_effect eq '') {
                   1391:         $offloadto = $currtargets;
                   1392:     } else {
                   1393:         if ($rule_in_effect eq 'homeserver') {
                   1394:             my $homeserver = &homeserver($uname,$udom);
                   1395:             if ($homeserver ne 'no_host') {
                   1396:                 $offloadto = [$homeserver];
                   1397:             }
                   1398:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1399:             my %domconfig =
                   1400:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1401:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1402:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1403:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1404:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1405:                     }
                   1406:                 }
                   1407:             } else {
                   1408:                 my %servers = &dom_servers($udom);
                   1409:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1410:                 if (&hostname($remotebalancer) ne '') {
                   1411:                     $offloadto = [$remotebalancer];
                   1412:                 }
                   1413:             }
                   1414:         } elsif (&hostname($rule_in_effect) ne '') {
                   1415:             $offloadto = [$rule_in_effect];
                   1416:         }
                   1417:     }
                   1418:     return $offloadto;
                   1419: }
                   1420: 
1.1127    raeburn  1421: sub internet_dom_servers {
                   1422:     my ($dom) = @_;
                   1423:     my (%uniqservers,%servers);
                   1424:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1425:     my @machinedoms = &machine_domains($primaryserver);
                   1426:     foreach my $mdom (@machinedoms) {
                   1427:         my %currservers = %servers;
                   1428:         my %server = &get_servers($mdom);
                   1429:         %servers = (%currservers,%server);
                   1430:     }
                   1431:     my %by_hostname;
                   1432:     foreach my $id (keys(%servers)) {
                   1433:         push(@{$by_hostname{$servers{$id}}},$id);
                   1434:     }
                   1435:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1436:         if (@{$by_hostname{$hostname}} > 1) {
                   1437:             my $match = 0;
                   1438:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1439:                 if (&host_domain($id) eq $dom) {
                   1440:                     $uniqservers{$id} = $hostname;
                   1441:                     $match = 1;
                   1442:                 }
                   1443:             }
                   1444:             unless ($match) {
                   1445:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1446:             }
                   1447:         } else {
                   1448:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1449:         }
                   1450:     }
                   1451:     return %uniqservers;
                   1452: }
                   1453: 
1.1       albertel 1454: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1455: 
1.599     albertel 1456: my %homecache;
1.1       albertel 1457: sub homeserver {
1.230     stredwic 1458:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1459:     my $index="$uname:$udom";
1.426     albertel 1460: 
1.599     albertel 1461:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1462: 
                   1463:     my %servers = &get_servers($udom,'library');
                   1464:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1465:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1466: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1467: 
                   1468: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1469: 	if ($answer eq 'found') {
                   1470: 	    delete($badServerCache{$tryserver}); 
                   1471: 	    return $homecache{$index}=$tryserver;
                   1472: 	} elsif ($answer eq 'no_host') {
                   1473: 	    $badServerCache{$tryserver}=1;
                   1474: 	}
1.1       albertel 1475:     }    
                   1476:     return 'no_host';
1.70      www      1477: }
                   1478: 
                   1479: # ------------------------------------- Find the usernames behind a list of IDs
                   1480: 
                   1481: sub idget {
                   1482:     my ($udom,@ids)=@_;
                   1483:     my %returnhash=();
                   1484:     
1.841     albertel 1485:     my %servers = &get_servers($udom,'library');
                   1486:     foreach my $tryserver (keys(%servers)) {
                   1487: 	my $idlist=join('&',@ids);
                   1488: 	$idlist=~tr/A-Z/a-z/; 
                   1489: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1490: 	my @answer=();
                   1491: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1492: 	    @answer=split(/\&/,$reply);
                   1493: 	}                    ;
                   1494: 	my $i;
                   1495: 	for ($i=0;$i<=$#ids;$i++) {
                   1496: 	    if ($answer[$i]) {
                   1497: 		$returnhash{$ids[$i]}=$answer[$i];
                   1498: 	    } 
                   1499: 	}
                   1500:     } 
1.70      www      1501:     return %returnhash;
                   1502: }
                   1503: 
                   1504: # ------------------------------------- Find the IDs behind a list of usernames
                   1505: 
                   1506: sub idrget {
                   1507:     my ($udom,@unames)=@_;
                   1508:     my %returnhash=();
1.800     albertel 1509:     foreach my $uname (@unames) {
                   1510:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1511:     }
1.70      www      1512:     return %returnhash;
                   1513: }
                   1514: 
                   1515: # ------------------------------- Store away a list of names and associated IDs
                   1516: 
                   1517: sub idput {
                   1518:     my ($udom,%ids)=@_;
                   1519:     my %servers=();
1.800     albertel 1520:     foreach my $uname (keys(%ids)) {
                   1521: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1522:         my $uhom=&homeserver($uname,$udom);
1.70      www      1523:         if ($uhom ne 'no_host') {
1.800     albertel 1524:             my $id=&escape($ids{$uname});
1.70      www      1525:             $id=~tr/A-Z/a-z/;
1.800     albertel 1526:             my $esc_unam=&escape($uname);
1.70      www      1527: 	    if ($servers{$uhom}) {
1.800     albertel 1528: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1529:             } else {
1.800     albertel 1530:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1531:             }
                   1532:         }
1.191     harris41 1533:     }
1.800     albertel 1534:     foreach my $server (keys(%servers)) {
                   1535:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1536:     }
1.344     www      1537: }
                   1538: 
1.1023    raeburn  1539: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1540: sub dump_dom {
1.1165    droeschl 1541:     my ($namespace, $udom, $regexp) = @_;
                   1542: 
                   1543:     $udom ||= $env{'user.domain'};
                   1544: 
                   1545:     return () unless $udom;
                   1546: 
                   1547:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1548: }
                   1549: 
1.1023    raeburn  1550: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1551: 
                   1552: sub get_dom {
1.860     raeburn  1553:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1554:     my $items='';
                   1555:     foreach my $item (@$storearr) {
                   1556:         $items.=&escape($item).'&';
                   1557:     }
                   1558:     $items=~s/\&$//;
1.860     raeburn  1559:     if (!$udom) {
                   1560:         $udom=$env{'user.domain'};
                   1561:         if (defined(&domain($udom,'primary'))) {
                   1562:             $uhome=&domain($udom,'primary');
                   1563:         } else {
1.874     albertel 1564:             undef($uhome);
1.860     raeburn  1565:         }
                   1566:     } else {
                   1567:         if (!$uhome) {
                   1568:             if (defined(&domain($udom,'primary'))) {
                   1569:                 $uhome=&domain($udom,'primary');
                   1570:             }
                   1571:         }
                   1572:     }
                   1573:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1574:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1575:         my %returnhash;
1.875     albertel 1576:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1577:             return %returnhash;
                   1578:         }
1.806     raeburn  1579:         my @pairs=split(/\&/,$rep);
                   1580:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1581:             return @pairs;
                   1582:         }
                   1583:         my $i=0;
                   1584:         foreach my $item (@$storearr) {
                   1585:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1586:             $i++;
                   1587:         }
                   1588:         return %returnhash;
                   1589:     } else {
1.880     banghart 1590:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1591:     }
                   1592: }
                   1593: 
                   1594: # -------------------------------------------- put items in domain db files 
                   1595: 
                   1596: sub put_dom {
1.860     raeburn  1597:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1598:     if (!$udom) {
                   1599:         $udom=$env{'user.domain'};
                   1600:         if (defined(&domain($udom,'primary'))) {
                   1601:             $uhome=&domain($udom,'primary');
                   1602:         } else {
1.874     albertel 1603:             undef($uhome);
1.860     raeburn  1604:         }
                   1605:     } else {
                   1606:         if (!$uhome) {
                   1607:             if (defined(&domain($udom,'primary'))) {
                   1608:                 $uhome=&domain($udom,'primary');
                   1609:             }
                   1610:         }
                   1611:     } 
                   1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1613:         my $items='';
                   1614:         foreach my $item (keys(%$storehash)) {
                   1615:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1616:         }
                   1617:         $items=~s/\&$//;
                   1618:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1619:     } else {
1.860     raeburn  1620:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1621:     }
                   1622: }
                   1623: 
1.1023    raeburn  1624: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1625: sub newput_dom {
1.1023    raeburn  1626:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1627:     my $result;
                   1628:     if (!$udom) {
                   1629:         $udom=$env{'user.domain'};
                   1630:     }
1.1023    raeburn  1631:     if ($udom) {
                   1632:         my $uname = &get_domainconfiguser($udom);
                   1633:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1634:     }
                   1635:     return $result;
                   1636: }
                   1637: 
1.1023    raeburn  1638: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1639: sub del_dom {
1.1023    raeburn  1640:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1641:     if (ref($storearr) eq 'ARRAY') {
                   1642:         if (!$udom) {
                   1643:             $udom=$env{'user.domain'};
                   1644:         }
1.1023    raeburn  1645:         if ($udom) {
                   1646:             my $uname = &get_domainconfiguser($udom); 
                   1647:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1648:         }
                   1649:     }
                   1650: }
                   1651: 
1.1023    raeburn  1652: # ----------------------------------construct domainconfig user for a domain 
                   1653: sub get_domainconfiguser {
                   1654:     my ($udom) = @_;
                   1655:     return $udom.'-domainconfig';
                   1656: }
                   1657: 
1.837     raeburn  1658: sub retrieve_inst_usertypes {
                   1659:     my ($udom) = @_;
                   1660:     my (%returnhash,@order);
1.989     raeburn  1661:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1662:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1663:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1664:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1665:         @order = @{$domdefs{'inststatusorder'}};
                   1666:     } else {
                   1667:         if (defined(&domain($udom,'primary'))) {
                   1668:             my $uhome=&domain($udom,'primary');
                   1669:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1670:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1671:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1672:                 return (\%returnhash,\@order);
                   1673:             }
                   1674:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1675:             my @pairs=split(/\&/,$hashitems);
                   1676:             foreach my $item (@pairs) {
                   1677:                 my ($key,$value)=split(/=/,$item,2);
                   1678:                 $key = &unescape($key);
                   1679:                 next if ($key =~ /^error: 2 /);
                   1680:                 $returnhash{$key}=&thaw_unescape($value);
                   1681:             }
                   1682:             my @esc_order = split(/\&/,$orderitems);
                   1683:             foreach my $item (@esc_order) {
                   1684:                 push(@order,&unescape($item));
                   1685:             }
                   1686:         } else {
                   1687:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1688:         }
                   1689:     }
                   1690:     return (\%returnhash,\@order);
                   1691: }
                   1692: 
1.868     raeburn  1693: sub is_domainimage {
                   1694:     my ($url) = @_;
                   1695:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1696:         if (&domain($1) ne '') {
                   1697:             return '1';
                   1698:         }
                   1699:     }
                   1700:     return;
                   1701: }
                   1702: 
1.899     raeburn  1703: sub inst_directory_query {
                   1704:     my ($srch) = @_;
                   1705:     my $udom = $srch->{'srchdomain'};
                   1706:     my %results;
                   1707:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1708:     my $outcome;
1.899     raeburn  1709:     if ($homeserver ne '') {
1.904     albertel 1710: 	my $queryid=&reply("querysend:instdirsearch:".
                   1711: 			   &escape($srch->{'srchby'}).':'.
                   1712: 			   &escape($srch->{'srchterm'}).':'.
                   1713: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1714: 	my $host=&hostname($homeserver);
                   1715: 	if ($queryid !~/^\Q$host\E\_/) {
                   1716: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1717: 	    return;
                   1718: 	}
                   1719: 	my $response = &get_query_reply($queryid);
                   1720: 	my $maxtries = 5;
                   1721: 	my $tries = 1;
                   1722: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1723: 	    $response = &get_query_reply($queryid);
                   1724: 	    $tries ++;
                   1725: 	}
                   1726: 
                   1727:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1728:             if ($response eq 'unavailable') {
                   1729:                 $outcome = $response;
                   1730:             } else {
                   1731:                 $outcome = 'ok';
                   1732:                 my @matches = split(/\n/,$response);
                   1733:                 foreach my $match (@matches) {
                   1734:                     my ($key,$value) = split(/=/,$match);
                   1735:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1736:                 }
1.899     raeburn  1737:             }
                   1738:         }
                   1739:     }
1.909     raeburn  1740:     return ($outcome,%results);
1.899     raeburn  1741: }
                   1742: 
                   1743: sub usersearch {
                   1744:     my ($srch) = @_;
                   1745:     my $dom = $srch->{'srchdomain'};
                   1746:     my %results;
                   1747:     my %libserv = &all_library();
                   1748:     my $query = 'usersearch';
                   1749:     foreach my $tryserver (keys(%libserv)) {
                   1750:         if (&host_domain($tryserver) eq $dom) {
                   1751:             my $host=&hostname($tryserver);
                   1752:             my $queryid=
1.911     raeburn  1753:                 &reply("querysend:".&escape($query).':'.
                   1754:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1755:                        &escape($srch->{'srchtype'}).':'.
                   1756:                        &escape($srch->{'srchterm'}),$tryserver);
                   1757:             if ($queryid !~/^\Q$host\E\_/) {
                   1758:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1759:                 next;
1.899     raeburn  1760:             }
                   1761:             my $reply = &get_query_reply($queryid);
                   1762:             my $maxtries = 1;
                   1763:             my $tries = 1;
                   1764:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1765:                 $reply = &get_query_reply($queryid);
                   1766:                 $tries ++;
                   1767:             }
                   1768:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1769:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1770:             } else {
1.911     raeburn  1771:                 my @matches;
                   1772:                 if ($reply =~ /\n/) {
                   1773:                     @matches = split(/\n/,$reply);
                   1774:                 } else {
                   1775:                     @matches = split(/\&/,$reply);
                   1776:                 }
1.899     raeburn  1777:                 foreach my $match (@matches) {
                   1778:                     my ($uname,$udom,%userhash);
1.911     raeburn  1779:                     foreach my $entry (split(/:/,$match)) {
                   1780:                         my ($key,$value) =
                   1781:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1782:                         $userhash{$key} = $value;
                   1783:                         if ($key eq 'username') {
                   1784:                             $uname = $value;
                   1785:                         } elsif ($key eq 'domain') {
                   1786:                             $udom = $value;
1.911     raeburn  1787:                         }
1.899     raeburn  1788:                     }
                   1789:                     $results{$uname.':'.$udom} = \%userhash;
                   1790:                 }
                   1791:             }
                   1792:         }
                   1793:     }
                   1794:     return %results;
                   1795: }
                   1796: 
1.912     raeburn  1797: sub get_instuser {
                   1798:     my ($udom,$uname,$id) = @_;
                   1799:     my $homeserver = &domain($udom,'primary');
                   1800:     my ($outcome,%results);
                   1801:     if ($homeserver ne '') {
                   1802:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1803:                            &escape($id).':'.&escape($udom),$homeserver);
                   1804:         my $host=&hostname($homeserver);
                   1805:         if ($queryid !~/^\Q$host\E\_/) {
                   1806:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1807:             return;
                   1808:         }
                   1809:         my $response = &get_query_reply($queryid);
                   1810:         my $maxtries = 5;
                   1811:         my $tries = 1;
                   1812:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1813:             $response = &get_query_reply($queryid);
                   1814:             $tries ++;
                   1815:         }
                   1816:         if (!&error($response) && $response ne 'refused') {
                   1817:             if ($response eq 'unavailable') {
                   1818:                 $outcome = $response;
                   1819:             } else {
                   1820:                 $outcome = 'ok';
                   1821:                 my @matches = split(/\n/,$response);
                   1822:                 foreach my $match (@matches) {
                   1823:                     my ($key,$value) = split(/=/,$match);
                   1824:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1825:                 }
                   1826:             }
                   1827:         }
                   1828:     }
                   1829:     my %userinfo;
                   1830:     if (ref($results{$uname}) eq 'HASH') {
                   1831:         %userinfo = %{$results{$uname}};
                   1832:     } 
                   1833:     return ($outcome,%userinfo);
                   1834: }
                   1835: 
                   1836: sub inst_rulecheck {
1.923     raeburn  1837:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1838:     my %returnhash;
                   1839:     if ($udom ne '') {
                   1840:         if (ref($rules) eq 'ARRAY') {
                   1841:             @{$rules} = map {&escape($_);} (@{$rules});
                   1842:             my $rulestr = join(':',@{$rules});
                   1843:             my $homeserver=&domain($udom,'primary');
                   1844:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1845:                 my $response;
                   1846:                 if ($item eq 'username') {                
                   1847:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1848:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1849:                                               $homeserver));
1.923     raeburn  1850:                 } elsif ($item eq 'id') {
                   1851:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1852:                                               ':'.&escape($id).':'.$rulestr,
                   1853:                                               $homeserver));
1.945     raeburn  1854:                 } elsif ($item eq 'selfcreate') {
                   1855:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1856:                                                &escape($udom).':'.&escape($uname).
                   1857:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1858:                 }
1.912     raeburn  1859:                 if ($response ne 'refused') {
                   1860:                     my @pairs=split(/\&/,$response);
                   1861:                     foreach my $item (@pairs) {
                   1862:                         my ($key,$value)=split(/=/,$item,2);
                   1863:                         $key = &unescape($key);
                   1864:                         next if ($key =~ /^error: 2 /);
                   1865:                         $returnhash{$key}=&thaw_unescape($value);
                   1866:                     }
                   1867:                 }
                   1868:             }
                   1869:         }
                   1870:     }
                   1871:     return %returnhash;
                   1872: }
                   1873: 
                   1874: sub inst_userrules {
1.923     raeburn  1875:     my ($udom,$check) = @_;
1.912     raeburn  1876:     my (%ruleshash,@ruleorder);
                   1877:     if ($udom ne '') {
                   1878:         my $homeserver=&domain($udom,'primary');
                   1879:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1880:             my $response;
                   1881:             if ($check eq 'id') {
                   1882:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1883:                                  $homeserver);
1.943     raeburn  1884:             } elsif ($check eq 'email') {
                   1885:                 $response=&reply('instemailrules:'.&escape($udom),
                   1886:                                  $homeserver);
1.923     raeburn  1887:             } else {
                   1888:                 $response=&reply('instuserrules:'.&escape($udom),
                   1889:                                  $homeserver);
                   1890:             }
1.912     raeburn  1891:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1892:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1893:                 ($response ne 'no_such_host')) {
                   1894:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1895:                 my @pairs=split(/\&/,$hashitems);
                   1896:                 foreach my $item (@pairs) {
                   1897:                     my ($key,$value)=split(/=/,$item,2);
                   1898:                     $key = &unescape($key);
                   1899:                     next if ($key =~ /^error: 2 /);
                   1900:                     $ruleshash{$key}=&thaw_unescape($value);
                   1901:                 }
                   1902:                 my @esc_order = split(/\&/,$orderitems);
                   1903:                 foreach my $item (@esc_order) {
                   1904:                     push(@ruleorder,&unescape($item));
                   1905:                 }
                   1906:             }
                   1907:         }
                   1908:     }
                   1909:     return (\%ruleshash,\@ruleorder);
                   1910: }
                   1911: 
1.976     raeburn  1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1913: 
                   1914: sub get_domain_defaults {
                   1915:     my ($domain) = @_;
                   1916:     my $cachetime = 60*60*24;
                   1917:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1918:     if (defined($cached)) {
                   1919:         if (ref($result) eq 'HASH') {
                   1920:             return %{$result};
                   1921:         }
                   1922:     }
                   1923:     my %domdefaults;
                   1924:     my %domconfig =
1.989     raeburn  1925:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1926:                                   'requestcourses','inststatus',
1.1073    raeburn  1927:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1928:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1929:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1930:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1931:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1932:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1933:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1934:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1935:     } else {
                   1936:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1937:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1938:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1939:     }
1.976     raeburn  1940:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1941:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1943:         } else {
                   1944:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1945:         } 
                   1946:         my @usertools = ('aboutme','blog','portfolio');
                   1947:         foreach my $item (@usertools) {
                   1948:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1949:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1950:             }
                   1951:         }
                   1952:     }
1.985     raeburn  1953:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1954:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1955:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1956:         }
                   1957:     }
1.989     raeburn  1958:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1959:         foreach my $item ('inststatustypes','inststatusorder') {
                   1960:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1961:         }
                   1962:     }
1.1047    raeburn  1963:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1964:         foreach my $item ('canuse_pdfforms') {
                   1965:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1966:         }
                   1967:     }
1.1073    raeburn  1968:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1969:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1970:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1971:         }
                   1972:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1973:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1974:         }
                   1975:     }
1.943     raeburn  1976:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1977:                                   $cachetime);
                   1978:     return %domdefaults;
                   1979: }
                   1980: 
1.344     www      1981: # --------------------------------------------------- Assign a key to a student
                   1982: 
                   1983: sub assign_access_key {
1.364     www      1984: #
                   1985: # a valid key looks like uname:udom#comments
                   1986: # comments are being appended
                   1987: #
1.498     www      1988:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1989:     $kdom=
1.620     albertel 1990:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1991:     $knum=
1.620     albertel 1992:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1993:     $cdom=
1.620     albertel 1994:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1995:     $cnum=
1.620     albertel 1996:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1997:     $udom=$env{'user.name'} unless (defined($udom));
                   1998:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1999:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2000:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2001:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2002:                                                   # assigned to this person
                   2003:                                                   # - this should not happen,
1.345     www      2004:                                                   # unless something went wrong
                   2005:                                                   # the first time around
                   2006: # ready to assign
1.364     www      2007:         $logentry=$1.'; '.$logentry;
1.496     www      2008:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2009:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2010: # key now belongs to user
1.346     www      2011: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2012:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2013:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2014:                 return 'ok';
                   2015:             } else {
                   2016:                 return 
                   2017:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2018: 	    }
                   2019:         } else {
                   2020:             return 'error: Could not assign key, try again later.';
                   2021:         }
1.364     www      2022:     } elsif (!$existing{$ckey}) {
1.345     www      2023: # the key does not exist
                   2024: 	return 'error: The key does not exist';
                   2025:     } else {
                   2026: # the key is somebody else's
                   2027: 	return 'error: The key is already in use';
                   2028:     }
1.344     www      2029: }
                   2030: 
1.364     www      2031: # ------------------------------------------ put an additional comment on a key
                   2032: 
                   2033: sub comment_access_key {
                   2034: #
                   2035: # a valid key looks like uname:udom#comments
                   2036: # comments are being appended
                   2037: #
                   2038:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2039:     $cdom=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2041:     $cnum=
1.620     albertel 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2043:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2044:     if ($existing{$ckey}) {
                   2045:         $existing{$ckey}.='; '.$logentry;
                   2046: # ready to assign
1.367     www      2047:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2048:                                                  $cdom,$cnum) eq 'ok') {
                   2049: 	    return 'ok';
                   2050:         } else {
                   2051: 	    return 'error: Count not store comment.';
                   2052:         }
                   2053:     } else {
                   2054: # the key does not exist
                   2055: 	return 'error: The key does not exist';
                   2056:     }
                   2057: }
                   2058: 
1.344     www      2059: # ------------------------------------------------------ Generate a set of keys
                   2060: 
                   2061: sub generate_access_keys {
1.364     www      2062:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2063:     $cdom=
1.620     albertel 2064:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2065:     $cnum=
1.620     albertel 2066:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2067:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2068:     unless (($cdom) && ($cnum)) { return 0; }
                   2069:     if ($number>10000) { return 0; }
                   2070:     sleep(2); # make sure don't get same seed twice
                   2071:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2072:     my $total=0;
                   2073:     for (my $i=1;$i<=$number;$i++) {
                   2074:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2075:                   sprintf("%lx",int(100000*rand)).'-'.
                   2076:                   sprintf("%lx",int(100000*rand));
                   2077:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2078:        $newkey=~s/0/h/g; # and also 0 and O
                   2079:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2080:        if ($existing{$newkey}) {
                   2081:            $i--;
                   2082:        } else {
1.364     www      2083: 	  if (&put('accesskeys',
                   2084:               { $newkey => '# generated '.localtime().
1.620     albertel 2085:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2086:                            '; '.$logentry },
                   2087: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2088:               $total++;
                   2089: 	  }
                   2090:        }
                   2091:     }
1.620     albertel 2092:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2093:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2094:     return $total;
                   2095: }
                   2096: 
                   2097: # ------------------------------------------------------- Validate an accesskey
                   2098: 
                   2099: sub validate_access_key {
                   2100:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2101:     $cdom=
1.620     albertel 2102:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2103:     $cnum=
1.620     albertel 2104:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2105:     $udom=$env{'user.domain'} unless (defined($udom));
                   2106:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2107:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2108:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2109: }
                   2110: 
                   2111: # ------------------------------------- Find the section of student in a course
1.652     albertel 2112: sub devalidate_getsection_cache {
                   2113:     my ($udom,$unam,$courseid)=@_;
                   2114:     my $hashid="$udom:$unam:$courseid";
                   2115:     &devalidate_cache_new('getsection',$hashid);
                   2116: }
1.298     matthew  2117: 
1.815     albertel 2118: sub courseid_to_courseurl {
                   2119:     my ($courseid) = @_;
                   2120:     #already url style courseid
                   2121:     return $courseid if ($courseid =~ m{^/});
                   2122: 
                   2123:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2124: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2125: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2126: 	return "/$cdom/$cnum";
                   2127:     }
                   2128: 
                   2129:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2130:     if (exists($courseinfo{'num'})) {
                   2131: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2132:     }
                   2133: 
                   2134:     return undef;
                   2135: }
                   2136: 
1.298     matthew  2137: sub getsection {
                   2138:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2139:     my $cachetime=1800;
1.551     albertel 2140: 
                   2141:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2142:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2143:     if (defined($cached)) { return $result; }
                   2144: 
1.298     matthew  2145:     my %Pending; 
                   2146:     my %Expired;
                   2147:     #
                   2148:     # Each role can either have not started yet (pending), be active, 
                   2149:     #    or have expired.
                   2150:     #
                   2151:     # If there is an active role, we are done.
                   2152:     #
                   2153:     # If there is more than one role which has not started yet, 
                   2154:     #     choose the one which will start sooner
                   2155:     # If there is one role which has not started yet, return it.
                   2156:     #
                   2157:     # If there is more than one expired role, choose the one which ended last.
                   2158:     # If there is a role which has expired, return it.
                   2159:     #
1.815     albertel 2160:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2161:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2162:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2163:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2164:         my $section=$1;
                   2165:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2166:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2167:         my $now=time;
1.548     albertel 2168:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2169:             $Expired{$end}=$section;
                   2170:             next;
                   2171:         }
1.548     albertel 2172:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2173:             $Pending{$start}=$section;
                   2174:             next;
                   2175:         }
1.599     albertel 2176:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2177:     }
                   2178:     #
                   2179:     # Presumedly there will be few matching roles from the above
                   2180:     # loop and the sorting time will be negligible.
                   2181:     if (scalar(keys(%Pending))) {
                   2182:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2183:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2184:     } 
                   2185:     if (scalar(keys(%Expired))) {
                   2186:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2187:         my $time = pop(@sorted);
1.599     albertel 2188:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2189:     }
1.599     albertel 2190:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2191: }
1.70      www      2192: 
1.599     albertel 2193: sub save_cache {
                   2194:     &purge_remembered();
1.722     albertel 2195:     #&Apache::loncommon::validate_page();
1.620     albertel 2196:     undef(%env);
1.780     albertel 2197:     undef($env_loaded);
1.599     albertel 2198: }
1.452     albertel 2199: 
1.599     albertel 2200: my $to_remember=-1;
                   2201: my %remembered;
                   2202: my %accessed;
                   2203: my $kicks=0;
                   2204: my $hits=0;
1.849     albertel 2205: sub make_key {
                   2206:     my ($name,$id) = @_;
1.872     albertel 2207:     if (length($id) > 65 
                   2208: 	&& length(&escape($id)) > 200) {
                   2209: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2210:     }
1.849     albertel 2211:     return &escape($name.':'.$id);
                   2212: }
                   2213: 
1.599     albertel 2214: sub devalidate_cache_new {
                   2215:     my ($name,$id,$debug) = @_;
                   2216:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2217:     $id=&make_key($name,$id);
1.599     albertel 2218:     $memcache->delete($id);
                   2219:     delete($remembered{$id});
                   2220:     delete($accessed{$id});
                   2221: }
                   2222: 
                   2223: sub is_cached_new {
                   2224:     my ($name,$id,$debug) = @_;
1.849     albertel 2225:     $id=&make_key($name,$id);
1.599     albertel 2226:     if (exists($remembered{$id})) {
1.1133    foxr     2227: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2228: 	$accessed{$id}=[&gettimeofday()];
                   2229: 	$hits++;
                   2230: 	return ($remembered{$id},1);
                   2231:     }
                   2232:     my $value = $memcache->get($id);
                   2233:     if (!(defined($value))) {
                   2234: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2235: 	return (undef,undef);
1.416     albertel 2236:     }
1.599     albertel 2237:     if ($value eq '__undef__') {
                   2238: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2239: 	$value=undef;
                   2240:     }
                   2241:     &make_room($id,$value,$debug);
                   2242:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2243:     return ($value,1);
                   2244: }
                   2245: 
                   2246: sub do_cache_new {
                   2247:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2248:     $id=&make_key($name,$id);
1.599     albertel 2249:     my $setvalue=$value;
                   2250:     if (!defined($setvalue)) {
                   2251: 	$setvalue='__undef__';
                   2252:     }
1.623     albertel 2253:     if (!defined($time) ) {
                   2254: 	$time=600;
                   2255:     }
1.599     albertel 2256:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2257:     my $result = $memcache->set($id,$setvalue,$time);
                   2258:     if (! $result) {
1.872     albertel 2259: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2260: 	$memcache->disconnect_all();
1.872     albertel 2261:     }
1.600     albertel 2262:     # need to make a copy of $value
1.919     albertel 2263:     &make_room($id,$value,$debug);
1.599     albertel 2264:     return $value;
                   2265: }
                   2266: 
                   2267: sub make_room {
                   2268:     my ($id,$value,$debug)=@_;
1.919     albertel 2269: 
                   2270:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2271:                                     : $value;
1.599     albertel 2272:     if ($to_remember<0) { return; }
                   2273:     $accessed{$id}=[&gettimeofday()];
                   2274:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2275:     my $to_kick;
                   2276:     my $max_time=0;
                   2277:     foreach my $other (keys(%accessed)) {
                   2278: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2279: 	    $to_kick=$other;
                   2280: 	    $max_time=&tv_interval($accessed{$other});
                   2281: 	}
                   2282:     }
                   2283:     delete($remembered{$to_kick});
                   2284:     delete($accessed{$to_kick});
                   2285:     $kicks++;
                   2286:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2287:     return;
                   2288: }
                   2289: 
1.599     albertel 2290: sub purge_remembered {
1.604     albertel 2291:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2292:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2293:     undef(%remembered);
                   2294:     undef(%accessed);
1.428     albertel 2295: }
1.70      www      2296: # ------------------------------------- Read an entry from a user's environment
                   2297: 
                   2298: sub userenvironment {
                   2299:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2300:     my $items;
                   2301:     foreach my $item (@what) {
                   2302:         $items.=&escape($item).'&';
                   2303:     }
                   2304:     $items=~s/\&$//;
1.70      www      2305:     my %returnhash=();
1.1009    raeburn  2306:     my $uhome = &homeserver($unam,$udom);
                   2307:     unless ($uhome eq 'no_host') {
                   2308:         my @answer=split(/\&/, 
                   2309:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2310:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2311:             return %returnhash;
                   2312:         }
1.1009    raeburn  2313:         my $i;
                   2314:         for ($i=0;$i<=$#what;$i++) {
                   2315: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2316:         }
1.70      www      2317:     }
                   2318:     return %returnhash;
1.1       albertel 2319: }
                   2320: 
1.617     albertel 2321: # ---------------------------------------------------------- Get a studentphoto
                   2322: sub studentphoto {
                   2323:     my ($udom,$unam,$ext) = @_;
                   2324:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2325:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2326:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2327:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2328:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2329:             } else {
                   2330:                 my ($result,$perm_reqd)=
1.707     albertel 2331: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2332:                 if ($result eq 'ok') {
                   2333:                     if (!($perm_reqd eq 'yes')) {
                   2334:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2335:                     }
                   2336:                 }
                   2337:             }
                   2338:         }
                   2339:     } else {
                   2340:         my ($result,$perm_reqd) = 
1.707     albertel 2341: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2342:         if ($result eq 'ok') {
                   2343:             if (!($perm_reqd eq 'yes')) {
                   2344:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2345:             }
                   2346:         }
                   2347:     }
                   2348:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2349: }
                   2350: 
                   2351: sub retrievestudentphoto {
                   2352:     my ($udom,$unam,$ext,$type) = @_;
                   2353:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2354:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2355:     if ($ret eq 'ok') {
                   2356:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2357:         if ($type eq 'thumbnail') {
                   2358:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2359:         }
                   2360:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2361:         return $tokenurl;
                   2362:     } else {
                   2363:         if ($type eq 'thumbnail') {
                   2364:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2365:         } else { 
                   2366:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2367:         }
1.617     albertel 2368:     }
                   2369: }
                   2370: 
1.263     www      2371: # -------------------------------------------------------------------- New chat
                   2372: 
                   2373: sub chatsend {
1.724     raeburn  2374:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2375:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2376:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2377:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2378:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2379: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2380: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2381: }
                   2382: 
                   2383: # ------------------------------------------ Find current version of a resource
                   2384: 
                   2385: sub getversion {
                   2386:     my $fname=&clutter(shift);
                   2387:     unless ($fname=~/^\/res\//) { return -1; }
                   2388:     return &currentversion(&filelocation('',$fname));
                   2389: }
                   2390: 
                   2391: sub currentversion {
                   2392:     my $fname=shift;
                   2393:     my $author=$fname;
                   2394:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2395:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2396:     my $home=&homeserver($uname,$udom);
1.292     www      2397:     if ($home eq 'no_host') { 
                   2398:         return -1; 
                   2399:     }
1.1112    www      2400:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2401:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2402: 	return -1;
                   2403:     }
1.1112    www      2404:     return $answer;
1.263     www      2405: }
                   2406: 
1.1111    www      2407: #
                   2408: # Return special version number of resource if set by override, empty otherwise
                   2409: #
                   2410: sub usedversion {
                   2411:     my $fname=shift;
                   2412:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2413:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2414:     if ($urlversion) { return $urlversion; }
                   2415:     return '';
                   2416: }
                   2417: 
1.1       albertel 2418: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2419: 
1.1       albertel 2420: sub subscribe {
                   2421:     my $fname=shift;
1.761     raeburn  2422:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2423:     $fname=~s/[\n\r]//g;
1.1       albertel 2424:     my $author=$fname;
                   2425:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2426:     my ($udom,$uname)=split(/\//,$author);
                   2427:     my $home=homeserver($uname,$udom);
1.335     albertel 2428:     if ($home eq 'no_host') {
                   2429:         return 'not_found';
1.1       albertel 2430:     }
                   2431:     my $answer=reply("sub:$fname",$home);
1.64      www      2432:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2433: 	$answer.=' by '.$home;
                   2434:     }
1.1       albertel 2435:     return $answer;
                   2436: }
                   2437:     
1.8       www      2438: # -------------------------------------------------------------- Replicate file
                   2439: 
                   2440: sub repcopy {
                   2441:     my $filename=shift;
1.23      www      2442:     $filename=~s/\/+/\//g;
1.1142    raeburn  2443:     my $londocroot = $perlvar{'lonDocRoot'};
                   2444:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2445:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2446:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2447: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2448: 	return &repcopy_userfile($filename);
                   2449:     }
1.532     albertel 2450:     $filename=~s/[\n\r]//g;
1.8       www      2451:     my $transname="$filename.in.transfer";
1.828     www      2452: # FIXME: this should flock
1.607     raeburn  2453:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2454:     my $remoteurl=subscribe($filename);
1.64      www      2455:     if ($remoteurl =~ /^con_lost by/) {
                   2456: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2457:            return 'unavailable';
1.8       www      2458:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2459: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2460: 	   return 'not_found';
1.64      www      2461:     } elsif ($remoteurl =~ /^rejected by/) {
                   2462: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2463:            return 'forbidden';
1.20      www      2464:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2465:            return 'ok';
1.8       www      2466:     } else {
1.290     www      2467:         my $author=$filename;
                   2468:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2469:         my ($udom,$uname)=split(/\//,$author);
                   2470:         my $home=homeserver($uname,$udom);
                   2471:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2472:            my @parts=split(/\//,$filename);
                   2473:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2474:            if ($path ne "$londocroot/res") {
1.8       www      2475:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2476: 	       return 'bad_request';
1.8       www      2477:            }
                   2478:            my $count;
                   2479:            for ($count=5;$count<$#parts;$count++) {
                   2480:                $path.="/$parts[$count]";
                   2481:                if ((-e $path)!=1) {
                   2482: 		   mkdir($path,0777);
                   2483:                }
                   2484:            }
                   2485:            my $ua=new LWP::UserAgent;
                   2486:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2487:            my $response=$ua->request($request,$transname);
                   2488:            if ($response->is_error()) {
                   2489: 	       unlink($transname);
                   2490:                my $message=$response->status_line;
1.672     albertel 2491:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2492:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2493:                return 'unavailable';
1.8       www      2494:            } else {
1.16      www      2495: 	       if ($remoteurl!~/\.meta$/) {
                   2496:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2497:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2498:                   if ($mresponse->is_error()) {
                   2499: 		      unlink($filename.'.meta');
                   2500:                       &logthis(
1.672     albertel 2501:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2502:                   }
                   2503: 	       }
1.8       www      2504:                rename($transname,$filename);
1.607     raeburn  2505:                return 'ok';
1.8       www      2506:            }
1.290     www      2507:        }
1.8       www      2508:     }
1.330     www      2509: }
                   2510: 
                   2511: # ------------------------------------------------ Get server side include body
                   2512: sub ssi_body {
1.381     albertel 2513:     my ($filelink,%form)=@_;
1.606     matthew  2514:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2515:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2516:     }
1.953     www      2517:     my $output='';
                   2518:     my $response;
1.980     raeburn  2519:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2520:        ($output,$response)=&externalssi($filelink);
1.953     www      2521:     } else {
1.1004    droeschl 2522:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2523:        $filelink .= 'inhibitmenu=yes';
1.953     www      2524:        ($output,$response)=&ssi($filelink,%form);
                   2525:     }
1.778     albertel 2526:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2527:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2528:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2529:     if (wantarray) {
                   2530:         return ($output, $response);
                   2531:     } else {
                   2532:         return $output;
                   2533:     }
1.8       www      2534: }
                   2535: 
1.15      www      2536: # --------------------------------------------------------- Server Side Include
                   2537: 
1.782     albertel 2538: sub absolute_url {
                   2539:     my ($host_name) = @_;
                   2540:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2541:     if ($host_name eq '') {
                   2542: 	$host_name = $ENV{'SERVER_NAME'};
                   2543:     }
                   2544:     return $protocol.$host_name;
                   2545: }
                   2546: 
1.942     foxr     2547: #
                   2548: #   Server side include.
                   2549: # Parameters:
                   2550: #  fn     Possibly encrypted resource name/id.
                   2551: #  form   Hash that describes how the rendering should be done
                   2552: #         and other things.
1.944     foxr     2553: # Returns:
1.950     raeburn  2554: #   Scalar context: The content of the response.
                   2555: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2556: #     
1.15      www      2557: sub ssi {
                   2558: 
1.944     foxr     2559:     my ($fn,%form)=@_;
1.15      www      2560:     my $ua=new LWP::UserAgent;
1.23      www      2561:     my $request;
1.711     albertel 2562: 
                   2563:     $form{'no_update_last_known'}=1;
1.895     albertel 2564:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2565:     if (%form) {
1.782     albertel 2566:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2567:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2568:     } else {
1.782     albertel 2569:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2570:     }
                   2571: 
1.15      www      2572:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173  ! foxr     2573:     my $response= $ua->request($request);
        !          2574:     my $content = Encode::decode_utf8($response->content);
1.944     foxr     2575:     if (wantarray) {
1.1173  ! foxr     2576: 	return ($content, $response);
1.944     foxr     2577:     } else {
1.1173  ! foxr     2578: 	return $content;
1.942     foxr     2579:     }
1.324     www      2580: }
                   2581: 
                   2582: sub externalssi {
                   2583:     my ($url)=@_;
                   2584:     my $ua=new LWP::UserAgent;
                   2585:     my $request=new HTTP::Request('GET',$url);
                   2586:     my $response=$ua->request($request);
1.954     raeburn  2587:     if (wantarray) {
                   2588:         return ($response->content, $response);
                   2589:     } else {
                   2590:         return $response->content;
                   2591:     }
1.15      www      2592: }
1.254     www      2593: 
1.492     albertel 2594: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2595: 
                   2596: sub allowuploaded {
                   2597:     my ($srcurl,$url)=@_;
                   2598:     $url=&clutter(&declutter($url));
                   2599:     my $dir=$url;
                   2600:     $dir=~s/\/[^\/]+$//;
                   2601:     my %httpref=();
                   2602:     my $httpurl=&hreflocation('',$url);
                   2603:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2604:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2605: }
1.477     raeburn  2606: 
1.478     albertel 2607: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2608: # input: action, courseID, current domain, intended
1.637     raeburn  2609: #        path to file, source of file, instruction to parse file for objects,
                   2610: #        ref to hash for embedded objects,
                   2611: #        ref to hash for codebase of java objects.
1.1095    raeburn  2612: #        reference to scalar to accommodate mime type determined
                   2613: #          from File::MMagic if $parser = parse.
1.637     raeburn  2614: #
1.485     raeburn  2615: # output: url to file (if action was uploaddoc), 
                   2616: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2617: #
1.478     albertel 2618: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2619: # course.
1.477     raeburn  2620: #
1.478     albertel 2621: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2622: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2623: #          course's home server.
1.477     raeburn  2624: #
1.478     albertel 2625: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2626: #          be copied from $source (current location) to 
                   2627: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2628: #         and will then be copied to
                   2629: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2630: #         course's home server.
1.485     raeburn  2631: #
1.481     raeburn  2632: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2633: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2634: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2635: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2636: #         in course's home server.
1.637     raeburn  2637: #
1.477     raeburn  2638: 
                   2639: sub process_coursefile {
1.1095    raeburn  2640:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2641:         $mimetype)=@_;
1.477     raeburn  2642:     my $fetchresult;
1.638     albertel 2643:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2644:     if ($action eq 'propagate') {
1.638     albertel 2645:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2646: 			     $home);
1.481     raeburn  2647:     } else {
1.477     raeburn  2648:         my $fpath = '';
                   2649:         my $fname = $file;
1.478     albertel 2650:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2651:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2652:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2653:         if ($action eq 'copy') {
                   2654:             if ($source eq '') {
                   2655:                 $fetchresult = 'no source file';
                   2656:                 return $fetchresult;
                   2657:             } else {
                   2658:                 my $destination = $filepath.'/'.$fname;
                   2659:                 rename($source,$destination);
                   2660:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2661:                                  $home);
1.481     raeburn  2662:             }
                   2663:         } elsif ($action eq 'uploaddoc') {
                   2664:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2665:             print $fh $env{'form.'.$source};
1.481     raeburn  2666:             close($fh);
1.637     raeburn  2667:             if ($parser eq 'parse') {
1.1024    raeburn  2668:                 my $mm = new File::MMagic;
1.1095    raeburn  2669:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2670:                 if ($type eq 'text/html') {
1.1024    raeburn  2671:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2672:                     unless ($parse_result eq 'ok') {
                   2673:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2674:                     }
1.637     raeburn  2675:                 }
1.1095    raeburn  2676:                 if (ref($mimetype)) {
                   2677:                     $$mimetype = $type;
                   2678:                 } 
1.637     raeburn  2679:             }
1.477     raeburn  2680:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2681:                                  $home);
1.481     raeburn  2682:             if ($fetchresult eq 'ok') {
                   2683:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2684:             } else {
                   2685:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2686:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2687:                 return '/adm/notfound.html';
                   2688:             }
1.477     raeburn  2689:         }
                   2690:     }
1.485     raeburn  2691:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2692:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2693:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2694:     }
                   2695:     return $fetchresult;
                   2696: }
                   2697: 
1.637     raeburn  2698: sub build_filepath {
                   2699:     my ($fpath) = @_;
                   2700:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2701:     unless ($fpath eq '') {
                   2702:         my @parts=split('/',$fpath);
                   2703:         foreach my $part (@parts) {
                   2704:             $filepath.= '/'.$part;
                   2705:             if ((-e $filepath)!=1) {
                   2706:                 mkdir($filepath,0777);
                   2707:             }
                   2708:         }
                   2709:     }
                   2710:     return $filepath;
                   2711: }
                   2712: 
                   2713: sub store_edited_file {
1.638     albertel 2714:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2715:     my $file = $primary_url;
                   2716:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2717:     my $fpath = '';
                   2718:     my $fname = $file;
                   2719:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2720:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2721:     my $filepath = &build_filepath($fpath);
                   2722:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2723:     print $fh $content;
                   2724:     close($fh);
1.638     albertel 2725:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2726:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2727: 			  $home);
1.637     raeburn  2728:     if ($$fetchresult eq 'ok') {
                   2729:         return '/uploaded/'.$fpath.'/'.$fname;
                   2730:     } else {
1.638     albertel 2731:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2732: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2733:         return '/adm/notfound.html';
                   2734:     }
                   2735: }
                   2736: 
1.531     albertel 2737: sub clean_filename {
1.831     albertel 2738:     my ($fname,$args)=@_;
1.315     www      2739: # Replace Windows backslashes by forward slashes
1.257     www      2740:     $fname=~s/\\/\//g;
1.831     albertel 2741:     if (!$args->{'keep_path'}) {
                   2742:         # Get rid of everything but the actual filename
                   2743: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2744:     }
1.315     www      2745: # Replace spaces by underscores
                   2746:     $fname=~s/\s+/\_/g;
                   2747: # Replace all other weird characters by nothing
1.831     albertel 2748:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2749: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2750: # numbers
                   2751:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2752:     return $fname;
                   2753: }
1.1051    raeburn  2754: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2755: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2756: # image with the same aspect ratio as the original, but with dimensions which do 
                   2757: # not exceed $resizewidth and $resizeheight.
                   2758:  
1.984     neumanie 2759: sub resizeImage {
1.1051    raeburn  2760:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2761:     my $ima = Image::Magick->new;
                   2762:     my $resized;
                   2763:     if (-e $img_path) {
                   2764:         $ima->Read($img_path);
                   2765:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2766:             my $width = $ima->Get('width');
                   2767:             my $height = $ima->Get('height');
                   2768:             if ($width > $resizewidth) {
                   2769: 	        my $factor = $width/$resizewidth;
                   2770:                 my $newheight = $height/$factor;
                   2771:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2772:                 $resized = 1;
                   2773:             }
                   2774:         }
                   2775:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2776:             my $width = $ima->Get('width');
                   2777:             my $height = $ima->Get('height');
                   2778:             if ($height > $resizeheight) {
                   2779:                 my $factor = $height/$resizeheight;
                   2780:                 my $newwidth = $width/$factor;
                   2781:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2782:                 $resized = 1;
                   2783:             }
                   2784:         }
                   2785:         if ($resized) {
                   2786:             $ima->Write($img_path);
                   2787:         }
                   2788:     }
                   2789:     return;
1.977     amueller 2790: }
                   2791: 
1.608     albertel 2792: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2793: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2794: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2795: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2796: #                                    canceloverwrite, or ''. 
                   2797: #                   if 'coursedoc': upload to the current course
                   2798: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2799: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2800: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2801: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2802: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2803: #        $allfiles - reference to hash for embedded objects
                   2804: #        $codebase - reference to hash for codebase of java objects
                   2805: #        $desuname - username for permanent storage of uploaded file
                   2806: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2807: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2808: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2809: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2810: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2811: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2812: #                    from File::MMagic.
1.858     raeburn  2813: # 
1.686     albertel 2814: # output: url of file in userspace, or error: <message> 
                   2815: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2816: 
1.531     albertel 2817: sub userfileupload {
1.1090    raeburn  2818:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2819:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2820:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2821:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2822:     $fname=&clean_filename($fname);
1.1090    raeburn  2823:     # See if there is anything left
1.257     www      2824:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2825:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2826:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2827:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2828:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2829:         my $now = time;
1.1090    raeburn  2830:         my $filepath;
1.1095    raeburn  2831:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2832:              $filepath = 'tmp/helprequests/'.$now;
                   2833:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2834:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2835:                          '_'.$env{'user.domain'}.'/pending';
                   2836:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2837:             my ($docuname,$docudom);
                   2838:             if ($destudom) {
                   2839:                 $docudom = $destudom;
                   2840:             } else {
                   2841:                 $docudom = $env{'user.domain'};
                   2842:             }
                   2843:             if ($destuname) {
                   2844:                 $docuname = $destuname;
                   2845:             } else {
                   2846:                 $docuname = $env{'user.name'};
                   2847:             }
                   2848:             if (exists($env{'form.group'})) {
                   2849:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2850:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2851:             }
                   2852:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2853:             if ($context eq 'canceloverwrite') {
                   2854:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2855:                 if (-e  $tempfile) {
                   2856:                     my @info = stat($tempfile);
                   2857:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2858:                         unlink($tempfile);
                   2859:                     }
                   2860:                 }
                   2861:                 return;
1.523     raeburn  2862:             }
                   2863:         }
1.1090    raeburn  2864:         # Create the directory if not present
1.741     raeburn  2865:         my @parts=split(/\//,$filepath);
                   2866:         my $fullpath = $perlvar{'lonDaemons'};
                   2867:         for (my $i=0;$i<@parts;$i++) {
                   2868:             $fullpath .= '/'.$parts[$i];
                   2869:             if ((-e $fullpath)!=1) {
                   2870:                 mkdir($fullpath,0777);
                   2871:             }
                   2872:         }
                   2873:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2874:         print $fh $env{'form.'.$formname};
                   2875:         close($fh);
1.1090    raeburn  2876:         if ($context eq 'existingfile') {
                   2877:             my @info = stat($fullpath.'/'.$fname);
                   2878:             return ($fullpath.'/'.$fname,$info[9]);
                   2879:         } else {
                   2880:             return $fullpath.'/'.$fname;
                   2881:         }
1.523     raeburn  2882:     }
1.995     raeburn  2883:     if ($subdir eq 'scantron') {
                   2884:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2885:     } else {
1.995     raeburn  2886:         $fname="$subdir/$fname";
                   2887:     }
1.1090    raeburn  2888:     if ($context eq 'coursedoc') {
1.638     albertel 2889: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2890: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2891:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2892:             return &finishuserfileupload($docuname,$docudom,
                   2893: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2894: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2895:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2896:         } else {
1.620     albertel 2897:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2898:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2899: 				       $fname,$formname,$parser,
1.1095    raeburn  2900: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2901:         }
1.719     banghart 2902:     } elsif (defined($destuname)) {
                   2903:         my $docuname=$destuname;
                   2904:         my $docudom=$destudom;
1.860     raeburn  2905: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2906: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2907:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2908:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2909:     } else {
1.638     albertel 2910:         my $docuname=$env{'user.name'};
                   2911:         my $docudom=$env{'user.domain'};
1.714     raeburn  2912:         if (exists($env{'form.group'})) {
                   2913:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2914:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2915:         }
1.860     raeburn  2916: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2917: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2918:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2919:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2920:     }
1.271     www      2921: }
                   2922: 
                   2923: sub finishuserfileupload {
1.860     raeburn  2924:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2925:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2926:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2927:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2928:   
1.860     raeburn  2929:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2930:     $file=$fname;
                   2931:     if ($fname=~m|/|) {
                   2932:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2933: 	$path.=$fnamepath.'/';
                   2934:     }
1.259     www      2935:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2936:     my $count;
                   2937:     for ($count=4;$count<=$#parts;$count++) {
                   2938:         $filepath.="/$parts[$count]";
                   2939:         if ((-e $filepath)!=1) {
                   2940: 	    mkdir($filepath,0777);
                   2941:         }
                   2942:     }
1.984     neumanie 2943: 
1.258     www      2944: # Save the file
                   2945:     {
1.701     albertel 2946: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2947: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2948: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2949: 	    return '/adm/notfound.html';
                   2950: 	}
1.1090    raeburn  2951:         if ($context eq 'overwrite') {
1.1117    foxr     2952:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2953:             my $target = $filepath.'/'.$file;
                   2954:             if (-e $source) {
                   2955:                 my @info = stat($source);
                   2956:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2957:                     unless (&File::Copy::move($source,$target)) {
                   2958:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2959:                         return "Moving from $source failed";
                   2960:                     }
                   2961:                 } else {
                   2962:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2963:                 }
                   2964:             } else {
                   2965:                 return "Temporary file: $source missing";
                   2966:             }
                   2967:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2968: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2969: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2970: 	    return '/adm/notfound.html';
                   2971: 	}
1.570     albertel 2972: 	close(FH);
1.1051    raeburn  2973:         if ($resizewidth && $resizeheight) {
                   2974:             my $mm = new File::MMagic;
                   2975:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2976:             if ($mime_type =~ m{^image/}) {
                   2977: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2978:             }  
1.977     amueller 2979: 	}
1.258     www      2980:     }
1.1152    raeburn  2981:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2982:         if (ref($mimetype)) {
                   2983:             if ($$mimetype eq '') {
                   2984:                 my $mm = new File::MMagic;
                   2985:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2986:                 $$mimetype = $type;
                   2987:             }
                   2988:         }
                   2989:     }
1.637     raeburn  2990:     if ($parser eq 'parse') {
1.1152    raeburn  2991:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  2992:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2993:                                                        $allfiles,$codebase);
                   2994:             unless ($parse_result eq 'ok') {
                   2995:                 &logthis('Failed to parse '.$filepath.$file.
                   2996: 	   	         ' for embedded media: '.$parse_result); 
                   2997:             }
1.637     raeburn  2998:         }
                   2999:     }
1.860     raeburn  3000:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3001:         my $input = $filepath.'/'.$file;
                   3002:         my $output = $filepath.'/'.'tn-'.$file;
                   3003:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3004:         system("convert -sample $thumbsize $input $output");
                   3005:         if (-e $filepath.'/'.'tn-'.$file) {
                   3006:             $fetchthumb  = 1; 
                   3007:         }
                   3008:     }
1.858     raeburn  3009:  
1.259     www      3010: # Notify homeserver to grep it
                   3011: #
1.984     neumanie 3012:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3013:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3014:     if ($fetchresult eq 'ok') {
1.860     raeburn  3015:         if ($fetchthumb) {
                   3016:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3017:             if ($thumbresult ne 'ok') {
                   3018:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3019:                          $docuhome.': '.$thumbresult);
                   3020:             }
                   3021:         }
1.259     www      3022: #
1.258     www      3023: # Return the URL to it
1.494     albertel 3024:         return '/uploaded/'.$path.$file;
1.263     www      3025:     } else {
1.494     albertel 3026:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3027: 		 ': '.$fetchresult);
1.263     www      3028:         return '/adm/notfound.html';
1.858     raeburn  3029:     }
1.493     albertel 3030: }
                   3031: 
1.637     raeburn  3032: sub extract_embedded_items {
1.961     raeburn  3033:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3034:     my @state = ();
1.1164    raeburn  3035:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3036:     my %javafiles = (
                   3037:                       codebase => '',
                   3038:                       code => '',
                   3039:                       archive => ''
                   3040:                     );
                   3041:     my %mediafiles = (
                   3042:                       src => '',
                   3043:                       movie => '',
                   3044:                      );
1.648     raeburn  3045:     my $p;
                   3046:     if ($content) {
                   3047:         $p = HTML::LCParser->new($content);
                   3048:     } else {
1.961     raeburn  3049:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3050:     }
1.641     albertel 3051:     while (my $t=$p->get_token()) {
1.640     albertel 3052: 	if ($t->[0] eq 'S') {
                   3053: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3054: 	    push(@state, $tagname);
1.648     raeburn  3055:             if (lc($tagname) eq 'allow') {
                   3056:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3057:             }
1.640     albertel 3058: 	    if (lc($tagname) eq 'img') {
                   3059: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3060: 	    }
1.886     albertel 3061: 	    if (lc($tagname) eq 'a') {
                   3062: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3063: 	    }
1.645     raeburn  3064:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3065:                 my $src;
1.645     raeburn  3066:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3067:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3068:                 } else {
1.1164    raeburn  3069:                     if ($attr->{'src'} ne '') {
                   3070:                         $src = $attr->{'src'};
                   3071:                         &add_filetype($allfiles,$src,'src');
                   3072:                     }
                   3073:                 }
                   3074:                 my $text = $p->get_trimmed_text();
                   3075:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3076:                     my @swfargs = split(/,/,$1);
                   3077:                     foreach my $item (@swfargs) {
                   3078:                         $item =~ s/["']//g;
                   3079:                         $item =~ s/^\s+//;
                   3080:                         $item =~ s/\s+$//;
                   3081:                     }
                   3082:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3083:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3084:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3085:                         } else {
                   3086:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3087:                         }
                   3088:                     }
1.645     raeburn  3089:                 }
                   3090:             }
                   3091:             if (lc($tagname) eq 'link') {
                   3092:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3093:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3094:                 }
                   3095:             }
1.640     albertel 3096: 	    if (lc($tagname) eq 'object' ||
                   3097: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3098: 		foreach my $item (keys(%javafiles)) {
                   3099: 		    $javafiles{$item} = '';
                   3100: 		}
1.1164    raeburn  3101:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3102:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3103:                 }
1.640     albertel 3104: 	    }
                   3105: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3106: 		my $name = lc($attr->{'name'});
                   3107: 		foreach my $item (keys(%javafiles)) {
                   3108: 		    if ($name eq $item) {
                   3109: 			$javafiles{$item} = $attr->{'value'};
                   3110: 			last;
                   3111: 		    }
                   3112: 		}
1.1164    raeburn  3113:                 my $pathfrom;
1.640     albertel 3114: 		foreach my $item (keys(%mediafiles)) {
                   3115: 		    if ($name eq $item) {
1.1164    raeburn  3116:                         $pathfrom = $attr->{'value'};
                   3117:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3118: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3119: 			last;
                   3120: 		    }
                   3121: 		}
1.1164    raeburn  3122:                 if ($name eq 'flashvars') {
                   3123:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3124:                 }
                   3125:                 if ($pathfrom ne '') {
                   3126:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3127:                                          $pathfrom);
                   3128:                 }
1.640     albertel 3129: 	    }
                   3130: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3131: 		foreach my $item (keys(%javafiles)) {
                   3132: 		    if ($attr->{$item}) {
                   3133: 			$javafiles{$item} = $attr->{$item};
                   3134: 			last;
                   3135: 		    }
                   3136: 		}
                   3137: 		foreach my $item (keys(%mediafiles)) {
                   3138: 		    if ($attr->{$item}) {
                   3139: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3140: 			last;
                   3141: 		    }
                   3142: 		}
1.1164    raeburn  3143:                 if (lc($tagname) eq 'embed') {
                   3144:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3145:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3146:                                              $attr->{'src'});
                   3147:                     }
                   3148:                 }
1.640     albertel 3149: 	    }
1.1164    raeburn  3150:             if ($t->[4] =~ m{/>$}) {
                   3151:                 pop(@state);  
                   3152:             }
1.640     albertel 3153: 	} elsif ($t->[0] eq 'E') {
                   3154: 	    my ($tagname) = ($t->[1]);
                   3155: 	    if ($javafiles{'codebase'} ne '') {
                   3156: 		$javafiles{'codebase'} .= '/';
                   3157: 	    }  
                   3158: 	    if (lc($tagname) eq 'applet' ||
                   3159: 		lc($tagname) eq 'object' ||
                   3160: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3161: 		) {
                   3162: 		foreach my $item (keys(%javafiles)) {
                   3163: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3164: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3165: 			&add_filetype($allfiles,$file,$item);
                   3166: 		    }
                   3167: 		}
                   3168: 	    } 
                   3169: 	    pop @state;
                   3170: 	}
                   3171:     }
1.1164    raeburn  3172:     foreach my $id (sort(keys(%flashvars))) {
                   3173:         if ($shockwave{$id} ne '') {
                   3174:             my @pairs = split(/\&/,$flashvars{$id});
                   3175:             foreach my $pair (@pairs) {
                   3176:                 my ($key,$value) = split(/\=/,$pair);
                   3177:                 if ($key eq 'thumb') {
                   3178:                     &add_filetype($allfiles,$value,$key);
                   3179:                 } elsif ($key eq 'content') {
                   3180:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3181:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3182:                     if ($ext ne '') {
                   3183:                         &add_filetype($allfiles,$path.$value,$ext);
                   3184:                     }
                   3185:                 }
                   3186:             }
                   3187:         }
                   3188:     }
1.637     raeburn  3189:     return 'ok';
                   3190: }
                   3191: 
1.639     albertel 3192: sub add_filetype {
                   3193:     my ($allfiles,$file,$type)=@_;
                   3194:     if (exists($allfiles->{$file})) {
                   3195: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3196: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3197: 	}
                   3198:     } else {
                   3199: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3200:     }
                   3201: }
                   3202: 
1.1164    raeburn  3203: sub embedded_dependency {
                   3204:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3205:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3206:         if (($identifier ne '') &&
                   3207:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3208:             ($pathfrom ne '')) {
                   3209:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3210:             foreach my $dep (@{$related->{$identifier}}) {
                   3211:                 &add_filetype($allfiles,$path.$dep,'object');
                   3212:             }
                   3213:         }
                   3214:     }
                   3215:     return;
                   3216: }
                   3217: 
1.493     albertel 3218: sub removeuploadedurl {
1.984     neumanie 3219:     my ($url)=@_;	
                   3220:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3221:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3222: }
                   3223: 
                   3224: sub removeuserfile {
                   3225:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3226:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3227:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3228:     if ($result eq 'ok') {	
1.798     raeburn  3229:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3230:             my $metafile = $fname.'.meta';
                   3231:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3232: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3233:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3234:             my $sqlresult = 
1.823     albertel 3235:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3236:                                         'portfolio_metadata',$group,
                   3237:                                         'delete');
1.798     raeburn  3238:         }
                   3239:     }
                   3240:     return $result;
1.257     www      3241: }
1.15      www      3242: 
1.530     albertel 3243: sub mkdiruserfile {
                   3244:     my ($docuname,$docudom,$dir)=@_;
                   3245:     my $home=&homeserver($docuname,$docudom);
                   3246:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3247: }
                   3248: 
1.531     albertel 3249: sub renameuserfile {
                   3250:     my ($docuname,$docudom,$old,$new)=@_;
                   3251:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3252:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3253:                         &escape("$old").':'.&escape("$new"),$home);
                   3254:     if ($result eq 'ok') {
                   3255:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3256:             my $oldmeta = $old.'.meta';
                   3257:             my $newmeta = $new.'.meta';
                   3258:             my $metaresult = 
                   3259:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3260: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3261:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3262:             my $sqlresult = 
1.823     albertel 3263:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3264:                                         'portfolio_metadata',$group,
                   3265:                                         'delete');
1.798     raeburn  3266:         }
                   3267:     }
                   3268:     return $result;
1.531     albertel 3269: }
                   3270: 
1.14      www      3271: # ------------------------------------------------------------------------- Log
                   3272: 
                   3273: sub log {
                   3274:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3275:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3276: }
                   3277: 
                   3278: # ------------------------------------------------------------------ Course Log
1.352     www      3279: #
                   3280: # This routine flushes several buffers of non-mission-critical nature
                   3281: #
1.157     www      3282: 
                   3283: sub flushcourselogs {
1.352     www      3284:     &logthis('Flushing log buffers');
                   3285: #
                   3286: # course logs
                   3287: # This is a log of all transactions in a course, which can be used
                   3288: # for data mining purposes
                   3289: #
                   3290: # It also collects the courseid database, which lists last transaction
                   3291: # times and course titles for all courseids
                   3292: #
                   3293:     my %courseidbuffer=();
1.921     raeburn  3294:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3295:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3296: 		          &escape($courselogs{$crsid}),
                   3297: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3298: 	    delete $courselogs{$crsid};
                   3299:         } else {
                   3300:             &logthis('Failed to flush log buffer for '.$crsid);
                   3301:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3302:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3303:                         " exceeded maximum size, deleting.</font>");
                   3304:                delete $courselogs{$crsid};
                   3305:             }
1.352     www      3306:         }
1.920     raeburn  3307:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3308:             'description' => $coursedescrbuf{$crsid},
                   3309:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3310:             'type'        => $coursetypebuf{$crsid},
                   3311:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3312:         };
1.191     harris41 3313:     }
1.352     www      3314: #
                   3315: # Write course id database (reverse lookup) to homeserver of courses 
                   3316: # Is used in pickcourse
                   3317: #
1.840     albertel 3318:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3319:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3320:                                     $courseidbuffer{$crs_home},
                   3321:                                     $crs_home,'timeonly');
1.352     www      3322:     }
                   3323: #
                   3324: # File accesses
                   3325: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3326: #
1.449     matthew  3327:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3328:         if ($entry =~ /___count$/) {
                   3329:             my ($dom,$name);
1.807     albertel 3330:             ($dom,$name,undef)=
1.811     albertel 3331: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3332:             if (! defined($dom) || $dom eq '' || 
                   3333:                 ! defined($name) || $name eq '') {
1.620     albertel 3334:                 my $cid = $env{'request.course.id'};
                   3335:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3336:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3337:             }
1.450     matthew  3338:             my $value = $accesshash{$entry};
                   3339:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3340:             my %temphash=($url => $value);
1.449     matthew  3341:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3342:             if ($result eq 'ok') {
                   3343:                 delete $accesshash{$entry};
                   3344:             }
                   3345:         } else {
1.811     albertel 3346:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3347:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3348:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3349:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3350:                 delete $accesshash{$entry};
                   3351:             }
1.185     www      3352:         }
1.191     harris41 3353:     }
1.352     www      3354: #
                   3355: # Roles
                   3356: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3357: #
1.800     albertel 3358:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3359:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3360: 	    split(/\:/,$entry);
                   3361:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3362:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3363:                 $rudom,$runame) eq 'ok') {
                   3364: 	    delete $userrolehash{$entry};
                   3365:         }
                   3366:     }
1.662     raeburn  3367: #
                   3368: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3369: #
                   3370:     my %domrolebuffer = ();
1.1000    raeburn  3371:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3372:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3373:         if ($domrolebuffer{$rudom}) {
                   3374:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3375:                       '='.&escape($domainrolehash{$entry});
                   3376:         } else {
                   3377:             $domrolebuffer{$rudom}.=&escape($entry).
                   3378:                       '='.&escape($domainrolehash{$entry});
                   3379:         }
                   3380:         delete $domainrolehash{$entry};
                   3381:     }
                   3382:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3383: 	my %servers = &get_servers($dom,'library');
                   3384: 	foreach my $tryserver (keys(%servers)) {
                   3385: 	    unless (&reply('domroleput:'.$dom.':'.
                   3386: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3387: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3388: 	    }
1.662     raeburn  3389:         }
                   3390:     }
1.186     www      3391:     $dumpcount++;
1.157     www      3392: }
                   3393: 
                   3394: sub courselog {
                   3395:     my $what=shift;
1.158     www      3396:     $what=time.':'.$what;
1.620     albertel 3397:     unless ($env{'request.course.id'}) { return ''; }
                   3398:     $coursedombuf{$env{'request.course.id'}}=
                   3399:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3400:     $coursenumbuf{$env{'request.course.id'}}=
                   3401:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3402:     $coursehombuf{$env{'request.course.id'}}=
                   3403:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3404:     $coursedescrbuf{$env{'request.course.id'}}=
                   3405:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3406:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3407:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3408:     $courseownerbuf{$env{'request.course.id'}}=
                   3409:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3410:     $coursetypebuf{$env{'request.course.id'}}=
                   3411:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3412:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3413: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3414:     } else {
1.620     albertel 3415: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3416:     }
1.620     albertel 3417:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3418: 	&flushcourselogs();
                   3419:     }
1.158     www      3420: }
                   3421: 
                   3422: sub courseacclog {
                   3423:     my $fnsymb=shift;
1.620     albertel 3424:     unless ($env{'request.course.id'}) { return ''; }
                   3425:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3426:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3427:         $what.=':POST';
1.583     matthew  3428:         # FIXME: Probably ought to escape things....
1.800     albertel 3429: 	foreach my $key (keys(%env)) {
                   3430:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3431:                 my $formitem = $1;
                   3432:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3433:                     $what.=':'.$formitem.'='.$env{$key};
                   3434:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3435:                     $what.=':'.$formitem.'='.$env{$key};
                   3436:                 }
1.158     www      3437:             }
1.191     harris41 3438:         }
1.583     matthew  3439:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3440:         # FIXME: We should not be depending on a form parameter that someone
                   3441:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3442:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3443:             $what.= ':POST';
                   3444:             # FIXME: Probably ought to escape things....
                   3445:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3446:                                  'crsdiscuss') {
1.620     albertel 3447:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3448:             }
                   3449:         }
1.158     www      3450:     }
                   3451:     &courselog($what);
1.149     www      3452: }
                   3453: 
1.185     www      3454: sub countacc {
                   3455:     my $url=&declutter(shift);
1.458     matthew  3456:     return if (! defined($url) || $url eq '');
1.620     albertel 3457:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3458: #
                   3459: # Mark that this url was used in this course
                   3460: #
1.620     albertel 3461:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3462: #
                   3463: # Increase the access count for this resource in this child process
                   3464: #
1.281     www      3465:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3466:     $accesshash{$key}++;
1.185     www      3467: }
1.349     www      3468: 
1.361     www      3469: sub linklog {
                   3470:     my ($from,$to)=@_;
                   3471:     $from=&declutter($from);
                   3472:     $to=&declutter($to);
                   3473:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3474:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3475: }
1.1160    www      3476: 
                   3477: sub statslog {
                   3478:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3479:     if ($users<2) { return; }
                   3480:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3481:             'course'       => $env{'request.course.id'},
                   3482:             'sections'     => '"all"',
                   3483:             'num_students' => $users,
                   3484:             'part'         => $part,
                   3485:             'symb'         => $symb,
                   3486:             'mean_tries'   => $av_attempts,
                   3487:             'deg_of_diff'  => $degdiff});
                   3488:     foreach my $key (keys(%dynstore)) {
                   3489:         $accesshash{$key}=$dynstore{$key};
                   3490:     }
                   3491: }
1.361     www      3492:   
1.349     www      3493: sub userrolelog {
                   3494:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3495:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3496:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3497:        $userrolehash
                   3498:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3499:                     =$tend.':'.$tstart;
1.662     raeburn  3500:     }
1.1169    droeschl 3501:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3502:        $userrolehash
                   3503:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3504:                     =$tend.':'.$tstart;
                   3505:     }
1.1169    droeschl 3506:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3507:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3508:        $domainrolehash
                   3509:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3510:                     = $tend.':'.$tstart;
                   3511:     }
1.351     www      3512: }
                   3513: 
1.957     raeburn  3514: sub courserolelog {
                   3515:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3516:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3517:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3518:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3519:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3520:         ($trole eq 'co')) {
1.957     raeburn  3521:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3522:             my $cdom = $1;
                   3523:             my $cnum = $2;
                   3524:             my $sec = $3;
                   3525:             my $namespace = 'rolelog';
                   3526:             my %storehash = (
                   3527:                                role    => $trole,
                   3528:                                start   => $tstart,
                   3529:                                end     => $tend,
                   3530:                                selfenroll => $selfenroll,
                   3531:                                context    => $context,
                   3532:                             );
                   3533:             if ($trole eq 'gr') {
                   3534:                 $namespace = 'groupslog';
                   3535:                 $storehash{'group'} = $sec;
                   3536:             } else {
                   3537:                 $storehash{'section'} = $sec;
                   3538:             }
                   3539:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3540:             if (($trole ne 'st') || ($sec ne '')) {
                   3541:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3542:             }
1.957     raeburn  3543:         }
                   3544:     }
                   3545:     return;
                   3546: }
                   3547: 
1.351     www      3548: sub get_course_adv_roles {
1.948     raeburn  3549:     my ($cid,$codes) = @_;
1.620     albertel 3550:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3551:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3552:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3553:     my %nothide=();
1.800     albertel 3554:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3555:         if ($user !~ /:/) {
                   3556: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3557:         } else {
                   3558:             $nothide{$user}=1;
                   3559:         }
1.470     www      3560:     }
1.351     www      3561:     my %returnhash=();
                   3562:     my %dumphash=
                   3563:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3564:     my $now=time;
1.997     raeburn  3565:     my %privileged;
1.1000    raeburn  3566:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3567: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3568:         if (($tstart) && ($tstart<0)) { next; }
                   3569:         if (($tend) && ($tend<$now)) { next; }
                   3570:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3571:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3572: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3573:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3574:             my %dompersonnel =
1.998     raeburn  3575:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3576:             $privileged{$domain} = {};
                   3577:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3578:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3579:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3580:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3581:                         $privileged{$udom}{$uname} = 1;
                   3582:                     }
                   3583:                 }
                   3584:             }
                   3585:         }
                   3586:         if ((exists($privileged{$domain}{$username})) && 
                   3587:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3588: 	if ($role eq 'cr') { next; }
1.948     raeburn  3589:         if ($codes) {
                   3590:             if ($section) { $role .= ':'.$section; }
                   3591:             if ($returnhash{$role}) {
                   3592:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3593:             } else {
                   3594:                 $returnhash{$role}=$username.':'.$domain;
                   3595:             }
1.351     www      3596:         } else {
1.988     raeburn  3597:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3598:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3599:             if ($returnhash{$key}) {
                   3600: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3601:             } else {
                   3602:                 $returnhash{$key}=$username.':'.$domain;
                   3603:             }
1.351     www      3604:         }
1.948     raeburn  3605:     }
1.400     www      3606:     return %returnhash;
                   3607: }
                   3608: 
                   3609: sub get_my_roles {
1.937     raeburn  3610:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3611:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3612:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3613:     my (%dumphash,%nothide);
1.1086    raeburn  3614:     if ($context eq 'userroles') {
1.1166    raeburn  3615:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3616:     } else {
                   3617:         %dumphash=
1.400     www      3618:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3619:         if ($hidepriv) {
                   3620:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3621:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3622:                 if ($user !~ /:/) {
                   3623:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3624:                 } else {
                   3625:                     $nothide{$user} = 1;
                   3626:                 }
                   3627:             }
                   3628:         }
1.858     raeburn  3629:     }
1.400     www      3630:     my %returnhash=();
                   3631:     my $now=time;
1.999     raeburn  3632:     my %privileged;
1.800     albertel 3633:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3634:         my ($role,$tend,$tstart);
                   3635:         if ($context eq 'userroles') {
1.1149    raeburn  3636:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3637: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3638:         } else {
                   3639:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3640:         }
1.400     www      3641:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3642:         my $status = 'active';
1.939     raeburn  3643:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3644:             $status = 'previous';
                   3645:         } 
                   3646:         if (($tstart) && ($now<$tstart)) {
                   3647:             $status = 'future';
                   3648:         }
                   3649:         if (ref($types) eq 'ARRAY') {
                   3650:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3651:                 next;
                   3652:             } 
                   3653:         } else {
                   3654:             if ($status ne 'active') {
                   3655:                 next;
                   3656:             }
                   3657:         }
1.867     raeburn  3658:         my ($rolecode,$username,$domain,$section,$area);
                   3659:         if ($context eq 'userroles') {
                   3660:             ($area,$rolecode) = split(/_/,$entry);
                   3661:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3662:         } else {
                   3663:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3664:         }
1.832     raeburn  3665:         if (ref($roledoms) eq 'ARRAY') {
                   3666:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3667:                 next;
                   3668:             }
                   3669:         }
                   3670:         if (ref($roles) eq 'ARRAY') {
                   3671:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3672:                 if ($role =~ /^cr\//) {
                   3673:                     if (!grep(/^cr$/,@{$roles})) {
                   3674:                         next;
                   3675:                     }
1.1104    raeburn  3676:                 } elsif ($role =~ /^gr\//) {
                   3677:                     if (!grep(/^gr$/,@{$roles})) {
                   3678:                         next;
                   3679:                     }
1.922     raeburn  3680:                 } else {
                   3681:                     next;
                   3682:                 }
1.832     raeburn  3683:             }
1.867     raeburn  3684:         }
1.937     raeburn  3685:         if ($hidepriv) {
1.999     raeburn  3686:             if ($context eq 'userroles') {
                   3687:                 if ((&privileged($username,$domain)) &&
                   3688:                     (!$nothide{$username.':'.$domain})) {
                   3689:                     next;
                   3690:                 }
                   3691:             } else {
                   3692:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3693:                     my %dompersonnel =
                   3694:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3695:                     $privileged{$domain} = {};
                   3696:                     if (keys(%dompersonnel)) {
                   3697:                         foreach my $server (keys(%dompersonnel)) {
                   3698:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3699:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3700:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3701:                                     $privileged{$udom}{$uname} = $trole;
                   3702:                                 }
                   3703:                             }
                   3704:                         }
                   3705:                     }
                   3706:                 }
                   3707:                 if (exists($privileged{$domain}{$username})) {
                   3708:                     if (!$nothide{$username.':'.$domain}) {
                   3709:                         next;
                   3710:                     }
                   3711:                 }
1.937     raeburn  3712:             }
                   3713:         }
1.933     raeburn  3714:         if ($withsec) {
                   3715:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3716:                 $tstart.':'.$tend;
                   3717:         } else {
                   3718:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3719:         }
1.832     raeburn  3720:     }
1.373     www      3721:     return %returnhash;
1.399     www      3722: }
                   3723: 
                   3724: # ----------------------------------------------------- Frontpage Announcements
                   3725: #
                   3726: #
                   3727: 
                   3728: sub postannounce {
                   3729:     my ($server,$text)=@_;
1.844     albertel 3730:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3731:     unless ($text=~/\w/) { $text=''; }
                   3732:     return &reply('setannounce:'.&escape($text),$server);
                   3733: }
                   3734: 
                   3735: sub getannounce {
1.448     albertel 3736: 
                   3737:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3738: 	my $announcement='';
1.800     albertel 3739: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3740: 	close($fh);
1.399     www      3741: 	if ($announcement=~/\w/) { 
                   3742: 	    return 
                   3743:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3744:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3745: 	} else {
                   3746: 	    return '';
                   3747: 	}
                   3748:     } else {
                   3749: 	return '';
                   3750:     }
1.351     www      3751: }
1.353     www      3752: 
                   3753: # ---------------------------------------------------------- Course ID routines
                   3754: # Deal with domain's nohist_courseid.db files
                   3755: #
                   3756: 
                   3757: sub courseidput {
1.921     raeburn  3758:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3759:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3760:     my $outcome;
                   3761:     if ($caller eq 'timeonly') {
                   3762:         my $cids = '';
                   3763:         foreach my $item (keys(%$storehash)) {
                   3764:             $cids.=&escape($item).'&';
                   3765:         }
                   3766:         $cids=~s/\&$//;
                   3767:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3768:                           $coursehome);       
                   3769:     } else {
                   3770:         my $items = '';
                   3771:         foreach my $item (keys(%$storehash)) {
                   3772:             $items.= &escape($item).'='.
                   3773:                      &freeze_escape($$storehash{$item}).'&';
                   3774:         }
                   3775:         $items=~s/\&$//;
                   3776:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3777:                           $coursehome);
1.918     raeburn  3778:     }
                   3779:     if ($outcome eq 'unknown_cmd') {
                   3780:         my $what;
                   3781:         foreach my $cid (keys(%$storehash)) {
                   3782:             $what .= &escape($cid).'=';
1.921     raeburn  3783:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3784:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3785:             }
                   3786:             $what =~ s/\:$/&/;
                   3787:         }
                   3788:         $what =~ s/\&$//;  
                   3789:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3790:     } else {
                   3791:         return $outcome;
                   3792:     }
1.353     www      3793: }
                   3794: 
                   3795: sub courseiddump {
1.921     raeburn  3796:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3797:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3798:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3799:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3800:     my $as_hash = 1;
                   3801:     my %returnhash;
                   3802:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3803:     my %libserv = &all_library();
                   3804:     foreach my $tryserver (keys(%libserv)) {
                   3805:         if ( (  $hostidflag == 1 
                   3806: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3807: 	     || (!defined($hostidflag)) ) {
                   3808: 
1.918     raeburn  3809: 	    if (($domfilter eq '') ||
                   3810: 		(&host_domain($tryserver) eq $domfilter)) {
                   3811:                 my $rep = 
                   3812:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3813:                          $sincefilter.':'.&escape($descfilter).':'.
                   3814:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3815:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3816:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3817:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3818:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3819:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3820:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3821:                          &escape($creationcontext).':'.$domcloner,
                   3822:                          $tryserver);
1.918     raeburn  3823:                 my @pairs=split(/\&/,$rep);
                   3824:                 foreach my $item (@pairs) {
                   3825:                     my ($key,$value)=split(/\=/,$item,2);
                   3826:                     $key = &unescape($key);
                   3827:                     next if ($key =~ /^error: 2 /);
                   3828:                     my $result = &thaw_unescape($value);
                   3829:                     if (ref($result) eq 'HASH') {
                   3830:                         $returnhash{$key}=$result;
                   3831:                     } else {
1.921     raeburn  3832:                         my @responses = split(/:/,$value);
                   3833:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3834:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3835:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3836:                         }
1.1008    raeburn  3837:                     }
1.353     www      3838:                 }
                   3839:             }
                   3840:         }
                   3841:     }
                   3842:     return %returnhash;
                   3843: }
                   3844: 
1.1055    raeburn  3845: sub courselastaccess {
                   3846:     my ($cdom,$cnum,$hostidref) = @_;
                   3847:     my %returnhash;
                   3848:     if ($cdom && $cnum) {
                   3849:         my $chome = &homeserver($cnum,$cdom);
                   3850:         if ($chome ne 'no_host') {
                   3851:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3852:             &extract_lastaccess(\%returnhash,$rep);
                   3853:         }
                   3854:     } else {
                   3855:         if (!$cdom) { $cdom=''; }
                   3856:         my %libserv = &all_library();
                   3857:         foreach my $tryserver (keys(%libserv)) {
                   3858:             if (ref($hostidref) eq 'ARRAY') {
                   3859:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3860:             } 
                   3861:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3862:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3863:                 &extract_lastaccess(\%returnhash,$rep);
                   3864:             }
                   3865:         }
                   3866:     }
                   3867:     return %returnhash;
                   3868: }
                   3869: 
                   3870: sub extract_lastaccess {
                   3871:     my ($returnhash,$rep) = @_;
                   3872:     if (ref($returnhash) eq 'HASH') {
                   3873:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3874:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3875:                  $rep eq '') {
                   3876:             my @pairs=split(/\&/,$rep);
                   3877:             foreach my $item (@pairs) {
                   3878:                 my ($key,$value)=split(/\=/,$item,2);
                   3879:                 $key = &unescape($key);
                   3880:                 next if ($key =~ /^error: 2 /);
                   3881:                 $returnhash->{$key} = &thaw_unescape($value);
                   3882:             }
                   3883:         }
                   3884:     }
                   3885:     return;
                   3886: }
                   3887: 
1.658     raeburn  3888: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3889: 
                   3890: sub dcmailput {
1.685     raeburn  3891:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3892:     my $status = &Apache::lonnet::critical(
1.740     www      3893:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3894:        &escape($message),$server);
1.662     raeburn  3895:     return $status;
                   3896: }
                   3897: 
1.658     raeburn  3898: sub dcmaildump {
                   3899:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3900:     my %returnhash=();
1.846     albertel 3901: 
                   3902:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3903:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3904:                                                          &escape($enddate).':';
                   3905: 	my @esc_senders=map { &escape($_)} @$senders;
                   3906: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3907: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3908:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3909:             if (($key) && ($value)) {
                   3910:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3911:             }
                   3912:         }
                   3913:     }
                   3914:     return %returnhash;
                   3915: }
1.662     raeburn  3916: # ---------------------------------------------------------- Domain roles
                   3917: 
                   3918: sub get_domain_roles {
                   3919:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3920:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3921:         $startdate = '.';
                   3922:     }
1.1018    raeburn  3923:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3924:         $enddate = '.';
                   3925:     }
1.922     raeburn  3926:     my $rolelist;
                   3927:     if (ref($roles) eq 'ARRAY') {
                   3928:         $rolelist = join(':',@{$roles});
                   3929:     }
1.662     raeburn  3930:     my %personnel = ();
1.841     albertel 3931: 
                   3932:     my %servers = &get_servers($dom,'library');
                   3933:     foreach my $tryserver (keys(%servers)) {
                   3934: 	%{$personnel{$tryserver}}=();
                   3935: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3936: 					    &escape($startdate).':'.
                   3937: 					    &escape($enddate).':'.
                   3938: 					    &escape($rolelist), $tryserver))) {
                   3939: 	    my ($key,$value) = split(/\=/,$line,2);
                   3940: 	    if (($key) && ($value)) {
                   3941: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3942: 	    }
                   3943: 	}
1.662     raeburn  3944:     }
                   3945:     return %personnel;
                   3946: }
1.658     raeburn  3947: 
1.1057    www      3948: # ----------------------------------------------------------- Interval timing 
1.149     www      3949: 
1.1153    www      3950: {
                   3951: # Caches needed for speedup of navmaps
                   3952: # We don't want to cache this for very long at all (5 seconds at most)
                   3953: # 
                   3954: # The user for whom we cache
                   3955: my $cachedkey='';
                   3956: # The cached times for this user
                   3957: my %cachedtimes=();
                   3958: # When this was last done
                   3959: my $cachedtime=();
                   3960: 
                   3961: sub load_all_first_access {
1.1154    raeburn  3962:     my ($uname,$udom)=@_;
1.1156    www      3963:     if (($cachedkey eq $uname.':'.$udom) &&
1.1154    raeburn  3964:         (abs($cachedtime-time)<5)) {
                   3965:         return;
                   3966:     }
                   3967:     $cachedtime=time;
                   3968:     $cachedkey=$uname.':'.$udom;
                   3969:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3970: }
                   3971: 
1.504     albertel 3972: sub get_first_access {
1.1162    raeburn  3973:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 3974:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3975:     if ($argsymb) { $symb=$argsymb; }
                   3976:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  3977:     if ($argmap) { $map = $argmap; }
1.926     albertel 3978:     if ($type eq 'course') {
                   3979: 	$res='course';
                   3980:     } elsif ($type eq 'map') {
1.588     albertel 3981: 	$res=&symbread($map);
                   3982:     } else {
                   3983: 	$res=$symb;
                   3984:     }
1.1153    www      3985:     &load_all_first_access($uname,$udom);
                   3986:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3987: }
                   3988: 
                   3989: sub set_first_access {
1.1162    raeburn  3990:     my ($type,$interval)=@_;
1.790     albertel 3991:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3992:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3993:     if ($type eq 'course') {
                   3994: 	$res='course';
                   3995:     } elsif ($type eq 'map') {
1.588     albertel 3996: 	$res=&symbread($map);
                   3997:     } else {
                   3998: 	$res=$symb;
                   3999:     }
1.1153    www      4000:     $cachedkey='';
1.1162    raeburn  4001:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4002:     if (!$firstaccess) {
1.1162    raeburn  4003:         my $start = time;
                   4004: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4005:                           $udom,$uname);
                   4006:         if ($putres eq 'ok') {
                   4007:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4008:                  $udom,$uname); 
                   4009:             &appenv(
                   4010:                      {
                   4011:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4012:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4013:                      }
                   4014:                   );
                   4015:         }
                   4016:         return $putres;
1.505     albertel 4017:     }
                   4018:     return 'already_set';
1.504     albertel 4019: }
1.1153    www      4020: }
1.110     www      4021: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4022: 
                   4023: sub expirespread {
                   4024:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4025:     my $cid=$env{'request.course.id'}; 
1.110     www      4026:     if ($cid) {
                   4027:        my $now=time;
                   4028:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4029:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4030:                             $env{'course.'.$cid.'.num'}.
1.110     www      4031: 	        	    ':nohist_expirationdates:'.
                   4032:                             &escape($key).'='.$now,
1.620     albertel 4033:                             $env{'course.'.$cid.'.home'})
1.110     www      4034:     }
                   4035:     return 'ok';
1.14      www      4036: }
                   4037: 
1.109     www      4038: # ----------------------------------------------------- Devalidate Spreadsheets
                   4039: 
                   4040: sub devalidate {
1.325     www      4041:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4042:     my $cid=$env{'request.course.id'}; 
1.109     www      4043:     if ($cid) {
1.391     matthew  4044:         # delete the stored spreadsheets for
                   4045:         # - the student level sheet of this user in course's homespace
                   4046:         # - the assessment level sheet for this resource 
                   4047:         #   for this user in user's homespace
1.553     albertel 4048: 	# - current conditional state info
1.325     www      4049: 	my $key=$uname.':'.$udom.':';
1.109     www      4050:         my $status=
1.299     matthew  4051: 	    &del('nohist_calculatedsheets',
1.391     matthew  4052: 		 [$key.'studentcalc:'],
1.620     albertel 4053: 		 $env{'course.'.$cid.'.domain'},
                   4054: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4055: 		.' '.
                   4056: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4057: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4058:         unless ($status eq 'ok ok') {
                   4059:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4060:                     $uname.' at '.$udom.' for '.
1.109     www      4061: 		    $symb.': '.$status);
1.133     albertel 4062:         }
1.553     albertel 4063: 	&delenv('user.state.'.$cid);
1.109     www      4064:     }
                   4065: }
                   4066: 
1.265     albertel 4067: sub get_scalar {
                   4068:     my ($string,$end) = @_;
                   4069:     my $value;
                   4070:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4071: 	$value = $1;
                   4072:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4073: 	$value = $1;
                   4074:     }
                   4075:     return &unescape($value);
                   4076: }
                   4077: 
                   4078: sub array2str {
                   4079:   my (@array) = @_;
                   4080:   my $result=&arrayref2str(\@array);
                   4081:   $result=~s/^__ARRAY_REF__//;
                   4082:   $result=~s/__END_ARRAY_REF__$//;
                   4083:   return $result;
                   4084: }
                   4085: 
1.204     albertel 4086: sub arrayref2str {
                   4087:   my ($arrayref) = @_;
1.265     albertel 4088:   my $result='__ARRAY_REF__';
1.204     albertel 4089:   foreach my $elem (@$arrayref) {
1.265     albertel 4090:     if(ref($elem) eq 'ARRAY') {
                   4091:       $result.=&arrayref2str($elem).'&';
                   4092:     } elsif(ref($elem) eq 'HASH') {
                   4093:       $result.=&hashref2str($elem).'&';
                   4094:     } elsif(ref($elem)) {
                   4095:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4096:     } else {
                   4097:       $result.=&escape($elem).'&';
                   4098:     }
                   4099:   }
                   4100:   $result=~s/\&$//;
1.265     albertel 4101:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4102:   return $result;
                   4103: }
                   4104: 
1.168     albertel 4105: sub hash2str {
1.204     albertel 4106:   my (%hash) = @_;
                   4107:   my $result=&hashref2str(\%hash);
1.265     albertel 4108:   $result=~s/^__HASH_REF__//;
                   4109:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4110:   return $result;
                   4111: }
                   4112: 
                   4113: sub hashref2str {
                   4114:   my ($hashref)=@_;
1.265     albertel 4115:   my $result='__HASH_REF__';
1.800     albertel 4116:   foreach my $key (sort(keys(%$hashref))) {
                   4117:     if (ref($key) eq 'ARRAY') {
                   4118:       $result.=&arrayref2str($key).'=';
                   4119:     } elsif (ref($key) eq 'HASH') {
                   4120:       $result.=&hashref2str($key).'=';
                   4121:     } elsif (ref($key)) {
1.265     albertel 4122:       $result.='=';
1.800     albertel 4123:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4124:     } else {
1.1132    raeburn  4125: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4126:     }
                   4127: 
1.800     albertel 4128:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4129:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4130:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4131:       $result.=&hashref2str($hashref->{$key}).'&';
                   4132:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4133:        $result.='&';
1.800     albertel 4134:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4135:     } else {
1.800     albertel 4136:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4137:     }
                   4138:   }
1.168     albertel 4139:   $result=~s/\&$//;
1.265     albertel 4140:   $result .= '__END_HASH_REF__';
1.168     albertel 4141:   return $result;
                   4142: }
                   4143: 
                   4144: sub str2hash {
1.265     albertel 4145:     my ($string)=@_;
                   4146:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4147:     return %$hash;
                   4148: }
                   4149: 
                   4150: sub str2hashref {
1.168     albertel 4151:   my ($string) = @_;
1.265     albertel 4152: 
                   4153:   my %hash;
                   4154: 
                   4155:   if($string !~ /^__HASH_REF__/) {
                   4156:       if (! ($string eq '' || !defined($string))) {
                   4157: 	  $hash{'error'}='Not hash reference';
                   4158:       }
                   4159:       return (\%hash, $string);
                   4160:   }
                   4161: 
                   4162:   $string =~ s/^__HASH_REF__//;
                   4163: 
                   4164:   while($string !~ /^__END_HASH_REF__/) {
                   4165:       #key
                   4166:       my $key='';
                   4167:       if($string =~ /^__HASH_REF__/) {
                   4168:           ($key, $string)=&str2hashref($string);
                   4169:           if(defined($key->{'error'})) {
                   4170:               $hash{'error'}='Bad data';
                   4171:               return (\%hash, $string);
                   4172:           }
                   4173:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4174:           ($key, $string)=&str2arrayref($string);
                   4175:           if($key->[0] eq 'Array reference error') {
                   4176:               $hash{'error'}='Bad data';
                   4177:               return (\%hash, $string);
                   4178:           }
                   4179:       } else {
                   4180:           $string =~ s/^(.*?)=//;
1.267     albertel 4181: 	  $key=&unescape($1);
1.265     albertel 4182:       }
                   4183:       $string =~ s/^=//;
                   4184: 
                   4185:       #value
                   4186:       my $value='';
                   4187:       if($string =~ /^__HASH_REF__/) {
                   4188:           ($value, $string)=&str2hashref($string);
                   4189:           if(defined($value->{'error'})) {
                   4190:               $hash{'error'}='Bad data';
                   4191:               return (\%hash, $string);
                   4192:           }
                   4193:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4194:           ($value, $string)=&str2arrayref($string);
                   4195:           if($value->[0] eq 'Array reference error') {
                   4196:               $hash{'error'}='Bad data';
                   4197:               return (\%hash, $string);
                   4198:           }
                   4199:       } else {
                   4200: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4201:       }
                   4202:       $string =~ s/^&//;
                   4203: 
                   4204:       $hash{$key}=$value;
1.204     albertel 4205:   }
1.265     albertel 4206: 
                   4207:   $string =~ s/^__END_HASH_REF__//;
                   4208: 
                   4209:   return (\%hash, $string);
1.204     albertel 4210: }
                   4211: 
                   4212: sub str2array {
1.265     albertel 4213:     my ($string)=@_;
                   4214:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4215:     return @$array;
                   4216: }
                   4217: 
                   4218: sub str2arrayref {
1.204     albertel 4219:   my ($string) = @_;
1.265     albertel 4220:   my @array;
                   4221: 
                   4222:   if($string !~ /^__ARRAY_REF__/) {
                   4223:       if (! ($string eq '' || !defined($string))) {
                   4224: 	  $array[0]='Array reference error';
                   4225:       }
                   4226:       return (\@array, $string);
                   4227:   }
                   4228: 
                   4229:   $string =~ s/^__ARRAY_REF__//;
                   4230: 
                   4231:   while($string !~ /^__END_ARRAY_REF__/) {
                   4232:       my $value='';
                   4233:       if($string =~ /^__HASH_REF__/) {
                   4234:           ($value, $string)=&str2hashref($string);
                   4235:           if(defined($value->{'error'})) {
                   4236:               $array[0] ='Array reference error';
                   4237:               return (\@array, $string);
                   4238:           }
                   4239:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4240:           ($value, $string)=&str2arrayref($string);
                   4241:           if($value->[0] eq 'Array reference error') {
                   4242:               $array[0] ='Array reference error';
                   4243:               return (\@array, $string);
                   4244:           }
                   4245:       } else {
                   4246: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4247:       }
                   4248:       $string =~ s/^&//;
                   4249: 
                   4250:       push(@array, $value);
1.191     harris41 4251:   }
1.265     albertel 4252: 
                   4253:   $string =~ s/^__END_ARRAY_REF__//;
                   4254: 
                   4255:   return (\@array, $string);
1.168     albertel 4256: }
                   4257: 
1.167     albertel 4258: # -------------------------------------------------------------------Temp Store
                   4259: 
1.168     albertel 4260: sub tmpreset {
                   4261:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4262:   if (!$symb) {
                   4263:     $symb=&symbread();
1.620     albertel 4264:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4265:   }
                   4266:   $symb=escape($symb);
                   4267: 
1.620     albertel 4268:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4269:   $namespace=~s/\//\_/g;
                   4270:   $namespace=~s/\W//g;
                   4271: 
1.620     albertel 4272:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4273:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4274:   if ($domain eq 'public' && $stuname eq 'public') {
                   4275:       $stuname=$ENV{'REMOTE_ADDR'};
                   4276:   }
1.1117    foxr     4277:   my $path=LONCAPA::tempdir();
1.168     albertel 4278:   my %hash;
                   4279:   if (tie(%hash,'GDBM_File',
                   4280: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4281: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4282:     foreach my $key (keys(%hash)) {
1.180     albertel 4283:       if ($key=~ /:$symb/) {
1.168     albertel 4284: 	delete($hash{$key});
                   4285:       }
                   4286:     }
                   4287:   }
                   4288: }
                   4289: 
1.167     albertel 4290: sub tmpstore {
1.168     albertel 4291:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4292: 
                   4293:   if (!$symb) {
                   4294:     $symb=&symbread();
1.620     albertel 4295:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4296:   }
                   4297:   $symb=escape($symb);
                   4298: 
                   4299:   if (!$namespace) {
                   4300:     # I don't think we would ever want to store this for a course.
                   4301:     # it seems this will only be used if we don't have a course.
1.620     albertel 4302:     #$namespace=$env{'request.course.id'};
1.168     albertel 4303:     #if (!$namespace) {
1.620     albertel 4304:       $namespace=$env{'request.state'};
1.168     albertel 4305:     #}
                   4306:   }
                   4307:   $namespace=~s/\//\_/g;
                   4308:   $namespace=~s/\W//g;
1.620     albertel 4309:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4310:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4311:   if ($domain eq 'public' && $stuname eq 'public') {
                   4312:       $stuname=$ENV{'REMOTE_ADDR'};
                   4313:   }
1.168     albertel 4314:   my $now=time;
                   4315:   my %hash;
1.1117    foxr     4316:   my $path=LONCAPA::tempdir();
1.168     albertel 4317:   if (tie(%hash,'GDBM_File',
                   4318: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4319: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4320:     $hash{"version:$symb"}++;
                   4321:     my $version=$hash{"version:$symb"};
                   4322:     my $allkeys=''; 
                   4323:     foreach my $key (keys(%$storehash)) {
                   4324:       $allkeys.=$key.':';
1.591     albertel 4325:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4326:     }
                   4327:     $hash{"$version:$symb:timestamp"}=$now;
                   4328:     $allkeys.='timestamp';
                   4329:     $hash{"$version:keys:$symb"}=$allkeys;
                   4330:     if (untie(%hash)) {
                   4331:       return 'ok';
                   4332:     } else {
                   4333:       return "error:$!";
                   4334:     }
                   4335:   } else {
                   4336:     return "error:$!";
                   4337:   }
                   4338: }
1.167     albertel 4339: 
1.168     albertel 4340: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4341: 
1.168     albertel 4342: sub tmprestore {
                   4343:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4344: 
1.168     albertel 4345:   if (!$symb) {
                   4346:     $symb=&symbread();
1.620     albertel 4347:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4348:   }
                   4349:   $symb=escape($symb);
                   4350: 
1.620     albertel 4351:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4352: 
1.620     albertel 4353:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4354:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4355:   if ($domain eq 'public' && $stuname eq 'public') {
                   4356:       $stuname=$ENV{'REMOTE_ADDR'};
                   4357:   }
1.168     albertel 4358:   my %returnhash;
                   4359:   $namespace=~s/\//\_/g;
                   4360:   $namespace=~s/\W//g;
                   4361:   my %hash;
1.1117    foxr     4362:   my $path=LONCAPA::tempdir();
1.168     albertel 4363:   if (tie(%hash,'GDBM_File',
                   4364: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4365: 	  &GDBM_READER(),0640)) {
1.168     albertel 4366:     my $version=$hash{"version:$symb"};
                   4367:     $returnhash{'version'}=$version;
                   4368:     my $scope;
                   4369:     for ($scope=1;$scope<=$version;$scope++) {
                   4370:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4371:       my @keys=split(/:/,$vkeys);
                   4372:       my $key;
                   4373:       $returnhash{"$scope:keys"}=$vkeys;
                   4374:       foreach $key (@keys) {
1.591     albertel 4375: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4376: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4377:       }
                   4378:     }
1.168     albertel 4379:     if (!(untie(%hash))) {
                   4380:       return "error:$!";
                   4381:     }
                   4382:   } else {
                   4383:     return "error:$!";
                   4384:   }
                   4385:   return %returnhash;
1.167     albertel 4386: }
                   4387: 
1.9       www      4388: # ----------------------------------------------------------------------- Store
                   4389: 
                   4390: sub store {
1.124     www      4391:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4392:     my $home='';
                   4393: 
1.168     albertel 4394:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4395: 
1.213     www      4396:     $symb=&symbclean($symb);
1.122     albertel 4397:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4398: 
1.620     albertel 4399:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4400:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4401: 
                   4402:     &devalidate($symb,$stuname,$domain);
1.109     www      4403: 
                   4404:     $symb=escape($symb);
1.187     www      4405:     if (!$namespace) { 
1.620     albertel 4406:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4407:           return ''; 
                   4408:        } 
                   4409:     }
1.620     albertel 4410:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4411: 
                   4412:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4413:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4414: 
1.12      www      4415:     my $namevalue='';
1.800     albertel 4416:     foreach my $key (keys(%$storehash)) {
                   4417:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4418:     }
1.12      www      4419:     $namevalue=~s/\&$//;
1.187     www      4420:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4421:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4422: }
                   4423: 
1.47      www      4424: # -------------------------------------------------------------- Critical Store
                   4425: 
                   4426: sub cstore {
1.124     www      4427:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4428:     my $home='';
                   4429: 
1.168     albertel 4430:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4431: 
1.213     www      4432:     $symb=&symbclean($symb);
1.122     albertel 4433:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4434: 
1.620     albertel 4435:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4436:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4437: 
                   4438:     &devalidate($symb,$stuname,$domain);
1.109     www      4439: 
                   4440:     $symb=escape($symb);
1.187     www      4441:     if (!$namespace) { 
1.620     albertel 4442:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4443:           return ''; 
                   4444:        } 
                   4445:     }
1.620     albertel 4446:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4447: 
                   4448:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4449:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4450: 
1.47      www      4451:     my $namevalue='';
1.800     albertel 4452:     foreach my $key (keys(%$storehash)) {
                   4453:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4454:     }
1.47      www      4455:     $namevalue=~s/\&$//;
1.187     www      4456:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4457:     return critical
                   4458:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4459: }
                   4460: 
1.9       www      4461: # --------------------------------------------------------------------- Restore
                   4462: 
                   4463: sub restore {
1.124     www      4464:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4465:     my $home='';
                   4466: 
1.168     albertel 4467:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4468: 
1.122     albertel 4469:     if (!$symb) {
                   4470:       unless ($symb=escape(&symbread())) { return ''; }
                   4471:     } else {
1.213     www      4472:       $symb=&escape(&symbclean($symb));
1.122     albertel 4473:     }
1.188     www      4474:     if (!$namespace) { 
1.620     albertel 4475:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4476:           return ''; 
                   4477:        } 
                   4478:     }
1.620     albertel 4479:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4480:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4481:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4482:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4483: 
1.12      www      4484:     my %returnhash=();
1.800     albertel 4485:     foreach my $line (split(/\&/,$answer)) {
                   4486: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4487:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4488:     }
1.75      www      4489:     my $version;
                   4490:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4491:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4492:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4493:        }
1.75      www      4494:     }
1.13      www      4495:     return %returnhash;
1.34      www      4496: }
                   4497: 
                   4498: # ---------------------------------------------------------- Course Description
1.1118    foxr     4499: #
                   4500: #  
1.34      www      4501: 
                   4502: sub coursedescription {
1.731     albertel 4503:     my ($courseid,$args)=@_;
1.34      www      4504:     $courseid=~s/^\///;
1.49      www      4505:     $courseid=~s/\_/\//g;
1.34      www      4506:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4507:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4508:     my $normalid=$cdomain.'_'.$cnum;
                   4509:     # need to always cache even if we get errors otherwise we keep 
                   4510:     # trying and trying and trying to get the course description.
                   4511:     my %envhash=();
                   4512:     my %returnhash=();
1.731     albertel 4513:     
                   4514:     my $expiretime=600;
                   4515:     if ($env{'request.course.id'} eq $normalid) {
                   4516: 	$expiretime=120;
                   4517:     }
                   4518: 
                   4519:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4520:     if (!$args->{'freshen_cache'}
                   4521: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4522: 	foreach my $key (keys(%env)) {
                   4523: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4524: 	    my ($setting) = $1;
                   4525: 	    $returnhash{$setting} = $env{$key};
                   4526: 	}
                   4527: 	return %returnhash;
                   4528:     }
                   4529: 
1.1118    foxr     4530:     # get the data again
                   4531: 
1.731     albertel 4532:     if (!$args->{'one_time'}) {
                   4533: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4534:     }
1.811     albertel 4535: 
1.34      www      4536:     if ($chome ne 'no_host') {
1.302     albertel 4537:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4538:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4539: 	   my $username = $env{'user.name'}; # Defult username
                   4540: 	   if(defined $args->{'user'}) {
                   4541: 	       $username = $args->{'user'};
                   4542: 	   }
1.129     albertel 4543:            $returnhash{'home'}= $chome;
                   4544: 	   $returnhash{'domain'} = $cdomain;
                   4545: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4546:            if (!defined($returnhash{'type'})) {
                   4547:                $returnhash{'type'} = 'Course';
                   4548:            }
1.130     albertel 4549:            while (my ($name,$value) = each %returnhash) {
1.53      www      4550:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4551:            }
1.270     www      4552:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4553:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4554: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4555:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4556:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4557:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4558:        }
                   4559:     }
1.731     albertel 4560:     if (!$args->{'one_time'}) {
1.949     raeburn  4561: 	&appenv(\%envhash);
1.731     albertel 4562:     }
1.302     albertel 4563:     return %returnhash;
1.461     www      4564: }
                   4565: 
1.1080    raeburn  4566: sub update_released_required {
                   4567:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4568:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4569:         $cid = $env{'request.course.id'};
                   4570:         $cdom = $env{'course.'.$cid.'.domain'};
                   4571:         $cnum = $env{'course.'.$cid.'.num'};
                   4572:         $chome = $env{'course.'.$cid.'.home'};
                   4573:     }
                   4574:     if ($needsrelease) {
                   4575:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4576:         my $needsupdate;
                   4577:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4578:             $needsupdate = 1;
                   4579:         } else {
                   4580:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4581:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4582:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4583:                 $needsupdate = 1;
                   4584:             }
                   4585:         }
                   4586:         if ($needsupdate) {
                   4587:             my %needshash = (
                   4588:                              'internal.releaserequired' => $needsrelease,
                   4589:                             );
                   4590:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4591:             if ($putresult eq 'ok') {
                   4592:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4593:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4594:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4595:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4596:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4597:                 }
                   4598:             }
                   4599:         }
                   4600:     }
                   4601:     return;
                   4602: }
                   4603: 
1.461     www      4604: # -------------------------------------------------See if a user is privileged
                   4605: 
                   4606: sub privileged {
                   4607:     my ($username,$domain)=@_;
1.1170    droeschl 4608: 
                   4609:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4610:     my $now = time;
                   4611: 
                   4612:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4613:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4614:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4615:                 return 1 unless ($tend && $tend < $now) 
                   4616:                     or ($tstart && $tstart > $now);
                   4617:             }
1.461     www      4618: 	}
1.1170    droeschl 4619: 
1.461     www      4620:     return 0;
1.9       www      4621: }
1.1       albertel 4622: 
1.103     harris41 4623: # -------------------------------------------------------- Get user privileges
1.11      www      4624: 
                   4625: sub rolesinit {
1.1169    droeschl 4626:     my ($domain, $username) = @_;
                   4627:     my %userroles = ('user.login.time' => time);
                   4628:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4629: 
                   4630:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4631:     # also, blocking can be triggered by an activating timer
                   4632:     # it's saved in the user's %env.
                   4633:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4634:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4635:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4636:         %timerintchk, %timerintenv);
                   4637: 
1.1162    raeburn  4638:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4639:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4640:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4641:     }
1.1169    droeschl 4642: 
1.1162    raeburn  4643:     foreach my $key (keys(%timerinterval)) {
                   4644:         my ($cid,$rest) = split(/\0/,$key);
                   4645:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4646:     }
1.1169    droeschl 4647: 
1.11      www      4648:     my %allroles=();
1.1162    raeburn  4649:     my %allgroups=();
1.11      www      4650: 
1.1169    droeschl 4651:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4652:         my $role = $rolesdump{$area};
                   4653:         $area =~ s/\_\w\w$//;
                   4654: 
                   4655:         my ($trole, $tend, $tstart, $group_privs);
                   4656: 
                   4657:         if ($role =~ /^cr/) {
                   4658:         # Custom role, defined by a user 
                   4659:         # e.g., user.role.cr/msu/smith/mynewrole
                   4660:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4661:                 $trole = $1;
                   4662:                 ($tend, $tstart) = split('_', $2);
                   4663:             } else {
                   4664:                 $trole = $role;
                   4665:             }
                   4666:         } elsif ($role =~ m|^gr/|) {
                   4667:         # Role of member in a group, defined within a course/community
                   4668:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4669:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4670:             next if $tstart eq '-1';
                   4671:             ($trole, $group_privs) = split(/\//, $trole);
                   4672:             $group_privs = &unescape($group_privs);
                   4673:         } else {
                   4674:         # Just a normal role, defined in roles.tab
                   4675:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4676:         }
                   4677: 
                   4678:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4679:                  $username);
                   4680:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4681: 
                   4682:         # role expired or not available yet?
                   4683:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4684:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4685: 
                   4686:         next if $area eq '' or $trole eq '';
                   4687: 
                   4688:         my $spec = "$trole.$area";
                   4689:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4690: 
                   4691:         if ($trole =~ /^cr\//) {
                   4692:         # Custom role, defined by a user
                   4693:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4694:         } elsif ($trole eq 'gr') {
                   4695:         # Role of a member in a group, defined within a course/community
                   4696:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4697:             next;
                   4698:         } else {
                   4699:         # Normal role, defined in roles.tab
                   4700:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4701:         }
                   4702: 
                   4703:         my $cid = $tdomain.'_'.$trest;
                   4704:         unless ($firstaccchk{$cid}) {
                   4705:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4706:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4707:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4708:                         $coursetimerstarts{$cid}{$item}; 
                   4709:                 }
                   4710:             }
                   4711:             $firstaccchk{$cid} = 1;
                   4712:         }
                   4713:         unless ($timerintchk{$cid}) {
                   4714:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4715:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4716:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4717:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4718:                 }
1.12      www      4719:             }
1.1169    droeschl 4720:             $timerintchk{$cid} = 1;
1.191     harris41 4721:         }
1.11      www      4722:     }
1.1169    droeschl 4723: 
                   4724:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4725:         \%allroles, \%allgroups);
                   4726:     $env{'user.adv'} = $userroles{'user.adv'};
                   4727: 
1.1162    raeburn  4728:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4729: }
                   4730: 
1.567     raeburn  4731: sub set_arearole {
                   4732:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4733: # log the associated role with the area
                   4734:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4735:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4736: }
                   4737: 
                   4738: sub custom_roleprivs {
                   4739:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4740:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4741:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4742:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4743:         my ($rdummy,$roledef)=
                   4744:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4745:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4746:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4747:             if (defined($syspriv)) {
1.1043    raeburn  4748:                 if ($trest =~ /^$match_community$/) {
                   4749:                     $syspriv =~ s/bre\&S//; 
                   4750:                 }
1.567     raeburn  4751:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4752:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4753:             }
                   4754:             if ($tdomain ne '') {
                   4755:                 if (defined($dompriv)) {
                   4756:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4757:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4758:                 }
                   4759:                 if (($trest ne '') && (defined($coursepriv))) {
                   4760:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4761:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4762:                 }
                   4763:             }
                   4764:         }
                   4765:     }
                   4766: }
                   4767: 
1.678     raeburn  4768: sub group_roleprivs {
                   4769:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4770:     my $access = 1;
                   4771:     my $now = time;
                   4772:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4773:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4774:     if ($access) {
1.811     albertel 4775:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4776:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4777:     }
                   4778: }
1.567     raeburn  4779: 
                   4780: sub standard_roleprivs {
                   4781:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4782:     if (defined($pr{$trole.':s'})) {
                   4783:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4784:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4785:     }
                   4786:     if ($tdomain ne '') {
                   4787:         if (defined($pr{$trole.':d'})) {
                   4788:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4789:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4790:         }
                   4791:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4792:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4793:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4794:         }
                   4795:     }
                   4796: }
                   4797: 
                   4798: sub set_userprivs {
1.1064    raeburn  4799:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4800:     my $author=0;
                   4801:     my $adv=0;
1.678     raeburn  4802:     my %grouproles = ();
                   4803:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4804:         my @groupkeys; 
1.1000    raeburn  4805:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4806:             push(@groupkeys,$role);
                   4807:         }
                   4808:         if (ref($groups_roles) eq 'HASH') {
                   4809:             foreach my $key (keys(%{$groups_roles})) {
                   4810:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4811:                     push(@groupkeys,$key);
                   4812:                 }
                   4813:             }
                   4814:         }
                   4815:         if (@groupkeys > 0) {
                   4816:             foreach my $role (@groupkeys) {
                   4817:                 my ($trole,$area,$sec,$extendedarea);
                   4818:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4819:                     $trole = $1;
                   4820:                     $area = $2;
                   4821:                     $sec = $3;
                   4822:                     $extendedarea = $area.$sec;
                   4823:                     if (exists($$allgroups{$area})) {
                   4824:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4825:                             my $spec = $trole.'.'.$extendedarea;
                   4826:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4827:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4828:                         }
1.678     raeburn  4829:                     }
                   4830:                 }
                   4831:             }
                   4832:         }
                   4833:     }
1.800     albertel 4834:     foreach my $group (keys(%grouproles)) {
                   4835:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4836:     }
1.800     albertel 4837:     foreach my $role (keys(%{$allroles})) {
                   4838:         my %thesepriv;
1.941     raeburn  4839:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4840:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4841:             if ($item ne '') {
                   4842:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4843:                 if ($restrictions eq '') {
                   4844:                     $thesepriv{$privilege}='F';
                   4845:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4846:                     $thesepriv{$privilege}.=$restrictions;
                   4847:                 }
                   4848:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4849:             }
                   4850:         }
                   4851:         my $thesestr='';
1.1104    raeburn  4852:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4853: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4854: 	}
                   4855:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4856:     }
                   4857:     return ($author,$adv);
                   4858: }
                   4859: 
1.994     raeburn  4860: sub role_status {
1.1104    raeburn  4861:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4862:     my @pwhere = ();
                   4863:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4864:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4865:         unless (!defined($$role) || $$role eq '') {
                   4866:             $$where=join('.',@pwhere);
                   4867:             $$trolecode=$$role.'.'.$$where;
                   4868:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4869:             $$tstatus='is';
1.1104    raeburn  4870:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4871:                 $$tstatus='future';
1.1034    raeburn  4872:                 if ($$tstart<$now) {
                   4873:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4874:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4875:                             my (%allroles,%allgroups,$group_privs,
                   4876:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4877:                             my %userroles = (
                   4878:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4879:                             );
1.1064    raeburn  4880:                             @rolecodes = ('cm'); 
1.1002    raeburn  4881:                             my $spec=$$role.'.'.$$where;
                   4882:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4883:                             if ($$role =~ /^cr\//) {
                   4884:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4885:                                 push(@rolecodes,'cr');
1.1002    raeburn  4886:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4887:                                 push(@rolecodes,$$role);
1.1002    raeburn  4888:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4889:                                                     $env{'user.name'});
1.1064    raeburn  4890:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4891:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4892:                                 $group_privs = &unescape($group_privs);
                   4893:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4894:                                 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  4895:                                 &get_groups_roles($tdomain,$trest,
                   4896:                                                   \%course_roles,\@rolecodes,
                   4897:                                                   \%groups_roles);
1.1002    raeburn  4898:                             } else {
1.1064    raeburn  4899:                                 push(@rolecodes,$$role);
1.1002    raeburn  4900:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4901:                             }
1.1064    raeburn  4902:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4903:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4904:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4905:                         }
                   4906:                     }
1.1034    raeburn  4907:                     $$tstatus = 'is';
1.1002    raeburn  4908:                 }
1.994     raeburn  4909:             }
                   4910:             if ($$tend) {
1.1104    raeburn  4911:                 if ($$tend<$update) {
1.994     raeburn  4912:                     $$tstatus='expired';
                   4913:                 } elsif ($$tend<$now) {
                   4914:                     $$tstatus='will_not';
                   4915:                 }
                   4916:             }
                   4917:         }
                   4918:     }
                   4919: }
                   4920: 
1.1104    raeburn  4921: sub get_groups_roles {
                   4922:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4923:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4924:                   (ref($rolecodes) eq 'ARRAY') && 
                   4925:                   (ref($groups_roles) eq 'HASH')); 
                   4926:     if (keys(%{$cdom_courseroles}) > 0) {
                   4927:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4928:         if ($cdom ne '' && $cnum ne '') {
                   4929:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4930:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4931:                     my $crsrole = $1;
                   4932:                     my $crssec = $2;
                   4933:                     if ($crsrole =~ /^cr/) {
                   4934:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4935:                             push(@{$rolecodes},'cr');
                   4936:                         }
                   4937:                     } else {
                   4938:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4939:                             push(@{$rolecodes},$crsrole);
                   4940:                         }
                   4941:                     }
                   4942:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4943:                     if ($crssec ne '') {
                   4944:                         $rolekey .= "/$crssec";
                   4945:                     }
                   4946:                     $rolekey .= './';
                   4947:                     $groups_roles->{$rolekey} = $rolecodes;
                   4948:                 }
                   4949:             }
                   4950:         }
                   4951:     }
                   4952:     return;
                   4953: }
                   4954: 
                   4955: sub delete_env_groupprivs {
                   4956:     my ($where,$courseroles,$possroles) = @_;
                   4957:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4958:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4959:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4960:         %{$courseroles->{$udom}} =
                   4961:             &get_my_roles('','','userroles',['active'],
                   4962:                           $possroles,[$udom],1);
                   4963:     }
                   4964:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4965:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4966:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4967:             my $area = '/'.$cdom.'/'.$cnum;
                   4968:             my $privkey = "user.priv.$crsrole.$area";
                   4969:             if ($crssec ne '') {
                   4970:                 $privkey .= '/'.$crssec;
                   4971:             }
                   4972:             $privkey .= ".$area/$group";
                   4973:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4974:         }
                   4975:     }
                   4976:     return;
                   4977: }
                   4978: 
1.994     raeburn  4979: sub check_adhoc_privs {
1.1104    raeburn  4980:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4981:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4982:     if ($env{$cckey}) {
                   4983:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4984:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4985:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4986:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4987:         }
                   4988:     } else {
1.1088    raeburn  4989:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4990:     }
                   4991: }
                   4992: 
                   4993: sub set_adhoc_privileges {
                   4994: # role can be cc or ca
1.1088    raeburn  4995:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4996:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4997:     my $spec = $role.'.'.$area;
                   4998:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4999:                                   $env{'user.name'});
                   5000:     my %ccrole = ();
                   5001:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5002:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5003:     &appenv(\%userroles,[$role,'cm']);
                   5004:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5005:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5006:         &appenv( {'request.role'        => $spec,
                   5007:                   'request.role.domain' => $dcdom,
                   5008:                   'request.course.sec'  => ''
                   5009:                  }
                   5010:                );
                   5011:         my $tadv=0;
                   5012:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5013:         &appenv({'request.role.adv'    => $tadv});
                   5014:     }
1.994     raeburn  5015: }
                   5016: 
1.12      www      5017: # --------------------------------------------------------------- get interface
                   5018: 
                   5019: sub get {
1.131     albertel 5020:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5021:    my $items='';
1.800     albertel 5022:    foreach my $item (@$storearr) {
                   5023:        $items.=&escape($item).'&';
1.191     harris41 5024:    }
1.12      www      5025:    $items=~s/\&$//;
1.620     albertel 5026:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5027:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5028:    my $uhome=&homeserver($uname,$udomain);
                   5029: 
1.133     albertel 5030:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5031:    my @pairs=split(/\&/,$rep);
1.273     albertel 5032:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5033:      return @pairs;
                   5034:    }
1.15      www      5035:    my %returnhash=();
1.42      www      5036:    my $i=0;
1.800     albertel 5037:    foreach my $item (@$storearr) {
                   5038:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5039:       $i++;
1.191     harris41 5040:    }
1.15      www      5041:    return %returnhash;
1.27      www      5042: }
                   5043: 
                   5044: # --------------------------------------------------------------- del interface
                   5045: 
                   5046: sub del {
1.133     albertel 5047:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5048:    my $items='';
1.800     albertel 5049:    foreach my $item (@$storearr) {
                   5050:        $items.=&escape($item).'&';
1.191     harris41 5051:    }
1.984     neumanie 5052: 
1.27      www      5053:    $items=~s/\&$//;
1.620     albertel 5054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5055:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5056:    my $uhome=&homeserver($uname,$udomain);
                   5057:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5058: }
                   5059: 
                   5060: # -------------------------------------------------------------- dump interface
                   5061: 
                   5062: sub dump {
1.1166    raeburn  5063:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5064:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5065:     if (!$uname) { $uname=$env{'user.name'}; }
                   5066:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5067: 
1.755     albertel 5068:     if ($regexp) {
                   5069: 	$regexp=&escape($regexp);
                   5070:     } else {
                   5071: 	$regexp='.';
                   5072:     }
1.1166    raeburn  5073:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5074:     my @pairs=split(/\&/,$rep);
                   5075:     my %returnhash=();
1.1098    foxr     5076:     if (!($rep =~ /^error/ )) {
                   5077: 	foreach my $item (@pairs) {
                   5078: 	    my ($key,$value)=split(/=/,$item,2);
                   5079: 	    $key = &unescape($key);
                   5080: 	    next if ($key =~ /^error: 2 /);
                   5081: 	    $returnhash{$key}=&thaw_unescape($value);
                   5082: 	}
1.755     albertel 5083:     }
                   5084:     return %returnhash;
1.407     www      5085: }
                   5086: 
1.1098    foxr     5087: 
1.717     albertel 5088: # --------------------------------------------------------- dumpstore interface
                   5089: 
                   5090: sub dumpstore {
                   5091:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5093:    if (!$uname) { $uname=$env{'user.name'}; }
                   5094:    my $uhome=&homeserver($uname,$udomain);
                   5095:    if ($regexp) {
                   5096:        $regexp=&escape($regexp);
                   5097:    } else {
                   5098:        $regexp='.';
                   5099:    }
                   5100:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5101:    my @pairs=split(/\&/,$rep);
                   5102:    my %returnhash=();
                   5103:    foreach my $item (@pairs) {
                   5104:        my ($key,$value)=split(/=/,$item,2);
                   5105:        next if ($key =~ /^error: 2 /);
                   5106:        $returnhash{$key}=&thaw_unescape($value);
                   5107:    }
                   5108:    return %returnhash;
1.717     albertel 5109: }
                   5110: 
1.407     www      5111: # -------------------------------------------------------------- keys interface
                   5112: 
                   5113: sub getkeys {
                   5114:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5116:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5117:    my $uhome=&homeserver($uname,$udomain);
                   5118:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5119:    my @keyarray=();
1.800     albertel 5120:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5121:       next if ($key =~ /^error: 2 /);
1.800     albertel 5122:       push(@keyarray,&unescape($key));
1.407     www      5123:    }
                   5124:    return @keyarray;
1.318     matthew  5125: }
                   5126: 
1.319     matthew  5127: # --------------------------------------------------------------- currentdump
                   5128: sub currentdump {
1.328     matthew  5129:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5130:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5131:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5132:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5133:    my $uhome = &homeserver($sname,$sdom);
                   5134:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5135:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5136:    #
1.318     matthew  5137:    my %returnhash=();
1.319     matthew  5138:    #
                   5139:    if ($rep eq "unknown_cmd") { 
                   5140:        # an old lond will not know currentdump
                   5141:        # Do a dump and make it look like a currentdump
1.822     albertel 5142:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5143:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5144:        my %hash = @tmp;
                   5145:        @tmp=();
1.424     matthew  5146:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5147:    } else {
                   5148:        my @pairs=split(/\&/,$rep);
1.800     albertel 5149:        foreach my $pair (@pairs) {
                   5150:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5151:            my ($symb,$param) = split(/:/,$key);
                   5152:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5153:                                                         &thaw_unescape($value);
1.319     matthew  5154:        }
1.191     harris41 5155:    }
1.12      www      5156:    return %returnhash;
1.424     matthew  5157: }
                   5158: 
                   5159: sub convert_dump_to_currentdump{
                   5160:     my %hash = %{shift()};
                   5161:     my %returnhash;
                   5162:     # Code ripped from lond, essentially.  The only difference
                   5163:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5164:     # we might run in to problems with parameter names =~ /^v\./
                   5165:     while (my ($key,$value) = each(%hash)) {
                   5166:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5167: 	$symb  = &unescape($symb);
                   5168: 	$param = &unescape($param);
1.424     matthew  5169:         next if ($v eq 'version' || $symb eq 'keys');
                   5170:         next if (exists($returnhash{$symb}) &&
                   5171:                  exists($returnhash{$symb}->{$param}) &&
                   5172:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5173:         $returnhash{$symb}->{$param}=$value;
                   5174:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5175:     }
                   5176:     #
                   5177:     # Remove all of the keys in the hashes which keep track of
                   5178:     # the version of the parameter.
                   5179:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5180:         # use a foreach because we are going to delete from the hash.
                   5181:         foreach my $key (keys(%$param_hash)) {
                   5182:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5183:         }
                   5184:     }
                   5185:     return \%returnhash;
1.12      www      5186: }
                   5187: 
1.627     albertel 5188: # ------------------------------------------------------ critical inc interface
                   5189: 
                   5190: sub cinc {
                   5191:     return &inc(@_,'critical');
                   5192: }
                   5193: 
1.449     matthew  5194: # --------------------------------------------------------------- inc interface
                   5195: 
                   5196: sub inc {
1.627     albertel 5197:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5198:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5199:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5200:     my $uhome=&homeserver($uname,$udomain);
                   5201:     my $items='';
                   5202:     if (! ref($store)) {
                   5203:         # got a single value, so use that instead
                   5204:         $items = &escape($store).'=&';
                   5205:     } elsif (ref($store) eq 'SCALAR') {
                   5206:         $items = &escape($$store).'=&';        
                   5207:     } elsif (ref($store) eq 'ARRAY') {
                   5208:         $items = join('=&',map {&escape($_);} @{$store});
                   5209:     } elsif (ref($store) eq 'HASH') {
                   5210:         while (my($key,$value) = each(%{$store})) {
                   5211:             $items.= &escape($key).'='.&escape($value).'&';
                   5212:         }
                   5213:     }
                   5214:     $items=~s/\&$//;
1.627     albertel 5215:     if ($critical) {
                   5216: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5217:     } else {
                   5218: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5219:     }
1.449     matthew  5220: }
                   5221: 
1.12      www      5222: # --------------------------------------------------------------- put interface
                   5223: 
                   5224: sub put {
1.134     albertel 5225:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5226:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5227:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5228:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5229:    my $items='';
1.800     albertel 5230:    foreach my $item (keys(%$storehash)) {
                   5231:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5232:    }
1.12      www      5233:    $items=~s/\&$//;
1.134     albertel 5234:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5235: }
                   5236: 
1.631     albertel 5237: # ------------------------------------------------------------ newput interface
                   5238: 
                   5239: sub newput {
                   5240:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5241:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5242:    if (!$uname) { $uname=$env{'user.name'}; }
                   5243:    my $uhome=&homeserver($uname,$udomain);
                   5244:    my $items='';
                   5245:    foreach my $key (keys(%$storehash)) {
                   5246:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5247:    }
                   5248:    $items=~s/\&$//;
                   5249:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5250: }
                   5251: 
                   5252: # ---------------------------------------------------------  putstore interface
                   5253: 
1.524     raeburn  5254: sub putstore {
1.715     albertel 5255:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5256:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5257:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5258:    my $uhome=&homeserver($uname,$udomain);
                   5259:    my $items='';
1.715     albertel 5260:    foreach my $key (keys(%$storehash)) {
                   5261:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5262:    }
1.715     albertel 5263:    $items=~s/\&$//;
1.716     albertel 5264:    my $esc_symb=&escape($symb);
                   5265:    my $esc_v=&escape($version);
1.715     albertel 5266:    my $reply =
1.716     albertel 5267:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5268: 	      $uhome);
                   5269:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5270:        # gfall back to way things use to be done
1.715     albertel 5271:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5272: 			    $uname);
1.524     raeburn  5273:    }
1.715     albertel 5274:    return $reply;
                   5275: }
                   5276: 
                   5277: sub old_putstore {
1.716     albertel 5278:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5279:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5280:     if (!$uname) { $uname=$env{'user.name'}; }
                   5281:     my $uhome=&homeserver($uname,$udomain);
                   5282:     my %newstorehash;
1.800     albertel 5283:     foreach my $item (keys(%$storehash)) {
                   5284: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5285: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5286:     }
                   5287:     my $items='';
                   5288:     my %allitems = ();
1.800     albertel 5289:     foreach my $item (keys(%newstorehash)) {
                   5290: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5291: 	    my $key = $1.':keys:'.$2;
                   5292: 	    $allitems{$key} .= $3.':';
                   5293: 	}
1.800     albertel 5294: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5295:     }
1.800     albertel 5296:     foreach my $item (keys(%allitems)) {
                   5297: 	$allitems{$item} =~ s/\:$//;
                   5298: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5299:     }
                   5300:     $items=~s/\&$//;
                   5301:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5302: }
                   5303: 
1.47      www      5304: # ------------------------------------------------------ critical put interface
                   5305: 
                   5306: sub cput {
1.134     albertel 5307:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5308:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5309:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5310:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5311:    my $items='';
1.800     albertel 5312:    foreach my $item (keys(%$storehash)) {
                   5313:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5314:    }
1.47      www      5315:    $items=~s/\&$//;
1.134     albertel 5316:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5317: }
                   5318: 
                   5319: # -------------------------------------------------------------- eget interface
                   5320: 
                   5321: sub eget {
1.133     albertel 5322:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5323:    my $items='';
1.800     albertel 5324:    foreach my $item (@$storearr) {
                   5325:        $items.=&escape($item).'&';
1.191     harris41 5326:    }
1.12      www      5327:    $items=~s/\&$//;
1.620     albertel 5328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5329:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5330:    my $uhome=&homeserver($uname,$udomain);
                   5331:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5332:    my @pairs=split(/\&/,$rep);
                   5333:    my %returnhash=();
1.42      www      5334:    my $i=0;
1.800     albertel 5335:    foreach my $item (@$storearr) {
                   5336:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5337:       $i++;
1.191     harris41 5338:    }
1.12      www      5339:    return %returnhash;
                   5340: }
                   5341: 
1.667     albertel 5342: # ------------------------------------------------------------ tmpput interface
                   5343: sub tmpput {
1.802     raeburn  5344:     my ($storehash,$server,$context)=@_;
1.667     albertel 5345:     my $items='';
1.800     albertel 5346:     foreach my $item (keys(%$storehash)) {
                   5347: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5348:     }
                   5349:     $items=~s/\&$//;
1.802     raeburn  5350:     if (defined($context)) {
                   5351:         $items .= ':'.&escape($context);
                   5352:     }
1.667     albertel 5353:     return &reply("tmpput:$items",$server);
                   5354: }
                   5355: 
                   5356: # ------------------------------------------------------------ tmpget interface
                   5357: sub tmpget {
1.688     albertel 5358:     my ($token,$server)=@_;
                   5359:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5360:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5361:     my %returnhash;
                   5362:     foreach my $item (split(/\&/,$rep)) {
                   5363: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5364:         next if ($key =~ /^error: 2 /);
1.667     albertel 5365: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5366:     }
                   5367:     return %returnhash;
                   5368: }
                   5369: 
1.1113    raeburn  5370: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5371: sub tmpdel {
                   5372:     my ($token,$server)=@_;
                   5373:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5374:     return &reply("tmpdel:$token",$server);
                   5375: }
                   5376: 
1.765     albertel 5377: # -------------------------------------------------- portfolio access checking
                   5378: 
                   5379: sub portfolio_access {
1.766     albertel 5380:     my ($requrl) = @_;
1.765     albertel 5381:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5382:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5383:     if ($result) {
                   5384:         my %setters;
                   5385:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5386:             my ($startblock,$endblock) =
                   5387:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5388:             if ($startblock && $endblock) {
                   5389:                 return 'B';
                   5390:             }
                   5391:         } else {
                   5392:             my ($startblock,$endblock) =
                   5393:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5394:             if ($startblock && $endblock) {
                   5395:                 return 'B';
                   5396:             }
                   5397:         }
                   5398:     }
1.765     albertel 5399:     if ($result eq 'ok') {
1.766     albertel 5400:        return 'F';
1.765     albertel 5401:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5402:        return 'A';
1.765     albertel 5403:     }
1.766     albertel 5404:     return '';
1.765     albertel 5405: }
                   5406: 
                   5407: sub get_portfolio_access {
1.767     albertel 5408:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5409: 
                   5410:     if (!ref($access_hash)) {
                   5411: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5412: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5413: 						   $file_name);
                   5414: 	$access_hash = $access_controls{$file_name};
                   5415:     }
                   5416: 
1.765     albertel 5417:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5418:     my $now = time;
                   5419:     if (ref($access_hash) eq 'HASH') {
                   5420:         foreach my $key (keys(%{$access_hash})) {
                   5421:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5422:             if ($start > $now) {
                   5423:                 next;
                   5424:             }
                   5425:             if ($end && $end<$now) {
                   5426:                 next;
                   5427:             }
                   5428:             if ($scope eq 'public') {
                   5429:                 $public = $key;
                   5430:                 last;
                   5431:             } elsif ($scope eq 'guest') {
                   5432:                 $guest = $key;
                   5433:             } elsif ($scope eq 'domains') {
                   5434:                 push(@domains,$key);
                   5435:             } elsif ($scope eq 'users') {
                   5436:                 push(@users,$key);
                   5437:             } elsif ($scope eq 'course') {
                   5438:                 push(@courses,$key);
                   5439:             } elsif ($scope eq 'group') {
                   5440:                 push(@groups,$key);
                   5441:             }
                   5442:         }
                   5443:         if ($public) {
                   5444:             return 'ok';
                   5445:         }
                   5446:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5447:             if ($guest) {
                   5448:                 return $guest;
                   5449:             }
                   5450:         } else {
                   5451:             if (@domains > 0) {
                   5452:                 foreach my $domkey (@domains) {
                   5453:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5454:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5455:                             return 'ok';
                   5456:                         }
                   5457:                     }
                   5458:                 }
                   5459:             }
                   5460:             if (@users > 0) {
                   5461:                 foreach my $userkey (@users) {
1.865     raeburn  5462:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5463:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5464:                             if (ref($item) eq 'HASH') {
                   5465:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5466:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5467:                                     return 'ok';
                   5468:                                 }
                   5469:                             }
                   5470:                         }
                   5471:                     } 
1.765     albertel 5472:                 }
                   5473:             }
                   5474:             my %roleshash;
                   5475:             my @courses_and_groups = @courses;
                   5476:             push(@courses_and_groups,@groups); 
                   5477:             if (@courses_and_groups > 0) {
                   5478:                 my (%allgroups,%allroles); 
                   5479:                 my ($start,$end,$role,$sec,$group);
                   5480:                 foreach my $envkey (%env) {
1.1060    raeburn  5481:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5482:                         my $cid = $2.'_'.$3; 
                   5483:                         if ($1 eq 'gr') {
                   5484:                             $group = $4;
                   5485:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5486:                         } else {
                   5487:                             if ($4 eq '') {
                   5488:                                 $sec = 'none';
                   5489:                             } else {
                   5490:                                 $sec = $4;
                   5491:                             }
                   5492:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5493:                         }
1.811     albertel 5494:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5495:                         my $cid = $2.'_'.$3;
                   5496:                         if ($4 eq '') {
                   5497:                             $sec = 'none';
                   5498:                         } else {
                   5499:                             $sec = $4;
                   5500:                         }
                   5501:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5502:                     }
                   5503:                 }
                   5504:                 if (keys(%allroles) == 0) {
                   5505:                     return;
                   5506:                 }
                   5507:                 foreach my $key (@courses_and_groups) {
                   5508:                     my %content = %{$$access_hash{$key}};
                   5509:                     my $cnum = $content{'number'};
                   5510:                     my $cdom = $content{'domain'};
                   5511:                     my $cid = $cdom.'_'.$cnum;
                   5512:                     if (!exists($allroles{$cid})) {
                   5513:                         next;
                   5514:                     }    
                   5515:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5516:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5517:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5518:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5519:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5520:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5521:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5522:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5523:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5524:                                         if (grep/^all$/,@sections) {
                   5525:                                             return 'ok';
                   5526:                                         } else {
                   5527:                                             if (grep/^$sec$/,@sections) {
                   5528:                                                 return 'ok';
                   5529:                                             }
                   5530:                                         }
                   5531:                                     }
                   5532:                                 }
                   5533:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5534:                                     if (grep/^none$/,@groups) {
                   5535:                                         return 'ok';
                   5536:                                     }
                   5537:                                 } else {
                   5538:                                     if (grep/^all$/,@groups) {
                   5539:                                         return 'ok';
                   5540:                                     } 
                   5541:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5542:                                         if (grep/^$group$/,@groups) {
                   5543:                                             return 'ok';
                   5544:                                         }
                   5545:                                     }
                   5546:                                 } 
                   5547:                             }
                   5548:                         }
                   5549:                     }
                   5550:                 }
                   5551:             }
                   5552:             if ($guest) {
                   5553:                 return $guest;
                   5554:             }
                   5555:         }
                   5556:     }
                   5557:     return;
                   5558: }
                   5559: 
                   5560: sub course_group_datechecker {
                   5561:     my ($dates,$now,$status) = @_;
                   5562:     my ($start,$end) = split(/\./,$dates);
                   5563:     if (!$start && !$end) {
                   5564:         return 'ok';
                   5565:     }
                   5566:     if (grep/^active$/,@{$status}) {
                   5567:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5568:             return 'ok';
                   5569:         }
                   5570:     }
                   5571:     if (grep/^previous$/,@{$status}) {
                   5572:         if ($end > $now ) {
                   5573:             return 'ok';
                   5574:         }
                   5575:     }
                   5576:     if (grep/^future$/,@{$status}) {
                   5577:         if ($start > $now) {
                   5578:             return 'ok';
                   5579:         }
                   5580:     }
                   5581:     return; 
                   5582: }
                   5583: 
                   5584: sub parse_portfolio_url {
                   5585:     my ($url) = @_;
                   5586: 
                   5587:     my ($type,$udom,$unum,$group,$file_name);
                   5588:     
1.823     albertel 5589:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5590: 	$type = 1;
                   5591:         $udom = $1;
                   5592:         $unum = $2;
                   5593:         $file_name = $3;
1.823     albertel 5594:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5595: 	$type = 2;
                   5596:         $udom = $1;
                   5597:         $unum = $2;
                   5598:         $group = $3;
                   5599:         $file_name = $3.'/'.$4;
                   5600:     }
                   5601:     if (wantarray) {
                   5602: 	return ($type,$udom,$unum,$file_name,$group);
                   5603:     }
                   5604:     return $type;
                   5605: }
                   5606: 
                   5607: sub is_portfolio_url {
                   5608:     my ($url) = @_;
                   5609:     return scalar(&parse_portfolio_url($url));
                   5610: }
                   5611: 
1.798     raeburn  5612: sub is_portfolio_file {
                   5613:     my ($file) = @_;
1.820     raeburn  5614:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5615:         return 1;
                   5616:     }
                   5617:     return;
                   5618: }
                   5619: 
1.976     raeburn  5620: sub usertools_access {
1.1084    raeburn  5621:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5622:     my ($access,%tools);
                   5623:     if ($context eq '') {
                   5624:         $context = 'tools';
                   5625:     }
                   5626:     if ($context eq 'requestcourses') {
                   5627:         %tools = (
                   5628:                       official   => 1,
                   5629:                       unofficial => 1,
1.1006    raeburn  5630:                       community  => 1,
1.985     raeburn  5631:                  );
                   5632:     } else {
                   5633:         %tools = (
                   5634:                       aboutme   => 1,
                   5635:                       blog      => 1,
                   5636:                       portfolio => 1,
                   5637:                  );
                   5638:     }
1.976     raeburn  5639:     return if (!defined($tools{$tool}));
                   5640: 
                   5641:     if ((!defined($udom)) || (!defined($uname))) {
                   5642:         $udom = $env{'user.domain'};
                   5643:         $uname = $env{'user.name'};
                   5644:     }
                   5645: 
1.978     raeburn  5646:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5647:         if ($action ne 'reload') {
1.985     raeburn  5648:             if ($context eq 'requestcourses') {
                   5649:                 return $env{'environment.canrequest.'.$tool};
                   5650:             } else {
                   5651:                 return $env{'environment.availabletools.'.$tool};
                   5652:             }
                   5653:         }
1.976     raeburn  5654:     }
                   5655: 
                   5656:     my ($toolstatus,$inststatus);
                   5657: 
1.985     raeburn  5658:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5659:          ($action ne 'reload')) {
                   5660:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5661:         $inststatus = $env{'environment.inststatus'};
                   5662:     } else {
1.1084    raeburn  5663:         if (ref($userenvref) eq 'HASH') {
                   5664:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5665:             $inststatus = $userenvref->{'inststatus'};
                   5666:         } else {
                   5667:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5668:             $toolstatus = $userenv{$context.'.'.$tool};
                   5669:             $inststatus = $userenv{'inststatus'};
                   5670:         }
1.976     raeburn  5671:     }
                   5672: 
                   5673:     if ($toolstatus ne '') {
                   5674:         if ($toolstatus) {
                   5675:             $access = 1;
                   5676:         } else {
                   5677:             $access = 0;
                   5678:         }
                   5679:         return $access;
                   5680:     }
                   5681: 
1.1084    raeburn  5682:     my ($is_adv,%domdef);
                   5683:     if (ref($is_advref) eq 'HASH') {
                   5684:         $is_adv = $is_advref->{'is_adv'};
                   5685:     } else {
                   5686:         $is_adv = &is_advanced_user($udom,$uname);
                   5687:     }
                   5688:     if (ref($domdefref) eq 'HASH') {
                   5689:         %domdef = %{$domdefref};
                   5690:     } else {
                   5691:         %domdef = &get_domain_defaults($udom);
                   5692:     }
1.976     raeburn  5693:     if (ref($domdef{$tool}) eq 'HASH') {
                   5694:         if ($is_adv) {
                   5695:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5696:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5697:                     $access = 1;
                   5698:                 } else {
                   5699:                     $access = 0;
                   5700:                 }
                   5701:                 return $access;
                   5702:             }
                   5703:         }
                   5704:         if ($inststatus ne '') {
                   5705:             my ($hasaccess,$hasnoaccess);
                   5706:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5707:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5708:                     if ($domdef{$tool}{$affiliation}) {
                   5709:                         $hasaccess = 1;
                   5710:                     } else {
                   5711:                         $hasnoaccess = 1;
                   5712:                     }
                   5713:                 }
                   5714:             }
                   5715:             if ($hasaccess || $hasnoaccess) {
                   5716:                 if ($hasaccess) {
                   5717:                     $access = 1;
                   5718:                 } elsif ($hasnoaccess) {
                   5719:                     $access = 0; 
                   5720:                 }
                   5721:                 return $access;
                   5722:             }
                   5723:         } else {
                   5724:             if ($domdef{$tool}{'default'} ne '') {
                   5725:                 if ($domdef{$tool}{'default'}) {
                   5726:                     $access = 1;
                   5727:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5728:                     $access = 0;
                   5729:                 }
                   5730:                 return $access;
                   5731:             }
                   5732:         }
                   5733:     } else {
1.985     raeburn  5734:         if ($context eq 'tools') {
                   5735:             $access = 1;
                   5736:         } else {
                   5737:             $access = 0;
                   5738:         }
1.976     raeburn  5739:         return $access;
                   5740:     }
                   5741: }
                   5742: 
1.1050    raeburn  5743: sub is_course_owner {
                   5744:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5745:     if (($udom eq '') || ($uname eq '')) {
                   5746:         $udom = $env{'user.domain'};
                   5747:         $uname = $env{'user.name'};
                   5748:     }
                   5749:     unless (($udom eq '') || ($uname eq '')) {
                   5750:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5751:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5752:                 return 1;
                   5753:             } else {
                   5754:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5755:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5756:                     return 1;
                   5757:                 }
                   5758:             }
                   5759:         }
                   5760:     }
                   5761:     return;
                   5762: }
                   5763: 
1.976     raeburn  5764: sub is_advanced_user {
                   5765:     my ($udom,$uname) = @_;
1.1085    raeburn  5766:     if ($udom ne '' && $uname ne '') {
                   5767:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5768:             if (wantarray) {
                   5769:                 return ($env{'user.adv'},$env{'user.author'});
                   5770:             } else {
                   5771:                 return $env{'user.adv'};
                   5772:             }
1.1085    raeburn  5773:         }
                   5774:     }
1.976     raeburn  5775:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5776:     my %allroles;
1.1128    raeburn  5777:     my ($is_adv,$is_author);
1.976     raeburn  5778:     foreach my $role (keys(%roleshash)) {
                   5779:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5780:         my $area = '/'.$tdomain.'/'.$trest;
                   5781:         if ($sec ne '') {
                   5782:             $area .= '/'.$sec;
                   5783:         }
                   5784:         if (($area ne '') && ($trole ne '')) {
                   5785:             my $spec=$trole.'.'.$area;
                   5786:             if ($trole =~ /^cr\//) {
                   5787:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5788:             } elsif ($trole ne 'gr') {
                   5789:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5790:             }
1.1128    raeburn  5791:             if ($trole eq 'au') {
                   5792:                 $is_author = 1;
                   5793:             }
1.976     raeburn  5794:         }
                   5795:     }
                   5796:     foreach my $role (keys(%allroles)) {
                   5797:         last if ($is_adv);
                   5798:         foreach my $item (split(/:/,$allroles{$role})) {
                   5799:             if ($item ne '') {
                   5800:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5801:                 if ($privilege eq 'adv') {
                   5802:                     $is_adv = 1;
                   5803:                     last;
                   5804:                 }
                   5805:             }
                   5806:         }
                   5807:     }
1.1128    raeburn  5808:     if (wantarray) {
                   5809:         return ($is_adv,$is_author);
                   5810:     }
1.976     raeburn  5811:     return $is_adv;
                   5812: }
1.798     raeburn  5813: 
1.1035    raeburn  5814: sub check_can_request {
1.1036    raeburn  5815:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5816:     my $canreq = 0;
                   5817:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5818:     my @options = ('approval','validate','autolimit');
                   5819:     my $optregex = join('|',@options);
                   5820:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5821:         foreach my $type (@{$types}) {
                   5822:             if (&usertools_access($env{'user.name'},
                   5823:                                   $env{'user.domain'},
                   5824:                                   $type,undef,'requestcourses')) {
                   5825:                 $canreq ++;
1.1036    raeburn  5826:                 if (ref($request_domains) eq 'HASH') {
                   5827:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5828:                 }
1.1035    raeburn  5829:                 if ($dom eq $env{'user.domain'}) {
                   5830:                     $can_request->{$type} = 1;
                   5831:                 }
                   5832:             }
                   5833:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5834:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5835:                 if (@curr > 0) {
1.1036    raeburn  5836:                     foreach my $item (@curr) {
                   5837:                         if (ref($request_domains) eq 'HASH') {
                   5838:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5839:                             if ($otherdom ne '') {
                   5840:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5841:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5842:                                         push(@{$request_domains->{$type}},$otherdom);
                   5843:                                     }
                   5844:                                 } else {
                   5845:                                     push(@{$request_domains->{$type}},$otherdom);
                   5846:                                 }
                   5847:                             }
                   5848:                         }
                   5849:                     }
                   5850:                     unless($dom eq $env{'user.domain'}) {
                   5851:                         $canreq ++;
1.1035    raeburn  5852:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5853:                             $can_request->{$type} = 1;
                   5854:                         }
                   5855:                     }
                   5856:                 }
                   5857:             }
                   5858:         }
                   5859:     }
                   5860:     return $canreq;
                   5861: }
                   5862: 
1.341     www      5863: # ---------------------------------------------- Custom access rule evaluation
                   5864: 
                   5865: sub customaccess {
                   5866:     my ($priv,$uri)=@_;
1.807     albertel 5867:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5868:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5869:     $udom = &LONCAPA::clean_domain($udom);
                   5870:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5871:     my $access=0;
1.800     albertel 5872:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5873: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5874: 	if ($type eq 'user') {
                   5875: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5876: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5877: 		if ($tdom) {
                   5878: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5879: 		}
1.896     albertel 5880: 		if ($tuname) {
                   5881: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5882: 		}
                   5883: 		$access=($effect eq 'allow');
                   5884: 		last;
                   5885: 	    }
                   5886: 	} else {
                   5887: 	    if ($role) {
                   5888: 		if ($role ne $urole) { next; }
                   5889: 	    }
                   5890: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5891: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5892: 		if ($tdom) {
                   5893: 		    if ($tdom ne $udom) { next; }
                   5894: 		}
                   5895: 		if ($tcrs) {
                   5896: 		    if ($tcrs ne $ucrs) { next; }
                   5897: 		}
                   5898: 		if ($tsec) {
                   5899: 		    if ($tsec ne $usec) { next; }
                   5900: 		}
                   5901: 		$access=($effect eq 'allow');
                   5902: 		last;
                   5903: 	    }
                   5904: 	    if ($realm eq '' && $role eq '') {
                   5905: 		$access=($effect eq 'allow');
                   5906: 	    }
1.402     bowersj2 5907: 	}
1.341     www      5908:     }
                   5909:     return $access;
                   5910: }
                   5911: 
1.103     harris41 5912: # ------------------------------------------------- Check for a user privilege
1.12      www      5913: 
                   5914: sub allowed {
1.810     raeburn  5915:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5916:     my $ver_orguri=$uri;
1.439     www      5917:     $uri=&deversion($uri);
1.152     www      5918:     my $orguri=$uri;
1.52      www      5919:     $uri=&declutter($uri);
1.809     raeburn  5920: 
1.810     raeburn  5921:     if ($priv eq 'evb') {
                   5922: # Evade communication block restrictions for specified role in a course
                   5923:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5924:             return $1;
                   5925:         } else {
                   5926:             return;
                   5927:         }
                   5928:     }
                   5929: 
1.620     albertel 5930:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5931: # Free bre access to adm and meta resources
1.775     albertel 5932:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5933: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5934: 	&& ($priv eq 'bre')) {
1.14      www      5935: 	return 'F';
1.159     www      5936:     }
                   5937: 
1.545     banghart 5938: # Free bre access to user's own portfolio contents
1.714     raeburn  5939:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5940:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5941: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5942:         my %setters;
                   5943:         my ($startblock,$endblock) = 
                   5944:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5945:         if ($startblock && $endblock) {
                   5946:             return 'B';
                   5947:         } else {
                   5948:             return 'F';
                   5949:         }
1.545     banghart 5950:     }
                   5951: 
1.762     raeburn  5952: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5953:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5954:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5955:         if (exists($env{'request.course.id'})) {
                   5956:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5957:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5958:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5959:                 my $courseprivid=$env{'request.course.id'};
                   5960:                 $courseprivid=~s/\_/\//;
                   5961:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5962:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5963:                     return $1; 
1.762     raeburn  5964:                 } else {
                   5965:                     if ($env{'request.course.sec'}) {
                   5966:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5967:                     }
                   5968:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5969:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5970:                         return $2;
                   5971:                     }
1.714     raeburn  5972:                 }
                   5973:             }
                   5974:         }
                   5975:     }
                   5976: 
1.159     www      5977: # Free bre to public access
                   5978: 
                   5979:     if ($priv eq 'bre') {
1.238     www      5980:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5981: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5982:            return 'F'; 
                   5983:         }
1.238     www      5984:         if ($copyright eq 'priv') {
                   5985:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5986: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5987: 		return '';
                   5988:             }
                   5989:         }
                   5990:         if ($copyright eq 'domain') {
                   5991:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5992: 	    unless (($env{'user.domain'} eq $1) ||
                   5993:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5994: 		return '';
                   5995:             }
1.262     matthew  5996:         }
1.620     albertel 5997:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5998:             # Library role, so allow browsing of resources in this domain.
                   5999:             return 'F';
1.238     www      6000:         }
1.341     www      6001:         if ($copyright eq 'custom') {
                   6002: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6003:         }
1.14      www      6004:     }
1.264     matthew  6005:     # Domain coordinator is trying to create a course
1.620     albertel 6006:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6007:         # uri is the requested domain in this case.
                   6008:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6009:         # a role of dc for the domain in question.
1.620     albertel 6010:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6011:     }
1.29      www      6012: 
1.52      www      6013:     my $thisallowed='';
                   6014:     my $statecond=0;
                   6015:     my $courseprivid='';
                   6016: 
1.1039    raeburn  6017:     my $ownaccess;
1.1043    raeburn  6018:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6019:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6020:         if ($uri eq '') {
                   6021:             $ownaccess = 1;
                   6022:         } else {
                   6023:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6024:                 my $udom = $env{'user.domain'};
                   6025:                 my $uname = $env{'user.name'};
                   6026:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6027:                     $ownaccess = 1;
1.1040    raeburn  6028:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6029:                     unless ($uri =~ m{\.\./}) {
                   6030:                         $ownaccess = 1;
                   6031:                     }
                   6032:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6033:                     my $now = time;
                   6034:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6035:                         my $adom = $1;
                   6036:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6037:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6038:                                 my ($start,$end) = split('.',$env{$key});
                   6039:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6040:                                     $ownaccess = 1;
                   6041:                                     last;
                   6042:                                 }
                   6043:                             }
                   6044:                         }
                   6045:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6046:                         my $adom = $1;
                   6047:                         my $aname = $2;
1.1042    raeburn  6048:                         foreach my $role ('ca','aa') { 
                   6049:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6050:                                 my ($start,$end) =
                   6051:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6052:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6053:                                     $ownaccess = 1;
                   6054:                                     last;
                   6055:                                 }
1.1039    raeburn  6056:                             }
                   6057:                         }
                   6058:                     }
                   6059:                 }
                   6060:             }
                   6061:         }
                   6062:     }
                   6063: 
1.52      www      6064: # Course
                   6065: 
1.620     albertel 6066:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6067:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6068:             $thisallowed.=$1;
                   6069:         }
1.52      www      6070:     }
1.29      www      6071: 
1.52      www      6072: # Domain
                   6073: 
1.620     albertel 6074:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6075:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6076:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6077:             $thisallowed.=$1;
                   6078:         }
1.12      www      6079:     }
1.52      www      6080: 
1.1141    raeburn  6081: # User who is not author or co-author might still be able to edit
                   6082: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6083:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6084:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6085:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6086:             $thisallowed.=$1;
                   6087:         }
                   6088:     }
                   6089: 
1.52      www      6090: # Course: uri itself is a course
1.66      www      6091:     my $courseuri=$uri;
                   6092:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6093:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6094: 
1.620     albertel 6095:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6096:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6097:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6098:             $thisallowed.=$1;
                   6099:         }
1.12      www      6100:     }
1.29      www      6101: 
1.665     albertel 6102: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6103: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6104:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6105: 	$thisallowed='';
1.671     raeburn  6106:         my ($match)=&is_on_map($uri);
                   6107:         if ($match) {
                   6108:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6109:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6110:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6111:                 if (@blockers > 0) {
                   6112:                     $thisallowed = 'B';
                   6113:                 } else {
                   6114:                     $thisallowed.=$1;
                   6115:                 }
1.671     raeburn  6116:             }
                   6117:         } else {
1.705     albertel 6118:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6119:             if ($refuri) {
                   6120:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6121:                     $thisallowed='F';
1.671     raeburn  6122:                 } else {
                   6123:                     $refuri=&declutter($refuri);
                   6124:                     my ($match) = &is_on_map($refuri);
                   6125:                     if ($match) {
1.1162    raeburn  6126:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6127:                         if (@blockers > 0) {
                   6128:                             $thisallowed = 'B';
                   6129:                         } else {
                   6130:                             $thisallowed='F';
                   6131:                         }
1.671     raeburn  6132:                     }
1.669     raeburn  6133:                 }
1.671     raeburn  6134:             }
                   6135:         }
1.314     www      6136:     }
1.492     albertel 6137: 
1.766     albertel 6138:     if ($priv eq 'bre'
                   6139: 	&& $thisallowed ne 'F' 
                   6140: 	&& $thisallowed ne '2'
                   6141: 	&& &is_portfolio_url($uri)) {
                   6142: 	$thisallowed = &portfolio_access($uri);
                   6143:     }
                   6144:     
1.52      www      6145: # Full access at system, domain or course-wide level? Exit.
1.29      www      6146:     if ($thisallowed=~/F/) {
                   6147: 	return 'F';
                   6148:     }
                   6149: 
1.52      www      6150: # If this is generating or modifying users, exit with special codes
1.29      www      6151: 
1.643     www      6152:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6153: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6154: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6155: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6156: 	    unless ($auname) { return $thisallowed; }
                   6157: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6158: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6159: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6160: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6161: 	}
1.52      www      6162: 	return $thisallowed;
                   6163:     }
                   6164: #
1.103     harris41 6165: # Gathered so far: system, domain and course wide privileges
1.52      www      6166: #
                   6167: # Course: See if uri or referer is an individual resource that is part of 
                   6168: # the course
                   6169: 
1.620     albertel 6170:     if ($env{'request.course.id'}) {
1.232     www      6171: 
1.620     albertel 6172:        $courseprivid=$env{'request.course.id'};
                   6173:        if ($env{'request.course.sec'}) {
                   6174:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6175:        }
                   6176:        $courseprivid=~s/\_/\//;
                   6177:        my $checkreferer=1;
1.232     www      6178:        my ($match,$cond)=&is_on_map($uri);
                   6179:        if ($match) {
                   6180:            $statecond=$cond;
1.620     albertel 6181:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6182:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6183:                my $value = $1;
                   6184:                if ($priv eq 'bre') {
                   6185:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6186:                    if (@blockers > 0) {
                   6187:                        $thisallowed = 'B';
                   6188:                    } else {
                   6189:                        $thisallowed.=$value;
                   6190:                    }
                   6191:                } else {
                   6192:                    $thisallowed.=$value;
                   6193:                }
1.52      www      6194:                $checkreferer=0;
                   6195:            }
1.29      www      6196:        }
1.83      www      6197:        
1.148     www      6198:        if ($checkreferer) {
1.620     albertel 6199: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6200:             unless ($refuri) {
1.800     albertel 6201:                 foreach my $key (keys(%env)) {
                   6202: 		    if ($key=~/^httpref\..*\*/) {
                   6203: 			my $pattern=$key;
1.156     www      6204:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6205:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6206:                         $pattern=~s/\//\\\//g;
1.152     www      6207:                         if ($orguri=~/$pattern/) {
1.800     albertel 6208: 			    $refuri=$env{$key};
1.148     www      6209:                         }
                   6210:                     }
1.191     harris41 6211:                 }
1.148     www      6212:             }
1.232     www      6213: 
1.148     www      6214:          if ($refuri) { 
1.152     www      6215: 	  $refuri=&declutter($refuri);
1.232     www      6216:           my ($match,$cond)=&is_on_map($refuri);
                   6217:             if ($match) {
                   6218:               my $refstatecond=$cond;
1.620     albertel 6219:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6220:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6221:                   my $value = $1;
                   6222:                   if ($priv eq 'bre') {
                   6223:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6224:                       if (@blockers > 0) {
                   6225:                           $thisallowed = 'B';
                   6226:                       } else {
                   6227:                           $thisallowed.=$value;
                   6228:                       }
                   6229:                   } else {
                   6230:                       $thisallowed.=$value;
                   6231:                   }
1.53      www      6232:                   $uri=$refuri;
                   6233:                   $statecond=$refstatecond;
1.52      www      6234:               }
                   6235:           }
1.148     www      6236:         }
1.29      www      6237:        }
1.52      www      6238:    }
1.29      www      6239: 
1.52      www      6240: #
1.103     harris41 6241: # Gathered now: all privileges that could apply, and condition number
1.52      www      6242: # 
                   6243: #
                   6244: # Full or no access?
                   6245: #
1.29      www      6246: 
1.52      www      6247:     if ($thisallowed=~/F/) {
                   6248: 	return 'F';
                   6249:     }
1.29      www      6250: 
1.52      www      6251:     unless ($thisallowed) {
                   6252:         return '';
                   6253:     }
1.29      www      6254: 
1.52      www      6255: # Restrictions exist, deal with them
                   6256: #
                   6257: #   C:according to course preferences
                   6258: #   R:according to resource settings
                   6259: #   L:unless locked
                   6260: #   X:according to user session state
                   6261: #
                   6262: 
                   6263: # Possibly locked functionality, check all courses
1.54      www      6264: # Locks might take effect only after 10 minutes cache expiration for other
                   6265: # courses, and 2 minutes for current course
1.52      www      6266: 
                   6267:     my $envkey;
                   6268:     if ($thisallowed=~/L/) {
1.1000    raeburn  6269:         foreach $envkey (keys(%env)) {
1.54      www      6270:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6271:                my $courseid=$2;
                   6272:                my $roleid=$1.'.'.$2;
1.92      www      6273:                $courseid=~s/^\///;
1.54      www      6274:                my $expiretime=600;
1.620     albertel 6275:                if ($env{'request.role'} eq $roleid) {
1.54      www      6276: 		  $expiretime=120;
                   6277:                }
                   6278: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6279:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6280:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6281: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6282:                }
1.620     albertel 6283:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6284:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6285: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6286:                        &log($env{'user.domain'},$env{'user.name'},
                   6287:                             $env{'user.home'},
1.57      www      6288:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6289:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6290:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6291: 		       return '';
                   6292:                    }
                   6293:                }
1.620     albertel 6294:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6295:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6296: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6297:                        &log($env{'user.domain'},$env{'user.name'},
                   6298:                             $env{'user.home'},
1.57      www      6299:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6300:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6301:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6302: 		       return '';
                   6303:                    }
                   6304:                }
                   6305: 	   }
1.29      www      6306:        }
1.52      www      6307:     }
                   6308:    
                   6309: #
                   6310: # Rest of the restrictions depend on selected course
                   6311: #
                   6312: 
1.620     albertel 6313:     unless ($env{'request.course.id'}) {
1.766     albertel 6314: 	if ($thisallowed eq 'A') {
                   6315: 	    return 'A';
1.814     raeburn  6316:         } elsif ($thisallowed eq 'B') {
                   6317:             return 'B';
1.766     albertel 6318: 	} else {
                   6319: 	    return '1';
                   6320: 	}
1.52      www      6321:     }
1.29      www      6322: 
1.52      www      6323: #
                   6324: # Now user is definitely in a course
                   6325: #
1.53      www      6326: 
                   6327: 
                   6328: # Course preferences
                   6329: 
                   6330:    if ($thisallowed=~/C/) {
1.620     albertel 6331:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6332:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6333:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6334: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6335: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6336: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6337: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6338: 			$env{'request.course.id'});
                   6339: 	   }
1.237     www      6340:            return '';
                   6341:        }
                   6342: 
1.620     albertel 6343:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6344: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6345: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6346: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6347: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6348: 			$env{'request.course.id'});
                   6349: 	   }
1.54      www      6350:            return '';
                   6351:        }
1.53      www      6352:    }
                   6353: 
                   6354: # Resource preferences
                   6355: 
                   6356:    if ($thisallowed=~/R/) {
1.620     albertel 6357:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6358:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6359: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6360: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6361: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6362: 	   }
                   6363: 	   return '';
1.54      www      6364:        }
1.53      www      6365:    }
1.30      www      6366: 
1.246     www      6367: # Restricted by state or randomout?
1.30      www      6368: 
1.52      www      6369:    if ($thisallowed=~/X/) {
1.620     albertel 6370:       if ($env{'acc.randomout'}) {
1.579     albertel 6371: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6372:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6373:             return ''; 
                   6374:          }
1.247     www      6375:       }
                   6376:       if (&condval($statecond)) {
1.52      www      6377: 	 return '2';
                   6378:       } else {
                   6379:          return '';
                   6380:       }
                   6381:    }
1.30      www      6382: 
1.766     albertel 6383:     if ($thisallowed eq 'A') {
                   6384: 	return 'A';
1.814     raeburn  6385:     } elsif ($thisallowed eq 'B') {
                   6386:         return 'B';
1.766     albertel 6387:     }
1.52      www      6388:    return 'F';
1.232     www      6389: }
1.1162    raeburn  6390: 
                   6391: sub get_comm_blocks {
                   6392:     my ($cdom,$cnum) = @_;
                   6393:     if ($cdom eq '' || $cnum eq '') {
                   6394:         return unless ($env{'request.course.id'});
                   6395:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6396:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6397:     }
                   6398:     my %commblocks;
                   6399:     my $hashid=$cdom.'_'.$cnum;
                   6400:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6401:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6402:         %commblocks = %{$blocksref};
                   6403:     } else {
                   6404:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6405:         my $cachetime = 600;
                   6406:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6407:     }
                   6408:     return %commblocks;
                   6409: }
                   6410: 
                   6411: sub has_comm_blocking {
                   6412:     my ($priv,$symb,$uri,$blocks) = @_;
                   6413:     return unless ($env{'request.course.id'});
                   6414:     return unless ($priv eq 'bre');
                   6415:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6416:     my %commblocks;
                   6417:     if (ref($blocks) eq 'HASH') {
                   6418:         %commblocks = %{$blocks};
                   6419:     } else {
                   6420:         %commblocks = &get_comm_blocks();
                   6421:     }
                   6422:     return unless (keys(%commblocks) > 0);
                   6423:     if (!$symb) { $symb=&symbread($uri,1); }
                   6424:     my ($map,$resid,undef)=&decode_symb($symb);
                   6425:     my %tocheck = (
                   6426:                     maps      => $map,
                   6427:                     resources => $symb,
                   6428:                   );
                   6429:     my @blockers;
                   6430:     my $now = time;
1.1163    raeburn  6431:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6432:     foreach my $block (keys(%commblocks)) {
                   6433:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6434:             my ($start,$end) = ($1,$2);
                   6435:             if ($start <= $now && $end >= $now) {
                   6436:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6437:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6438:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6439:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6440:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6441:                                     push(@blockers,$block);
                   6442:                                 }
                   6443:                             }
                   6444:                         }
                   6445:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6446:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6447:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6448:                                     push(@blockers,$block);
                   6449:                                 }
                   6450:                             }
                   6451:                         }
                   6452:                     }
                   6453:                 }
                   6454:             }
                   6455:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6456:             my $item = $1;
1.1163    raeburn  6457:             my @to_test;
1.1162    raeburn  6458:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6459:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6460:                     my $check_interval;
                   6461:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6462:                         my @interval;
                   6463:                         my $type = 'map';
                   6464:                         if ($item eq 'course') {
                   6465:                             $type = 'course';
                   6466:                             @interval=&EXT("resource.0.interval");
                   6467:                         } else {
                   6468:                             if ($item =~ /___\d+___/) {
                   6469:                                 $type = 'resource';
                   6470:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6471:                                 if (ref($navmap)) {                        
                   6472:                                     my $res = $navmap->getBySymb($item); 
                   6473:                                     push(@to_test,$res);
                   6474:                                 }
1.1162    raeburn  6475:                             } else {
                   6476:                                 my $mapsymb = &symbread($item,1);
                   6477:                                 if ($mapsymb) {
                   6478:                                     if (ref($navmap)) {
                   6479:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6480:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6481:                                         foreach my $res (@to_test) {
1.1162    raeburn  6482:                                             my $symb = $res->symb();
                   6483:                                             next if ($symb eq $mapsymb);
                   6484:                                             if ($symb ne '') {
                   6485:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6486:                                                 last;
                   6487:                                             }
                   6488:                                         }
                   6489:                                     }
                   6490:                                 }
                   6491:                             }
                   6492:                         }
                   6493:                         if ($interval[0] =~ /\d+/) {
                   6494:                             my $first_access;
                   6495:                             if ($type eq 'resource') {
                   6496:                                 $first_access=&get_first_access($interval[1],$item);
                   6497:                             } elsif ($type eq 'map') {
                   6498:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6499:                             } else {
                   6500:                                 $first_access=&get_first_access($interval[1]);
                   6501:                             }
                   6502:                             if ($first_access) {
                   6503:                                 my $timesup = $first_access+$interval[0];
                   6504:                                 if ($timesup > $now) {
1.1163    raeburn  6505:                                     foreach my $res (@to_test) {
                   6506:                                         if ($res->is_problem()) {
                   6507:                                             if ($res->completable()) {
                   6508:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6509:                                                     push(@blockers,$block);
                   6510:                                                 }
                   6511:                                                 last;
                   6512:                                             }
                   6513:                                         }
1.1162    raeburn  6514:                                     }
                   6515:                                 }
                   6516:                             }
                   6517:                         }
                   6518:                     }
                   6519:                 }
                   6520:             }
                   6521:         }
                   6522:     }
                   6523:     return @blockers;
                   6524: }
                   6525: 
                   6526: sub check_docs_block {
                   6527:     my ($docsblock,$tocheck) =@_;
                   6528:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6529:         return;
                   6530:     }
                   6531:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6532:         if ($tocheck->{'maps'}) {
                   6533:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6534:                 return 1;
                   6535:             }
                   6536:         }
                   6537:     }
                   6538:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6539:         if ($tocheck->{'resources'}) {
                   6540:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6541:                 return 1;
                   6542:             }
                   6543:         }
                   6544:     }
                   6545:     return;
                   6546: }
                   6547: 
1.1133    foxr     6548: #
                   6549: #   Removes the versino from a URI and
                   6550: #   splits it in to its filename and path to the filename.
                   6551: #   Seems like File::Basename could have done this more clearly.
                   6552: #   Parameters:
                   6553: #      $uri   - input URI
                   6554: #   Returns:
                   6555: #     Two element list consisting of 
                   6556: #     $pathname  - the URI up to and excluding the trailing /
                   6557: #     $filename  - The part of the URI following the last /
                   6558: #  NOTE:
                   6559: #    Another realization of this is simply:
                   6560: #    use File::Basename;
                   6561: #    ...
                   6562: #    $uri = shift;
                   6563: #    $filename = basename($uri);
                   6564: #    $path     = dirname($uri);
                   6565: #    return ($filename, $path);
                   6566: #
                   6567: #     The implementation below is probably faster however.
                   6568: #
1.710     albertel 6569: sub split_uri_for_cond {
                   6570:     my $uri=&deversion(&declutter(shift));
                   6571:     my @uriparts=split(/\//,$uri);
                   6572:     my $filename=pop(@uriparts);
                   6573:     my $pathname=join('/',@uriparts);
                   6574:     return ($pathname,$filename);
                   6575: }
1.232     www      6576: # --------------------------------------------------- Is a resource on the map?
                   6577: 
                   6578: sub is_on_map {
1.710     albertel 6579:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6580:     #Trying to find the conditional for the file
1.620     albertel 6581:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6582: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6583:     if ($match) {
1.289     bowersj2 6584: 	return (1,$1);
                   6585:     } else {
1.434     www      6586: 	return (0,0);
1.289     bowersj2 6587:     }
1.12      www      6588: }
                   6589: 
1.427     www      6590: # --------------------------------------------------------- Get symb from alias
                   6591: 
                   6592: sub get_symb_from_alias {
                   6593:     my $symb=shift;
                   6594:     my ($map,$resid,$url)=&decode_symb($symb);
                   6595: # Already is a symb
                   6596:     if ($url) { return $symb; }
                   6597: # Must be an alias
                   6598:     my $aliassymb='';
                   6599:     my %bighash;
1.620     albertel 6600:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6601:                             &GDBM_READER(),0640)) {
                   6602:         my $rid=$bighash{'mapalias_'.$symb};
                   6603: 	if ($rid) {
                   6604: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6605: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6606: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6607: 	}
                   6608:         untie %bighash;
                   6609:     }
                   6610:     return $aliassymb;
                   6611: }
                   6612: 
1.12      www      6613: # ----------------------------------------------------------------- Define Role
                   6614: 
                   6615: sub definerole {
                   6616:   if (allowed('mcr','/')) {
                   6617:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6618:     foreach my $role (split(':',$sysrole)) {
                   6619: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6620:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6621:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6622: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6623:                return "refused:s:$crole&$cqual"; 
                   6624:             }
                   6625:         }
1.191     harris41 6626:     }
1.800     albertel 6627:     foreach my $role (split(':',$domrole)) {
                   6628: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6629:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6630:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6631: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6632:                return "refused:d:$crole&$cqual"; 
                   6633:             }
                   6634:         }
1.191     harris41 6635:     }
1.800     albertel 6636:     foreach my $role (split(':',$courole)) {
                   6637: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6638:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6639:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6640: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6641:                return "refused:c:$crole&$cqual"; 
                   6642:             }
                   6643:         }
1.191     harris41 6644:     }
1.620     albertel 6645:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6646:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6647: 	        "rolesdef_$rolename=".
                   6648:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6649:     return reply($command,$env{'user.home'});
1.12      www      6650:   } else {
                   6651:     return 'refused';
                   6652:   }
1.105     harris41 6653: }
                   6654: 
                   6655: # ---------------- Make a metadata query against the network of library servers
                   6656: 
                   6657: sub metadata_query {
1.244     matthew  6658:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6659:     my %rhash;
1.845     albertel 6660:     my %libserv = &all_library();
1.244     matthew  6661:     my @server_list = (defined($server_array) ? @$server_array
                   6662:                                               : keys(%libserv) );
                   6663:     for my $server (@server_list) {
1.118     harris41 6664: 	unless ($custom or $customshow) {
                   6665: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6666: 	    $rhash{$server}=$reply;
                   6667: 	}
                   6668: 	else {
                   6669: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6670: 			     &escape($custom).':'.&escape($customshow),
                   6671: 			     $server);
                   6672: 	    $rhash{$server}=$reply;
                   6673: 	}
1.112     harris41 6674:     }
1.118     harris41 6675:     return \%rhash;
1.240     www      6676: }
                   6677: 
                   6678: # ----------------------------------------- Send log queries and wait for reply
                   6679: 
                   6680: sub log_query {
                   6681:     my ($uname,$udom,$query,%filters)=@_;
                   6682:     my $uhome=&homeserver($uname,$udom);
                   6683:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6684:     my $uhost=&hostname($uhome);
1.800     albertel 6685:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6686:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6687:                        $uhome);
1.479     albertel 6688:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6689:     return get_query_reply($queryid);
                   6690: }
                   6691: 
1.818     raeburn  6692: # -------------------------- Update MySQL table for portfolio file
                   6693: 
                   6694: sub update_portfolio_table {
1.821     raeburn  6695:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6696:     if ($group ne '') {
                   6697:         $file_name =~s /^\Q$group\E//;
                   6698:     }
1.818     raeburn  6699:     my $homeserver = &homeserver($uname,$udom);
                   6700:     my $queryid=
1.821     raeburn  6701:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6702:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6703:     my $reply = &get_query_reply($queryid);
                   6704:     return $reply;
                   6705: }
                   6706: 
1.899     raeburn  6707: # -------------------------- Update MySQL allusers table
                   6708: 
                   6709: sub update_allusers_table {
                   6710:     my ($uname,$udom,$names) = @_;
                   6711:     my $homeserver = &homeserver($uname,$udom);
                   6712:     my $queryid=
                   6713:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6714:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6715:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6716:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6717:                'generation='.&escape($names->{'generation'}).'%%'.
                   6718:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6719:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6720:     return;
1.899     raeburn  6721: }
                   6722: 
1.508     raeburn  6723: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6724: 
                   6725: sub fetch_enrollment_query {
1.511     raeburn  6726:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6727:     my $homeserver;
1.547     raeburn  6728:     my $maxtries = 1;
1.508     raeburn  6729:     if ($context eq 'automated') {
                   6730:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6731:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6732:     } else {
                   6733:         $homeserver = &homeserver($cnum,$dom);
                   6734:     }
1.838     albertel 6735:     my $host=&hostname($homeserver);
1.506     raeburn  6736:     my $cmd = '';
1.1000    raeburn  6737:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6738:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6739:     }
                   6740:     $cmd =~ s/%%$//;
                   6741:     $cmd = &escape($cmd);
                   6742:     my $query = 'fetchenrollment';
1.620     albertel 6743:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6744:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6745:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6746:         return 'error: '.$queryid;
                   6747:     }
1.506     raeburn  6748:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6749:     my $tries = 1;
                   6750:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6751:         $reply = &get_query_reply($queryid);
                   6752:         $tries ++;
                   6753:     }
1.526     raeburn  6754:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6755:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6756:     } else {
1.901     albertel 6757:         my @responses = split(/:/,$reply);
1.515     raeburn  6758:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6759:             foreach my $line (@responses) {
                   6760:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6761:                 $$replyref{$key} = $value;
                   6762:             }
                   6763:         } else {
1.1117    foxr     6764:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6765:             foreach my $line (@responses) {
                   6766:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6767:                 $$replyref{$key} = $value;
                   6768:                 if ($value > 0) {
1.800     albertel 6769:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6770:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6771:                         my $destname = $pathname.'/'.$filename;
                   6772:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6773:                         if ($xml_classlist =~ /^error/) {
                   6774:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6775:                         } else {
1.506     raeburn  6776:                             if ( open(FILE,">$destname") ) {
                   6777:                                 print FILE &unescape($xml_classlist);
                   6778:                                 close(FILE);
1.526     raeburn  6779:                             } else {
                   6780:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6781:                             }
                   6782:                         }
                   6783:                     }
                   6784:                 }
                   6785:             }
                   6786:         }
                   6787:         return 'ok';
                   6788:     }
                   6789:     return 'error';
                   6790: }
                   6791: 
1.242     www      6792: sub get_query_reply {
                   6793:     my $queryid=shift;
1.1117    foxr     6794:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6795:     my $reply='';
                   6796:     for (1..100) {
                   6797: 	sleep 2;
                   6798:         if (-e $replyfile.'.end') {
1.448     albertel 6799: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6800: 		$reply = join('',<$fh>);
                   6801: 		close($fh);
1.240     www      6802: 	   } else { return 'error: reply_file_error'; }
1.242     www      6803:            return &unescape($reply);
                   6804: 	}
1.240     www      6805:     }
1.242     www      6806:     return 'timeout:'.$queryid;
1.240     www      6807: }
                   6808: 
                   6809: sub courselog_query {
1.241     www      6810: #
                   6811: # possible filters:
                   6812: # url: url or symb
                   6813: # username
                   6814: # domain
                   6815: # action: view, submit, grade
                   6816: # start: timestamp
                   6817: # end: timestamp
                   6818: #
1.240     www      6819:     my (%filters)=@_;
1.620     albertel 6820:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6821:     if ($filters{'url'}) {
                   6822: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6823:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6824:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6825:     }
1.620     albertel 6826:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6827:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6828:     return &log_query($cname,$cdom,'courselog',%filters);
                   6829: }
                   6830: 
                   6831: sub userlog_query {
1.858     raeburn  6832: #
                   6833: # possible filters:
                   6834: # action: log check role
                   6835: # start: timestamp
                   6836: # end: timestamp
                   6837: #
1.240     www      6838:     my ($uname,$udom,%filters)=@_;
                   6839:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6840: }
                   6841: 
1.506     raeburn  6842: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6843: 
                   6844: sub auto_run {
1.508     raeburn  6845:     my ($cnum,$cdom) = @_;
1.876     raeburn  6846:     my $response = 0;
                   6847:     my $settings;
                   6848:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6849:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6850:         $settings = $domconfig{'autoenroll'};
                   6851:         if ($settings->{'run'} eq '1') {
                   6852:             $response = 1;
                   6853:         }
                   6854:     } else {
1.934     raeburn  6855:         my $homeserver;
                   6856:         if (&is_course($cdom,$cnum)) {
                   6857:             $homeserver = &homeserver($cnum,$cdom);
                   6858:         } else {
                   6859:             $homeserver = &domain($cdom,'primary');
                   6860:         }
                   6861:         if ($homeserver ne 'no_host') {
                   6862:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6863:         }
1.876     raeburn  6864:     }
1.506     raeburn  6865:     return $response;
                   6866: }
1.776     albertel 6867: 
1.506     raeburn  6868: sub auto_get_sections {
1.508     raeburn  6869:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6870:     my $homeserver;
                   6871:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6872:         $homeserver = &homeserver($cnum,$cdom);
                   6873:     }
                   6874:     if (!defined($homeserver)) { 
                   6875:         if ($cdom =~ /^$match_domain$/) {
                   6876:             $homeserver = &domain($cdom,'primary');
                   6877:         }
                   6878:     }
                   6879:     my @secs;
                   6880:     if (defined($homeserver)) {
                   6881:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6882:         unless ($response eq 'refused') {
                   6883:             @secs = split(/:/,$response);
                   6884:         }
1.506     raeburn  6885:     }
                   6886:     return @secs;
                   6887: }
1.776     albertel 6888: 
1.506     raeburn  6889: sub auto_new_course {
1.1099    raeburn  6890:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6891:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6892:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6893:     return $response;
                   6894: }
1.776     albertel 6895: 
1.506     raeburn  6896: sub auto_validate_courseID {
1.508     raeburn  6897:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6898:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6899:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6900:     return $response;
                   6901: }
1.776     albertel 6902: 
1.1007    raeburn  6903: sub auto_validate_instcode {
1.1020    raeburn  6904:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6905:     my ($homeserver,$response);
                   6906:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6907:         $homeserver = &homeserver($cnum,$cdom);
                   6908:     }
                   6909:     if (!defined($homeserver)) {
                   6910:         if ($cdom =~ /^$match_domain$/) {
                   6911:             $homeserver = &domain($cdom,'primary');
                   6912:         }
                   6913:     }
1.1065    raeburn  6914:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6915:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6916:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6917:     return ($outcome,$description);
1.1007    raeburn  6918: }
                   6919: 
1.506     raeburn  6920: sub auto_create_password {
1.873     raeburn  6921:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6922:     my ($homeserver,$response);
1.506     raeburn  6923:     my $create_passwd = 0;
                   6924:     my $authchk = '';
1.873     raeburn  6925:     if ($udom =~ /^$match_domain$/) {
                   6926:         $homeserver = &domain($udom,'primary');
                   6927:     }
                   6928:     if ($homeserver eq '') {
                   6929:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6930:             $homeserver = &homeserver($cnum,$cdom);
                   6931:         }
                   6932:     }
                   6933:     if ($homeserver eq '') {
                   6934:         $authchk = 'nodomain';
1.506     raeburn  6935:     } else {
1.873     raeburn  6936:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6937:         if ($response eq 'refused') {
                   6938:             $authchk = 'refused';
                   6939:         } else {
1.901     albertel 6940:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6941:         }
1.506     raeburn  6942:     }
                   6943:     return ($authparam,$create_passwd,$authchk);
                   6944: }
                   6945: 
1.706     raeburn  6946: sub auto_photo_permission {
                   6947:     my ($cnum,$cdom,$students) = @_;
                   6948:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6949:     my ($outcome,$perm_reqd,$conditions) = 
                   6950: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6951:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6952: 	return (undef,undef);
                   6953:     }
1.706     raeburn  6954:     return ($outcome,$perm_reqd,$conditions);
                   6955: }
                   6956: 
                   6957: sub auto_checkphotos {
                   6958:     my ($uname,$udom,$pid) = @_;
                   6959:     my $homeserver = &homeserver($uname,$udom);
                   6960:     my ($result,$resulttype);
                   6961:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6962: 				   &escape($uname).':'.&escape($pid),
                   6963: 				   $homeserver));
1.709     albertel 6964:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6965: 	return (undef,undef);
                   6966:     }
1.706     raeburn  6967:     if ($outcome) {
                   6968:         ($result,$resulttype) = split(/:/,$outcome);
                   6969:     } 
                   6970:     return ($result,$resulttype);
                   6971: }
                   6972: 
                   6973: sub auto_photochoice {
                   6974:     my ($cnum,$cdom) = @_;
                   6975:     my $homeserver = &homeserver($cnum,$cdom);
                   6976:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6977: 						       &escape($cdom),
                   6978: 						       $homeserver)));
1.709     albertel 6979:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6980: 	return (undef,undef);
                   6981:     }
1.706     raeburn  6982:     return ($update,$comment);
                   6983: }
                   6984: 
                   6985: sub auto_photoupdate {
                   6986:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6987:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6988:     my $host=&hostname($homeserver);
1.706     raeburn  6989:     my $cmd = '';
                   6990:     my $maxtries = 1;
1.800     albertel 6991:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6992:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6993:     }
                   6994:     $cmd =~ s/%%$//;
                   6995:     $cmd = &escape($cmd);
                   6996:     my $query = 'institutionalphotos';
                   6997:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6998:     unless ($queryid=~/^\Q$host\E\_/) {
                   6999:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7000:         return 'error: '.$queryid;
                   7001:     }
                   7002:     my $reply = &get_query_reply($queryid);
                   7003:     my $tries = 1;
                   7004:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7005:         $reply = &get_query_reply($queryid);
                   7006:         $tries ++;
                   7007:     }
                   7008:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7009:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7010:     } else {
                   7011:         my @responses = split(/:/,$reply);
                   7012:         my $outcome = shift(@responses); 
                   7013:         foreach my $item (@responses) {
                   7014:             my ($key,$value) = split(/=/,$item);
                   7015:             $$photo{$key} = $value;
                   7016:         }
                   7017:         return $outcome;
                   7018:     }
                   7019:     return 'error';
                   7020: }
                   7021: 
1.521     raeburn  7022: sub auto_instcode_format {
1.793     albertel 7023:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7024: 	$cat_order) = @_;
1.521     raeburn  7025:     my $courses = '';
1.772     raeburn  7026:     my @homeservers;
1.521     raeburn  7027:     if ($caller eq 'global') {
1.841     albertel 7028: 	my %servers = &get_servers($codedom,'library');
                   7029: 	foreach my $tryserver (keys(%servers)) {
                   7030: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7031: 		push(@homeservers,$tryserver);
                   7032: 	    }
1.584     raeburn  7033:         }
1.1022    raeburn  7034:     } elsif ($caller eq 'requests') {
                   7035:         if ($codedom =~ /^$match_domain$/) {
                   7036:             my $chome = &domain($codedom,'primary');
                   7037:             unless ($chome eq 'no_host') {
                   7038:                 push(@homeservers,$chome);
                   7039:             }
                   7040:         }
1.521     raeburn  7041:     } else {
1.772     raeburn  7042:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7043:     }
1.793     albertel 7044:     foreach my $code (keys(%{$instcodes})) {
                   7045:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7046:     }
                   7047:     chop($courses);
1.772     raeburn  7048:     my $ok_response = 0;
                   7049:     my $response;
                   7050:     while (@homeservers > 0 && $ok_response == 0) {
                   7051:         my $server = shift(@homeservers); 
                   7052:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7053:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7054:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7055: 		split(/:/,$response);
1.772     raeburn  7056:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7057:             push(@{$codetitles},&str2array($codetitles_str));
                   7058:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7059:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7060:             $ok_response = 1;
                   7061:         }
                   7062:     }
                   7063:     if ($ok_response) {
1.521     raeburn  7064:         return 'ok';
1.772     raeburn  7065:     } else {
                   7066:         return $response;
1.521     raeburn  7067:     }
                   7068: }
                   7069: 
1.792     raeburn  7070: sub auto_instcode_defaults {
                   7071:     my ($domain,$returnhash,$code_order) = @_;
                   7072:     my @homeservers;
1.841     albertel 7073: 
                   7074:     my %servers = &get_servers($domain,'library');
                   7075:     foreach my $tryserver (keys(%servers)) {
                   7076: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7077: 	    push(@homeservers,$tryserver);
                   7078: 	}
1.792     raeburn  7079:     }
1.841     albertel 7080: 
1.792     raeburn  7081:     my $response;
1.841     albertel 7082:     foreach my $server (@homeservers) {
1.792     raeburn  7083:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7084:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7085: 	
                   7086: 	foreach my $pair (split(/\&/,$response)) {
                   7087: 	    my ($name,$value)=split(/\=/,$pair);
                   7088: 	    if ($name eq 'code_order') {
                   7089: 		@{$code_order} = split(/\&/,&unescape($value));
                   7090: 	    } else {
                   7091: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7092: 	    }
                   7093: 	}
                   7094: 	return 'ok';
1.792     raeburn  7095:     }
1.841     albertel 7096: 
                   7097:     return $response;
1.1003    raeburn  7098: }
                   7099: 
                   7100: sub auto_possible_instcodes {
1.1007    raeburn  7101:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7102:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7103:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7104:         return;
                   7105:     }
1.1003    raeburn  7106:     my (@homeservers,$uhome);
                   7107:     if (defined(&domain($domain,'primary'))) {
                   7108:         $uhome=&domain($domain,'primary');
                   7109:         push(@homeservers,&domain($domain,'primary'));
                   7110:     } else {
                   7111:         my %servers = &get_servers($domain,'library');
                   7112:         foreach my $tryserver (keys(%servers)) {
                   7113:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7114:                 push(@homeservers,$tryserver);
                   7115:             }
                   7116:         }
                   7117:     }
                   7118:     my $response;
                   7119:     foreach my $server (@homeservers) {
                   7120:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7121:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7122:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7123:             split(':',$response);
                   7124:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7125:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7126:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7127:             my ($name,$value)=split('=',$item);
                   7128:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7129:         }
                   7130:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7131:             my ($name,$value)=split('=',$item);
                   7132:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7133:         }
                   7134:         return 'ok';
                   7135:     }
                   7136:     return $response;
                   7137: }
1.792     raeburn  7138: 
1.1010    raeburn  7139: sub auto_courserequest_checks {
                   7140:     my ($dom) = @_;
1.1020    raeburn  7141:     my ($homeserver,%validations);
                   7142:     if ($dom =~ /^$match_domain$/) {
                   7143:         $homeserver = &domain($dom,'primary');
                   7144:     }
                   7145:     unless ($homeserver eq 'no_host') {
                   7146:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7147:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7148:             my @items = split(/&/,$response);
                   7149:             foreach my $item (@items) {
                   7150:                 my ($key,$value) = split('=',$item);
                   7151:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7152:             }
                   7153:         }
                   7154:     }
1.1010    raeburn  7155:     return %validations; 
                   7156: }
                   7157: 
1.1020    raeburn  7158: sub auto_courserequest_validation {
                   7159:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7160:     my ($homeserver,$response);
                   7161:     if ($dom =~ /^$match_domain$/) {
                   7162:         $homeserver = &domain($dom,'primary');
                   7163:     }
                   7164:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7165:           
1.1020    raeburn  7166:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7167:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7168:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7169:                                     $homeserver));
                   7170:     }
                   7171:     return $response;
                   7172: }
                   7173: 
1.777     albertel 7174: sub auto_validate_class_sec {
1.918     raeburn  7175:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7176:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7177:     my $ownerlist;
                   7178:     if (ref($owners) eq 'ARRAY') {
                   7179:         $ownerlist = join(',',@{$owners});
                   7180:     } else {
                   7181:         $ownerlist = $owners;
                   7182:     }
1.773     raeburn  7183:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7184:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7185:     return $response;
                   7186: }
                   7187: 
1.679     raeburn  7188: # ------------------------------------------------------- Course Group routines
                   7189: 
                   7190: sub get_coursegroups {
1.809     raeburn  7191:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7192:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7193: }
                   7194: 
1.679     raeburn  7195: sub modify_coursegroup {
                   7196:     my ($cdom,$cnum,$groupsettings) = @_;
                   7197:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7198: }
                   7199: 
1.809     raeburn  7200: sub toggle_coursegroup_status {
                   7201:     my ($cdom,$cnum,$group,$action) = @_;
                   7202:     my ($from_namespace,$to_namespace);
                   7203:     if ($action eq 'delete') {
                   7204:         $from_namespace = 'coursegroups';
                   7205:         $to_namespace = 'deleted_groups';
                   7206:     } else {
                   7207:         $from_namespace = 'deleted_groups';
                   7208:         $to_namespace = 'coursegroups';
                   7209:     }
                   7210:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7211:     if (my $tmp = &error(%curr_group)) {
                   7212:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7213:         return ('read error',$tmp);
                   7214:     } else {
                   7215:         my %savedsettings = %curr_group; 
1.809     raeburn  7216:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7217:         my $deloutcome;
                   7218:         if ($result eq 'ok') {
1.809     raeburn  7219:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7220:         } else {
                   7221:             return ('write error',$result);
                   7222:         }
                   7223:         if ($deloutcome eq 'ok') {
                   7224:             return 'ok';
                   7225:         } else {
                   7226:             return ('delete error',$deloutcome);
                   7227:         }
                   7228:     }
                   7229: }
                   7230: 
1.679     raeburn  7231: sub modify_group_roles {
1.957     raeburn  7232:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7233:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7234:     my $role = 'gr/'.&escape($userprivs);
                   7235:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7236:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7237:     if ($result eq 'ok') {
                   7238:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7239:     }
1.679     raeburn  7240:     return $result;
                   7241: }
                   7242: 
                   7243: sub modify_coursegroup_membership {
                   7244:     my ($cdom,$cnum,$membership) = @_;
                   7245:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7246:     return $result;
                   7247: }
                   7248: 
1.682     raeburn  7249: sub get_active_groups {
                   7250:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7251:     my $now = time;
                   7252:     my %groups = ();
                   7253:     foreach my $key (keys(%env)) {
1.811     albertel 7254:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7255:             my ($start,$end) = split(/\./,$env{$key});
                   7256:             if (($end!=0) && ($end<$now)) { next; }
                   7257:             if (($start!=0) && ($start>$now)) { next; }
                   7258:             if ($1 eq $cdom && $2 eq $cnum) {
                   7259:                 $groups{$3} = $env{$key} ;
                   7260:             }
                   7261:         }
                   7262:     }
                   7263:     return %groups;
                   7264: }
                   7265: 
1.683     raeburn  7266: sub get_group_membership {
                   7267:     my ($cdom,$cnum,$group) = @_;
                   7268:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7269: }
                   7270: 
                   7271: sub get_users_groups {
                   7272:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7273:     my @usersgroups;
1.683     raeburn  7274:     my $cachetime=1800;
                   7275: 
                   7276:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7277:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7278:     if (defined($cached)) {
1.734     albertel 7279:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7280:     } else {  
                   7281:         $grouplist = '';
1.816     raeburn  7282:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7283:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7284:         my $access_end = $env{'course.'.$courseid.
                   7285:                               '.default_enrollment_end_date'};
                   7286:         my $now = time;
                   7287:         foreach my $key (keys(%roleshash)) {
                   7288:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7289:                 my $group = $1;
                   7290:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7291:                     my $start = $2;
                   7292:                     my $end = $1;
                   7293:                     if ($start == -1) { next; } # deleted from group
                   7294:                     if (($start!=0) && ($start>$now)) { next; }
                   7295:                     if (($end!=0) && ($end<$now)) {
                   7296:                         if ($access_end && $access_end < $now) {
                   7297:                             if ($access_end - $end < 86400) {
                   7298:                                 push(@usersgroups,$group);
1.733     raeburn  7299:                             }
                   7300:                         }
1.817     raeburn  7301:                         next;
1.733     raeburn  7302:                     }
1.817     raeburn  7303:                     push(@usersgroups,$group);
1.683     raeburn  7304:                 }
                   7305:             }
                   7306:         }
1.817     raeburn  7307:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7308:         $grouplist = join(':',@usersgroups);
                   7309:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7310:     }
1.733     raeburn  7311:     return @usersgroups;
1.683     raeburn  7312: }
                   7313: 
                   7314: sub devalidate_getgroups_cache {
                   7315:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7316:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7317: 
1.683     raeburn  7318:     my $hashid="$udom:$uname:$courseid";
                   7319:     &devalidate_cache_new('getgroups',$hashid);
                   7320: }
                   7321: 
1.12      www      7322: # ------------------------------------------------------------------ Plain Text
                   7323: 
                   7324: sub plaintext {
1.988     raeburn  7325:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7326:     if ($short =~ m{^cr/}) {
1.758     albertel 7327: 	return (split('/',$short))[-1];
                   7328:     }
1.742     raeburn  7329:     if (!defined($cid)) {
                   7330:         $cid = $env{'request.course.id'};
                   7331:     }
                   7332:     my %rolenames = (
1.1008    raeburn  7333:                       Course    => 'std',
                   7334:                       Community => 'alt1',
1.742     raeburn  7335:                     );
1.1037    raeburn  7336:     if ($cid ne '') {
                   7337:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7338:             unless ($forcedefault) {
                   7339:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7340:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7341:                 return &Apache::lonlocal::mt($roletext);
                   7342:             }
                   7343:         }
                   7344:     }
                   7345:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7346:         (defined($rolenames{$type})) && 
                   7347:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7348:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7349:     } elsif ($cid ne '') {
                   7350:         my $crstype = $env{'course.'.$cid.'.type'};
                   7351:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7352:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7353:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7354:         }
1.742     raeburn  7355:     }
1.1037    raeburn  7356:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7357: }
                   7358: 
                   7359: # ----------------------------------------------------------------- Assign Role
                   7360: 
                   7361: sub assignrole {
1.957     raeburn  7362:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7363:         $context)=@_;
1.21      www      7364:     my $mrole;
                   7365:     if ($role =~ /^cr\//) {
1.393     www      7366:         my $cwosec=$url;
1.811     albertel 7367:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7368: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7369:            my $refused = 1;
                   7370:            if ($context eq 'requestcourses') {
                   7371:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7372:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7373:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7374:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7375:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7376:                            if ($crsenv{'internal.courseowner'} eq
                   7377:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7378:                                $refused = '';
                   7379:                            }
                   7380:                        }
                   7381:                    }
                   7382:                }
                   7383:            }
                   7384:            if ($refused) {
                   7385:                &logthis('Refused custom assignrole: '.
                   7386:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7387:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7388:                return 'refused';
                   7389:            }
1.104     www      7390:         }
1.21      www      7391:         $mrole='cr';
1.678     raeburn  7392:     } elsif ($role =~ /^gr\//) {
                   7393:         my $cwogrp=$url;
1.811     albertel 7394:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7395:         unless (&allowed('mdg',$cwogrp)) {
                   7396:             &logthis('Refused group assignrole: '.
                   7397:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7398:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7399:             return 'refused';
                   7400:         }
                   7401:         $mrole='gr';
1.21      www      7402:     } else {
1.82      www      7403:         my $cwosec=$url;
1.811     albertel 7404:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7405:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7406:             my $refused;
                   7407:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7408:                 if (!(&allowed('c'.$role,$url))) {
                   7409:                     $refused = 1;
                   7410:                 }
                   7411:             } else {
                   7412:                 $refused = 1;
                   7413:             }
1.947     raeburn  7414:             if ($refused) {
1.1045    raeburn  7415:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7416:                 if (!$selfenroll && $context eq 'course') {
                   7417:                     my %crsenv;
                   7418:                     if ($role eq 'cc' || $role eq 'co') {
                   7419:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7420:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7421:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7422:                                 if ($crsenv{'internal.courseowner'} eq 
                   7423:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7424:                                     $refused = '';
                   7425:                                 }
                   7426:                             }
                   7427:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7428:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7429:                                 if ($crsenv{'internal.courseowner'} eq 
                   7430:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7431:                                     $refused = '';
                   7432:                                 }
                   7433:                             }
                   7434:                         }
                   7435:                     }
                   7436:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7437:                     $refused = '';
1.1017    raeburn  7438:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7439:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7440:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7441:                         my $wrongcc;
                   7442:                         if ($cnum =~ /^$match_community$/) {
                   7443:                             $wrongcc = 1 if ($role eq 'cc');
                   7444:                         } else {
                   7445:                             $wrongcc = 1 if ($role eq 'co');
                   7446:                         }
                   7447:                         unless ($wrongcc) {
                   7448:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7449:                             if ($crsenv{'internal.courseowner'} eq 
                   7450:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7451:                                 $refused = '';
                   7452:                             }
1.1017    raeburn  7453:                         }
                   7454:                     }
                   7455:                 }
                   7456:                 if ($refused) {
1.947     raeburn  7457:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7458:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7459: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7460:                     return 'refused';
                   7461:                 }
1.932     raeburn  7462:             }
1.1131    raeburn  7463:         } elsif ($role eq 'au') {
                   7464:             if ($url ne '/'.$udom.'/') {
                   7465:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7466:                          ' to assign author role for '.$uname.':'.$udom.
                   7467:                          ' in domain: '.$url.' refused (wrong domain).');
                   7468:                 return 'refused';
                   7469:             }
1.104     www      7470:         }
1.21      www      7471:         $mrole=$role;
                   7472:     }
1.620     albertel 7473:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7474:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7475:     if ($end) { $command.='_'.$end; }
1.21      www      7476:     if ($start) {
                   7477: 	if ($end) { 
1.81      www      7478:            $command.='_'.$start; 
1.21      www      7479:         } else {
1.81      www      7480:            $command.='_0_'.$start;
1.21      www      7481:         }
                   7482:     }
1.739     raeburn  7483:     my $origstart = $start;
                   7484:     my $origend = $end;
1.957     raeburn  7485:     my $delflag;
1.357     www      7486: # actually delete
                   7487:     if ($deleteflag) {
1.373     www      7488: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7489: # modify command to delete the role
1.620     albertel 7490:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7491:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7492: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7493: # set start and finish to negative values for userrolelog
                   7494:            $start=-1;
                   7495:            $end=-1;
1.957     raeburn  7496:            $delflag = 1;
1.357     www      7497:         }
                   7498:     }
                   7499: # send command
1.349     www      7500:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7501: # log new user role if status is ok
1.349     www      7502:     if ($answer eq 'ok') {
1.663     raeburn  7503: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7504: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7505:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7506:         unless ($role =~ /^gr/) {
                   7507:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7508:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7509:         }
1.1053    raeburn  7510:         if ($role eq 'cc') {
                   7511:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7512:         }
1.349     www      7513:     }
                   7514:     return $answer;
1.169     harris41 7515: }
                   7516: 
1.1053    raeburn  7517: sub autoupdate_coowners {
                   7518:     my ($url,$end,$start,$uname,$udom) = @_;
                   7519:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7520:     if (($cdom ne '') && ($cnum ne '')) {
                   7521:         my $now = time;
                   7522:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7523:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7524:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7525:             my $instcode = $coursehash{'internal.coursecode'};
                   7526:             if ($instcode ne '') {
1.1056    raeburn  7527:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7528:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7529:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7530:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7531:                         if ($result eq 'valid') {
                   7532:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7533:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7534:                                     push(@newcoowners,$coowner);
                   7535:                                 }
                   7536:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7537:                                     push(@newcoowners,$uname.':'.$udom);
                   7538:                                 }
                   7539:                                 @newcoowners = sort(@newcoowners);
                   7540:                             } else {
                   7541:                                 push(@newcoowners,$uname.':'.$udom);
                   7542:                             }
                   7543:                         } else {
                   7544:                             if ($coursehash{'internal.co-owners'}) {
                   7545:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7546:                                     unless ($coowner eq $uname.':'.$udom) {
                   7547:                                         push(@newcoowners,$coowner);
                   7548:                                     }
                   7549:                                 }
                   7550:                                 unless (@newcoowners > 0) {
                   7551:                                     $delcoowners = 1;
                   7552:                                     $coowners = '';
                   7553:                                 }
                   7554:                             }
                   7555:                         }
                   7556:                         if (@newcoowners || $delcoowners) {
                   7557:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7558:                                             $delcoowners,@newcoowners);
                   7559:                         }
                   7560:                     }
                   7561:                 }
                   7562:             }
                   7563:         }
                   7564:     }
                   7565: }
                   7566: 
                   7567: sub store_coowners {
                   7568:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7569:     my $cid = $cdom.'_'.$cnum;
                   7570:     my ($coowners,$delresult,$putresult);
                   7571:     if (@newcoowners) {
                   7572:         $coowners = join(',',@newcoowners);
                   7573:         my %coownershash = (
                   7574:                             'internal.co-owners' => $coowners,
                   7575:                            );
                   7576:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7577:         if ($putresult eq 'ok') {
                   7578:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7579:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7580:             }
                   7581:         }
                   7582:     }
                   7583:     if ($delcoowners) {
                   7584:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7585:         if ($delresult eq 'ok') {
                   7586:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7587:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7588:             }
                   7589:         }
                   7590:     }
                   7591:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7592:         my %crsinfo =
                   7593:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7594:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7595:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7596:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7597:         }
                   7598:     }
                   7599: }
                   7600: 
1.169     harris41 7601: # -------------------------------------------------- Modify user authentication
1.197     www      7602: # Overrides without validation
                   7603: 
1.169     harris41 7604: sub modifyuserauth {
                   7605:     my ($udom,$uname,$umode,$upass)=@_;
                   7606:     my $uhome=&homeserver($uname,$udom);
1.197     www      7607:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7608:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7609:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7610:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7611:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7612: 		     &escape($upass),$uhome);
1.620     albertel 7613:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7614:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7615:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7616:     &log($udom,,$uname,$uhome,
1.620     albertel 7617:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7618:                                      $env{'user.name'}.', '.$umode.
1.197     www      7619:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7620:     unless ($reply eq 'ok') {
1.197     www      7621:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7622: 	return 'error: '.$reply;
                   7623:     }   
1.170     harris41 7624:     return 'ok';
1.80      www      7625: }
                   7626: 
1.81      www      7627: # --------------------------------------------------------------- Modify a user
1.80      www      7628: 
1.81      www      7629: sub modifyuser {
1.206     matthew  7630:     my ($udom,    $uname, $uid,
                   7631:         $umode,   $upass, $first,
                   7632:         $middle,  $last,  $gene,
1.1058    raeburn  7633:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7634:     $udom= &LONCAPA::clean_domain($udom);
                   7635:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7636:     my $showcandelete = 'none';
                   7637:     if (ref($candelete) eq 'ARRAY') {
                   7638:         if (@{$candelete} > 0) {
                   7639:             $showcandelete = join(', ',@{$candelete});
                   7640:         }
                   7641:     }
1.81      www      7642:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7643:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7644: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7645:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7646:                                      ' desiredhome not specified'). 
1.620     albertel 7647:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7648:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7649:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7650:     my $newuser;
                   7651:     if ($uhome eq 'no_host') {
                   7652:         $newuser = 1;
                   7653:     }
1.80      www      7654: # ----------------------------------------------------------------- Create User
1.406     albertel 7655:     if (($uhome eq 'no_host') && 
                   7656: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7657:         my $unhome='';
1.844     albertel 7658:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7659:             $unhome = $desiredhome;
1.620     albertel 7660: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7661: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7662:         } else { # load balancing routine for determining $unhome
1.81      www      7663:             my $loadm=10000000;
1.841     albertel 7664: 	    my %servers = &get_servers($udom,'library');
                   7665: 	    foreach my $tryserver (keys(%servers)) {
                   7666: 		my $answer=reply('load',$tryserver);
                   7667: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7668: 		    $loadm=$answer;
                   7669: 		    $unhome=$tryserver;
                   7670: 		}
1.80      www      7671: 	    }
                   7672:         }
                   7673:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7674: 	    return 'error: unable to find a home server for '.$uname.
                   7675:                    ' in domain '.$udom;
1.80      www      7676:         }
                   7677:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7678:                          &escape($upass),$unhome);
                   7679: 	unless ($reply eq 'ok') {
                   7680:             return 'error: '.$reply;
                   7681:         }   
1.230     stredwic 7682:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7683:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7684: 	    return 'error: unable verify users home machine.';
1.80      www      7685:         }
1.209     matthew  7686:     }   # End of creation of new user
1.80      www      7687: # ---------------------------------------------------------------------- Add ID
                   7688:     if ($uid) {
                   7689:        $uid=~tr/A-Z/a-z/;
                   7690:        my %uidhash=&idrget($udom,$uname);
1.196     www      7691:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7692:          && (!$forceid)) {
1.80      www      7693: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7694: 	      return 'error: user id "'.$uid.'" does not match '.
                   7695:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7696:           }
                   7697:        } else {
                   7698: 	  &idput($udom,($uname => $uid));
                   7699:        }
                   7700:     }
                   7701: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7702:     my @tmp=&get('environment',
1.899     raeburn  7703: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7704:                     'permanentemail','inststatus'],
1.134     albertel 7705: 		   $udom,$uname);
1.1075    raeburn  7706:     my (%names,%oldnames);
1.313     matthew  7707:     if ($tmp[0] =~ m/^error:.*/) { 
                   7708:         %names=(); 
                   7709:     } else {
                   7710:         %names = @tmp;
1.1075    raeburn  7711:         %oldnames = %names;
1.313     matthew  7712:     }
1.388     www      7713: #
1.1058    raeburn  7714: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7715: # of users did not contain them), do not overwrite existing values
                   7716: # unless field is in $candelete array ref.  
                   7717: #
                   7718: 
                   7719:     my @fields = ('firstname','middlename','lastname','generation',
                   7720:                   'permanentemail','id');
                   7721:     my %newvalues;
                   7722:     if (ref($candelete) eq 'ARRAY') {
                   7723:         foreach my $field (@fields) {
                   7724:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7725:                 if ($field eq 'firstname') {
                   7726:                     $names{$field} = $first;
                   7727:                 } elsif ($field eq 'middlename') {
                   7728:                     $names{$field} = $middle;
                   7729:                 } elsif ($field eq 'lastname') {
                   7730:                     $names{$field} = $last;
                   7731:                 } elsif ($field eq 'generation') { 
                   7732:                     $names{$field} = $gene;
                   7733:                 } elsif ($field eq 'permanentemail') {
                   7734:                     $names{$field} = $email;
                   7735:                 } elsif ($field eq 'id') {
                   7736:                     $names{$field}  = $uid;
                   7737:                 }
                   7738:             }
                   7739:         }
                   7740:     }
1.388     www      7741:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7742:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7743:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7744:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7745:     if ($email) {
                   7746:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7747:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7748:     }
1.899     raeburn  7749:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7750:     if (defined($inststatus)) {
                   7751:         $names{'inststatus'} = '';
                   7752:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7753:         if (ref($usertypes) eq 'HASH') {
                   7754:             my @okstatuses; 
                   7755:             foreach my $item (split(/:/,$inststatus)) {
                   7756:                 if (defined($usertypes->{$item})) {
                   7757:                     push(@okstatuses,$item);  
                   7758:                 }
                   7759:             }
                   7760:             if (@okstatuses) {
                   7761:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7762:             }
                   7763:         }
                   7764:     }
1.1075    raeburn  7765:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7766:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7767:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7768:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7769:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7770:     } else {
                   7771:         $logmsg .= ' during self creation';
                   7772:     }
1.1075    raeburn  7773:     my $changed;
                   7774:     if ($newuser) {
                   7775:         $changed = 1;
                   7776:     } else {
                   7777:         foreach my $field (@fields) {
                   7778:             if ($names{$field} ne $oldnames{$field}) {
                   7779:                 $changed = 1;
                   7780:                 last;
                   7781:             }
                   7782:         }
                   7783:     }
                   7784:     unless ($changed) {
                   7785:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7786:         &logthis($logmsg);
                   7787:         return 'ok';
                   7788:     }
                   7789:     my $reply = &put('environment', \%names, $udom,$uname);
                   7790:     if ($reply ne 'ok') { 
                   7791:         return 'error: '.$reply;
                   7792:     }
1.1087    raeburn  7793:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7794:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7795:     }
1.1075    raeburn  7796:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7797:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7798:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7799:     &logthis($logmsg);
1.134     albertel 7800:     return 'ok';
1.80      www      7801: }
                   7802: 
1.81      www      7803: # -------------------------------------------------------------- Modify student
1.80      www      7804: 
1.81      www      7805: sub modifystudent {
                   7806:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7807:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7808:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7809:     if (!$cid) {
1.620     albertel 7810: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7811: 	    return 'not_in_class';
                   7812: 	}
1.80      www      7813:     }
                   7814: # --------------------------------------------------------------- Make the user
1.81      www      7815:     my $reply=&modifyuser
1.209     matthew  7816: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7817:          $desiredhome,$email,$inststatus);
1.80      www      7818:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7819:     # This will cause &modify_student_enrollment to get the uid from the
                   7820:     # students environment
                   7821:     $uid = undef if (!$forceid);
1.455     albertel 7822:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7823: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7824:     return $reply;
                   7825: }
                   7826: 
                   7827: sub modify_student_enrollment {
1.957     raeburn  7828:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7829:     my ($cdom,$cnum,$chome);
                   7830:     if (!$cid) {
1.620     albertel 7831: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7832: 	    return 'not_in_class';
                   7833: 	}
1.620     albertel 7834: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7835: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7836:     } else {
                   7837: 	($cdom,$cnum)=split(/_/,$cid);
                   7838:     }
1.620     albertel 7839:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7840:     if (!$chome) {
1.457     raeburn  7841: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7842:     }
1.455     albertel 7843:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7844:     # Make sure the user exists
1.81      www      7845:     my $uhome=&homeserver($uname,$udom);
                   7846:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7847: 	return 'error: no such user';
                   7848:     }
1.297     matthew  7849:     # Get student data if we were not given enough information
                   7850:     if (!defined($first)  || $first  eq '' || 
                   7851:         !defined($last)   || $last   eq '' || 
                   7852:         !defined($uid)    || $uid    eq '' || 
                   7853:         !defined($middle) || $middle eq '' || 
                   7854:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7855:         # They did not supply us with enough data to enroll the student, so
                   7856:         # we need to pick up more information.
1.297     matthew  7857:         my %tmp = &get('environment',
1.294     matthew  7858:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7859:                        ,$udom,$uname);
                   7860: 
1.800     albertel 7861:         #foreach my $key (keys(%tmp)) {
                   7862:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7863:         #}
1.294     matthew  7864:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7865:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7866:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7867:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7868:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7869:     }
1.556     albertel 7870:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7871:     my $user = "$uname:$udom";
                   7872:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7873:     my $reply=cput('classlist',
1.1148    raeburn  7874: 		   {$user => 
1.515     raeburn  7875: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7876: 		   $cdom,$cnum);
1.1148    raeburn  7877:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7878:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7879:     } else { 
1.81      www      7880: 	return 'error: '.$reply;
                   7881:     }
1.297     matthew  7882:     # Add student role to user
1.83      www      7883:     my $uurl='/'.$cid;
1.81      www      7884:     $uurl=~s/\_/\//g;
                   7885:     if ($usec) {
                   7886: 	$uurl.='/'.$usec;
                   7887:     }
1.1148    raeburn  7888:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7889:                              $selfenroll,$context);
                   7890:     if ($result ne 'ok') {
                   7891:         if ($old_entry{$user} ne '') {
                   7892:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7893:         } else {
                   7894:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7895:         }
                   7896:     }
                   7897:     return $result; 
1.21      www      7898: }
                   7899: 
1.556     albertel 7900: sub format_name {
                   7901:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7902:     my $name;
                   7903:     if ($first ne 'lastname') {
                   7904: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7905:     } else {
                   7906: 	if ($lastname=~/\S/) {
                   7907: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7908: 	    $name=~s/\s+,/,/;
                   7909: 	} else {
                   7910: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7911: 	}
                   7912:     }
                   7913:     $name=~s/^\s+//;
                   7914:     $name=~s/\s+$//;
                   7915:     $name=~s/\s+/ /g;
                   7916:     return $name;
                   7917: }
                   7918: 
1.84      www      7919: # ------------------------------------------------- Write to course preferences
                   7920: 
                   7921: sub writecoursepref {
                   7922:     my ($courseid,%prefs)=@_;
                   7923:     $courseid=~s/^\///;
                   7924:     $courseid=~s/\_/\//g;
                   7925:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7926:     my $chome=homeserver($cnum,$cdomain);
                   7927:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7928: 	return 'error: no such course';
                   7929:     }
                   7930:     my $cstring='';
1.800     albertel 7931:     foreach my $pref (keys(%prefs)) {
                   7932: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7933:     }
1.84      www      7934:     $cstring=~s/\&$//;
                   7935:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7936: }
                   7937: 
                   7938: # ---------------------------------------------------------- Make/modify course
                   7939: 
                   7940: sub createcourse {
1.741     raeburn  7941:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7942:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7943:     $url=&declutter($url);
                   7944:     my $cid='';
1.1028    raeburn  7945:     if ($context eq 'requestcourses') {
                   7946:         my $can_create = 0;
                   7947:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7948:         if ($udom eq $ownerdom) {
                   7949:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7950:                                   $context)) {
                   7951:                 $can_create = 1;
                   7952:             }
                   7953:         } else {
                   7954:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7955:                                            $category);
                   7956:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7957:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7958:                 if (@curr > 0) {
                   7959:                     my @options = qw(approval validate autolimit);
                   7960:                     my $optregex = join('|',@options);
                   7961:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7962:                         $can_create = 1;
                   7963:                     }
                   7964:                 }
                   7965:             }
                   7966:         }
                   7967:         if ($can_create) {
                   7968:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7969:                 unless (&allowed('ccc',$udom)) {
                   7970:                     return 'refused'; 
                   7971:                 }
1.1017    raeburn  7972:             }
                   7973:         } else {
                   7974:             return 'refused';
                   7975:         }
1.1028    raeburn  7976:     } elsif (!&allowed('ccc',$udom)) {
                   7977:         return 'refused';
1.84      www      7978:     }
1.1011    raeburn  7979: # --------------------------------------------------------------- Get Unique ID
                   7980:     my $uname;
                   7981:     if ($cnum =~ /^$match_courseid$/) {
                   7982:         my $chome=&homeserver($cnum,$udom,'true');
                   7983:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7984:             $uname = $cnum;
                   7985:         } else {
1.1038    raeburn  7986:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7987:         }
                   7988:     } else {
1.1038    raeburn  7989:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7990:     }
                   7991:     return $uname if ($uname =~ /^error/);
                   7992: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7993:     if (!defined($course_server)) {
                   7994:         if (defined(&domain($udom,'primary'))) {
                   7995:             $course_server = &domain($udom,'primary');
                   7996:         } else {
                   7997:             $course_server = $env{'user.home'}; 
                   7998:         }
                   7999:     }
                   8000:     my %host_servers =
                   8001:         &Apache::lonnet::get_servers($udom,'library');
                   8002:     unless ($host_servers{$course_server}) {
                   8003:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8004:     }
1.84      www      8005: # ------------------------------------------------------------- Make the course
                   8006:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8007:                       $course_server);
1.84      www      8008:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8009:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8010:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8011: 	return 'error: no such course';
                   8012:     }
1.271     www      8013: # ----------------------------------------------------------------- Course made
1.516     raeburn  8014: # log existence
1.1029    raeburn  8015:     my $now = time;
1.918     raeburn  8016:     my $newcourse = {
                   8017:                     $udom.'_'.$uname => {
1.921     raeburn  8018:                                      description => $description,
                   8019:                                      inst_code   => $inst_code,
                   8020:                                      owner       => $course_owner,
                   8021:                                      type        => $crstype,
1.1029    raeburn  8022:                                      creator     => $env{'user.name'}.':'.
                   8023:                                                     $env{'user.domain'},
                   8024:                                      created     => $now,
                   8025:                                      context     => $context,
1.918     raeburn  8026:                                                 },
                   8027:                     };
1.921     raeburn  8028:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8029: # set toplevel url
1.271     www      8030:     my $topurl=$url;
                   8031:     unless ($nonstandard) {
                   8032: # ------------------------------------------ For standard courses, make top url
                   8033:         my $mapurl=&clutter($url);
1.278     www      8034:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8035:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8036: <map>
                   8037: <resource id="1" type="start"></resource>
                   8038: <resource id="2" src="$mapurl"></resource>
                   8039: <resource id="3" type="finish"></resource>
                   8040: <link index="1" from="1" to="2"></link>
                   8041: <link index="2" from="2" to="3"></link>
                   8042: </map>
                   8043: ENDINITMAP
                   8044:         $topurl=&declutter(
1.638     albertel 8045:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8046:                           );
                   8047:     }
                   8048: # ----------------------------------------------------------- Write preferences
1.84      www      8049:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8050:                      ('description'              => $description,
                   8051:                       'url'                      => $topurl,
                   8052:                       'internal.creator'         => $env{'user.name'}.':'.
                   8053:                                                     $env{'user.domain'},
                   8054:                       'internal.created'         => $now,
                   8055:                       'internal.creationcontext' => $context)
                   8056:                     );
1.84      www      8057:     return '/'.$udom.'/'.$uname;
                   8058: }
                   8059: 
1.1011    raeburn  8060: # ------------------------------------------------------------------- Create ID
                   8061: sub generate_coursenum {
1.1038    raeburn  8062:     my ($udom,$crstype) = @_;
1.1011    raeburn  8063:     my $domdesc = &domain($udom);
                   8064:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8065:     my $first;
                   8066:     if ($crstype eq 'Community') {
                   8067:         $first = '0';
                   8068:     } else {
                   8069:         $first = int(1+rand(9)); 
                   8070:     } 
                   8071:     my $uname=$first.
1.1011    raeburn  8072:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8073:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8074:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8075: # ----------------------------------------------- Make sure that does not exist
                   8076:     my $uhome=&homeserver($uname,$udom,'true');
                   8077:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8078:         if ($crstype eq 'Community') {
                   8079:             $first = '0';
                   8080:         } else {
                   8081:             $first = int(1+rand(9));
                   8082:         }
                   8083:         $uname=$first.
1.1011    raeburn  8084:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8085:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8086:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8087:         $uhome=&homeserver($uname,$udom,'true');
                   8088:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8089:             return 'error: unable to generate unique course-ID';
                   8090:         }
                   8091:     }
                   8092:     return $uname;
                   8093: }
                   8094: 
1.813     albertel 8095: sub is_course {
1.1167    droeschl 8096:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8097:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8098: 
                   8099:     return unless $cdom and $cnum;
                   8100: 
                   8101:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8102:         '.');
                   8103: 
                   8104:     return unless exists($courses{$cdom.'_'.$cnum});
                   8105:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8106: }
                   8107: 
1.1015    raeburn  8108: sub store_userdata {
                   8109:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8110:     my $result;
1.1016    raeburn  8111:     if ($datakey ne '') {
1.1013    raeburn  8112:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8113:             if ($udom eq '' || $uname eq '') {
                   8114:                 $udom = $env{'user.domain'};
                   8115:                 $uname = $env{'user.name'};
                   8116:             }
                   8117:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8118:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8119:                 $result = 'error: no_host';
                   8120:             } else {
                   8121:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8122:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8123: 
                   8124:                 my $namevalue='';
                   8125:                 foreach my $key (keys(%{$storehash})) {
                   8126:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8127:                 }
                   8128:                 $namevalue=~s/\&$//;
1.1105    raeburn  8129:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8130:                                   $namevalue,$uhome);
1.1013    raeburn  8131:             }
                   8132:         } else {
                   8133:             $result = 'error: data to store was not a hash reference'; 
                   8134:         }
                   8135:     } else {
                   8136:         $result= 'error: invalid requestkey'; 
                   8137:     }
                   8138:     return $result;
                   8139: }
                   8140: 
1.21      www      8141: # ---------------------------------------------------------- Assign Custom Role
                   8142: 
                   8143: sub assigncustomrole {
1.957     raeburn  8144:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8145:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8146:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8147: }
                   8148: 
                   8149: # ----------------------------------------------------------------- Revoke Role
                   8150: 
                   8151: sub revokerole {
1.957     raeburn  8152:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8153:     my $now=time;
1.965     raeburn  8154:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8155: }
                   8156: 
                   8157: # ---------------------------------------------------------- Revoke Custom Role
                   8158: 
                   8159: sub revokecustomrole {
1.957     raeburn  8160:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8161:     my $now=time;
1.357     www      8162:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8163:            $deleteflag,$selfenroll,$context);
1.17      www      8164: }
                   8165: 
1.533     banghart 8166: # ------------------------------------------------------------ Disk usage
1.535     albertel 8167: sub diskusage {
1.955     raeburn  8168:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8169:     $directorypath =~ s/\/$//;
                   8170:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8171:                        .&escape($getpropath).':'.&escape($uname).':'
                   8172:                        .&escape($udom),homeserver($uname,$udom));
                   8173:     if ($listing eq 'unknown_cmd') {
                   8174:         if ($getpropath) {
                   8175:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8176:         }
                   8177:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8178:     }
1.514     albertel 8179:     return $listing;
1.512     banghart 8180: }
                   8181: 
1.566     banghart 8182: sub is_locked {
1.1096    raeburn  8183:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8184:     my @check;
                   8185:     my $is_locked;
1.1093    raeburn  8186:     push (@check,$file_name);
1.613     albertel 8187:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8188: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8189:     my ($tmp)=keys(%locked);
                   8190:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8191:     
1.566     banghart 8192:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8193:         $is_locked = 'false';
                   8194:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8195:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8196:                $is_locked = 'true';
1.1096    raeburn  8197:                if (ref($which) eq 'ARRAY') {
                   8198:                    push(@{$which},$entry);
                   8199:                } else {
                   8200:                    last;
                   8201:                }
1.745     raeburn  8202:            }
                   8203:        }
1.566     banghart 8204:     } else {
                   8205:         $is_locked = 'false';
                   8206:     }
1.1093    raeburn  8207:     return $is_locked;
1.566     banghart 8208: }
                   8209: 
1.759     albertel 8210: sub declutter_portfile {
                   8211:     my ($file) = @_;
1.833     albertel 8212:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8213:     return $file;
                   8214: }
                   8215: 
1.559     banghart 8216: # ------------------------------------------------------------- Mark as Read Only
                   8217: 
                   8218: sub mark_as_readonly {
                   8219:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8220:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8221:     my ($tmp)=keys(%current_permissions);
                   8222:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8223:     foreach my $file (@{$files}) {
1.759     albertel 8224: 	$file = &declutter_portfile($file);
1.561     banghart 8225:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8226:     }
1.613     albertel 8227:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8228:     return;
                   8229: }
                   8230: 
1.572     banghart 8231: # ------------------------------------------------------------Save Selected Files
                   8232: 
                   8233: sub save_selected_files {
                   8234:     my ($user, $path, @files) = @_;
                   8235:     my $filename = $user."savedfiles";
1.573     banghart 8236:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8237:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8238:     foreach my $file (@files) {
1.620     albertel 8239:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8240:     }
                   8241:     foreach my $file (@other_files) {
1.574     banghart 8242:         print (OUT $file."\n");
1.572     banghart 8243:     }
1.574     banghart 8244:     close (OUT);
1.572     banghart 8245:     return 'ok';
                   8246: }
                   8247: 
1.574     banghart 8248: sub clear_selected_files {
                   8249:     my ($user) = @_;
                   8250:     my $filename = $user."savedfiles";
1.1117    foxr     8251:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8252:     print (OUT undef);
                   8253:     close (OUT);
                   8254:     return ("ok");    
                   8255: }
                   8256: 
1.572     banghart 8257: sub files_in_path {
                   8258:     my ($user, $path) = @_;
                   8259:     my $filename = $user."savedfiles";
                   8260:     my %return_files;
1.1117    foxr     8261:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8262:     while (my $line_in = <IN>) {
1.574     banghart 8263:         chomp ($line_in);
                   8264:         my @paths_and_file = split (m!/!, $line_in);
                   8265:         my $file_part = pop (@paths_and_file);
                   8266:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8267:         $path_part.='/';
                   8268:         my $path_and_file = $path_part.$file_part;
                   8269:         if ($path_part eq $path) {
                   8270:             $return_files{$file_part}= 'selected';
                   8271:         }
                   8272:     }
1.574     banghart 8273:     close (IN);
                   8274:     return (\%return_files);
1.572     banghart 8275: }
                   8276: 
                   8277: # called in portfolio select mode, to show files selected NOT in current directory
                   8278: sub files_not_in_path {
                   8279:     my ($user, $path) = @_;
                   8280:     my $filename = $user."savedfiles";
                   8281:     my @return_files;
                   8282:     my $path_part;
1.1117    foxr     8283:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8284:     while (my $line = <IN>) {
1.572     banghart 8285:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8286:         my @paths_and_file = split(m|/|, $line);
                   8287:         my $file_part = pop(@paths_and_file);
                   8288:         chomp($file_part);
                   8289:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8290:         $path_part .= '/';
                   8291:         my $path_and_file = $path_part.$file_part;
                   8292:         if ($path_part ne $path) {
1.800     albertel 8293:             push(@return_files, ($path_and_file));
1.572     banghart 8294:         }
                   8295:     }
1.800     albertel 8296:     close(OUT);
1.574     banghart 8297:     return (@return_files);
1.572     banghart 8298: }
                   8299: 
1.745     raeburn  8300: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8301: 
1.745     raeburn  8302: sub get_portfile_permissions {
                   8303:     my ($domain,$user) = @_;
1.613     albertel 8304:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8305:     my ($tmp)=keys(%current_permissions);
                   8306:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8307:     return \%current_permissions;
                   8308: }
                   8309: 
                   8310: #---------------------------------------------Get portfolio file access controls
                   8311: 
1.749     raeburn  8312: sub get_access_controls {
1.745     raeburn  8313:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8314:     my %access;
                   8315:     my $real_file = $file;
                   8316:     $file =~ s/\.meta$//;
1.745     raeburn  8317:     if (defined($file)) {
1.749     raeburn  8318:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8319:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8320:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8321:             }
                   8322:         }
1.745     raeburn  8323:     } else {
1.749     raeburn  8324:         foreach my $key (keys(%{$current_permissions})) {
                   8325:             if ($key =~ /\0accesscontrol$/) {
                   8326:                 if (defined($group)) {
                   8327:                     if ($key !~ m-^\Q$group\E/-) {
                   8328:                         next;
                   8329:                     }
                   8330:                 }
                   8331:                 my ($fullpath) = split(/\0/,$key);
                   8332:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8333:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8334:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8335:                     }
                   8336:                 }
                   8337:             }
                   8338:         }
                   8339:     }
                   8340:     return %access;
                   8341: }
                   8342: 
                   8343: sub modify_access_controls {
                   8344:     my ($file_name,$changes,$domain,$user)=@_;
                   8345:     my ($outcome,$deloutcome);
                   8346:     my %store_permissions;
                   8347:     my %new_values;
                   8348:     my %new_control;
                   8349:     my %translation;
                   8350:     my @deletions = ();
                   8351:     my $now = time;
                   8352:     if (exists($$changes{'activate'})) {
                   8353:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8354:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8355:             my $numnew = scalar(@newitems);
                   8356:             for (my $i=0; $i<$numnew; $i++) {
                   8357:                 my $newkey = $newitems[$i];
                   8358:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8359:                 if ($newkey =~ /^\d+:/) { 
                   8360:                     $newkey =~ s/^(\d+)/$newid/;
                   8361:                     $translation{$1} = $newid;
                   8362:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8363:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8364:                     $translation{$1} = $newid;
                   8365:                 }
1.749     raeburn  8366:                 $new_values{$file_name."\0".$newkey} = 
                   8367:                                           $$changes{'activate'}{$newitems[$i]};
                   8368:                 $new_control{$newkey} = $now;
                   8369:             }
                   8370:         }
                   8371:     }
                   8372:     my %todelete;
                   8373:     my %changed_items;
                   8374:     foreach my $action ('delete','update') {
                   8375:         if (exists($$changes{$action})) {
                   8376:             if (ref($$changes{$action}) eq 'HASH') {
                   8377:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8378:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8379:                     if ($action eq 'delete') { 
                   8380:                         $todelete{$itemnum} = 1;
                   8381:                     } else {
                   8382:                         $changed_items{$itemnum} = $key;
                   8383:                     }
                   8384:                 }
1.745     raeburn  8385:             }
                   8386:         }
1.749     raeburn  8387:     }
                   8388:     # get lock on access controls for file.
                   8389:     my $lockhash = {
                   8390:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8391:                                                        ':'.$env{'user.domain'},
                   8392:                    }; 
                   8393:     my $tries = 0;
                   8394:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8395:    
                   8396:     while (($gotlock ne 'ok') && $tries <3) {
                   8397:         $tries ++;
                   8398:         sleep 1;
                   8399:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8400:     }
                   8401:     if ($gotlock eq 'ok') {
                   8402:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8403:         my ($tmp)=keys(%curr_permissions);
                   8404:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8405:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8406:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8407:             if (ref($curr_controls) eq 'HASH') {
                   8408:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8409:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8410:                     if (defined($todelete{$itemnum})) {
                   8411:                         push(@deletions,$file_name."\0".$control_item);
                   8412:                     } else {
                   8413:                         if (defined($changed_items{$itemnum})) {
                   8414:                             $new_control{$changed_items{$itemnum}} = $now;
                   8415:                             push(@deletions,$file_name."\0".$control_item);
                   8416:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8417:                         } else {
                   8418:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8419:                         }
                   8420:                     }
1.745     raeburn  8421:                 }
                   8422:             }
                   8423:         }
1.970     raeburn  8424:         my ($group);
                   8425:         if (&is_course($domain,$user)) {
                   8426:             ($group,my $file) = split(/\//,$file_name,2);
                   8427:         }
1.749     raeburn  8428:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8429:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8430:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8431:         #  remove lock
                   8432:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8433:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8434:         my $sqlresult =
1.970     raeburn  8435:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8436:                                     $group);
1.749     raeburn  8437:     } else {
                   8438:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8439:     }
1.749     raeburn  8440:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8441: }
                   8442: 
1.827     raeburn  8443: sub make_public_indefinitely {
                   8444:     my ($requrl) = @_;
                   8445:     my $now = time;
                   8446:     my $action = 'activate';
                   8447:     my $aclnum = 0;
                   8448:     if (&is_portfolio_url($requrl)) {
                   8449:         my (undef,$udom,$unum,$file_name,$group) =
                   8450:             &parse_portfolio_url($requrl);
                   8451:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8452:         my %access_controls = &get_access_controls($current_perms,
                   8453:                                                    $group,$file_name);
                   8454:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8455:             my ($num,$scope,$end,$start) = 
                   8456:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8457:             if ($scope eq 'public') {
                   8458:                 if ($start <= $now && $end == 0) {
                   8459:                     $action = 'none';
                   8460:                 } else {
                   8461:                     $action = 'update';
                   8462:                     $aclnum = $num;
                   8463:                 }
                   8464:                 last;
                   8465:             }
                   8466:         }
                   8467:         if ($action eq 'none') {
                   8468:              return 'ok';
                   8469:         } else {
                   8470:             my %changes;
                   8471:             my $newend = 0;
                   8472:             my $newstart = $now;
                   8473:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8474:             $changes{$action}{$newkey} = {
                   8475:                 type => 'public',
                   8476:                 time => {
                   8477:                     start => $newstart,
                   8478:                     end   => $newend,
                   8479:                 },
                   8480:             };
                   8481:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8482:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8483:             return $outcome;
                   8484:         }
                   8485:     } else {
                   8486:         return 'invalid';
                   8487:     }
                   8488: }
                   8489: 
1.745     raeburn  8490: #------------------------------------------------------Get Marked as Read Only
                   8491: 
                   8492: sub get_marked_as_readonly {
                   8493:     my ($domain,$user,$what,$group) = @_;
                   8494:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8495:     my @readonly_files;
1.629     banghart 8496:     my $cmp1=$what;
                   8497:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8498:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8499:         if (defined($group)) {
                   8500:             if ($file_name !~ m-^\Q$group\E/-) {
                   8501:                 next;
                   8502:             }
                   8503:         }
1.561     banghart 8504:         if (ref($value) eq "ARRAY"){
                   8505:             foreach my $stored_what (@{$value}) {
1.629     banghart 8506:                 my $cmp2=$stored_what;
1.759     albertel 8507:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8508:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8509:                 }
1.629     banghart 8510:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8511:                     push(@readonly_files, $file_name);
1.745     raeburn  8512:                     last;
1.563     banghart 8513:                 } elsif (!defined($what)) {
                   8514:                     push(@readonly_files, $file_name);
1.745     raeburn  8515:                     last;
1.561     banghart 8516:                 }
                   8517:             }
1.745     raeburn  8518:         }
1.561     banghart 8519:     }
                   8520:     return @readonly_files;
                   8521: }
1.577     banghart 8522: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8523: 
1.577     banghart 8524: sub get_marked_as_readonly_hash {
1.745     raeburn  8525:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8526:     my %readonly_files;
1.745     raeburn  8527:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8528:         if (defined($group)) {
                   8529:             if ($file_name !~ m-^\Q$group\E/-) {
                   8530:                 next;
                   8531:             }
                   8532:         }
1.577     banghart 8533:         if (ref($value) eq "ARRAY"){
                   8534:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8535:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8536:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8537:                         if ($lock_descriptor eq 'graded') {
                   8538:                             $readonly_files{$file_name} = 'graded';
                   8539:                         } elsif ($lock_descriptor eq 'handback') {
                   8540:                             $readonly_files{$file_name} = 'handback';
                   8541:                         } else {
                   8542:                             if (!exists($readonly_files{$file_name})) {
                   8543:                                 $readonly_files{$file_name} = 'locked';
                   8544:                             }
                   8545:                         }
1.745     raeburn  8546:                     }
1.750     banghart 8547:                 } 
1.577     banghart 8548:             }
                   8549:         } 
                   8550:     }
                   8551:     return %readonly_files;
                   8552: }
1.559     banghart 8553: # ------------------------------------------------------------ Unmark as Read Only
                   8554: 
                   8555: sub unmark_as_readonly {
1.629     banghart 8556:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8557:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8558:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8559:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8560:     my $symb_crs = $what;
                   8561:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8562:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8563:     my ($tmp)=keys(%current_permissions);
                   8564:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8565:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8566:     foreach my $file (@readonly_files) {
1.759     albertel 8567: 	my $clean_file = &declutter_portfile($file);
                   8568: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8569: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8570:         my @new_locks;
                   8571:         my @del_keys;
                   8572:         if (ref($current_locks) eq "ARRAY"){
                   8573:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8574:                 my $compare=$locker;
1.749     raeburn  8575:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8576:                     $compare=join('',@{$locker});
1.746     raeburn  8577:                     if ($compare ne $symb_crs) {
                   8578:                         push(@new_locks, $locker);
                   8579:                     }
1.563     banghart 8580:                 }
                   8581:             }
1.650     albertel 8582:             if (scalar(@new_locks) > 0) {
1.563     banghart 8583:                 $current_permissions{$file} = \@new_locks;
                   8584:             } else {
                   8585:                 push(@del_keys, $file);
1.613     albertel 8586:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8587:                 delete($current_permissions{$file});
1.563     banghart 8588:             }
                   8589:         }
1.561     banghart 8590:     }
1.613     albertel 8591:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8592:     return;
                   8593: }
1.512     banghart 8594: 
1.17      www      8595: # ------------------------------------------------------------ Directory lister
                   8596: 
                   8597: sub dirlist {
1.955     raeburn  8598:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8599:     $uri=~s/^\///;
                   8600:     $uri=~s/\/$//;
1.253     stredwic 8601:     my ($udom, $uname);
1.955     raeburn  8602:     if ($getuserdir) {
1.253     stredwic 8603:         $udom = $userdomain;
                   8604:         $uname = $username;
1.955     raeburn  8605:     } else {
                   8606:         (undef,$udom,$uname)=split(/\//,$uri);
                   8607:         if(defined($userdomain)) {
                   8608:             $udom = $userdomain;
                   8609:         }
                   8610:         if(defined($username)) {
                   8611:             $uname = $username;
                   8612:         }
1.253     stredwic 8613:     }
1.955     raeburn  8614:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8615: 
1.955     raeburn  8616:     $dirRoot = $perlvar{'lonDocRoot'};
                   8617:     if (defined($getpropath)) {
                   8618:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8619:         $dirRoot =~ s/\/$//;
1.955     raeburn  8620:     } elsif (defined($getuserdir)) {
                   8621:         my $subdir=$uname.'__';
                   8622:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8623:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8624:                    ."/$udom/$subdir/$uname";
                   8625:     } elsif (defined($alternateRoot)) {
                   8626:         $dirRoot = $alternateRoot;
1.751     banghart 8627:     }
1.253     stredwic 8628: 
                   8629:     if($udom) {
                   8630:         if($uname) {
1.1135    raeburn  8631:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8632:             if ($uhome eq 'no_host') {
                   8633:                 return ([],'no_host');
                   8634:             }
1.955     raeburn  8635:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8636:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8637:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8638:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8639:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8640:             } else {
                   8641:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8642:             }
1.605     matthew  8643:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8644:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8645:                 @listing_results = split(/:/,$listing);
                   8646:             } else {
                   8647:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8648:             }
1.1135    raeburn  8649:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8650:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8651:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8652:                 return ([],$listing);
                   8653:             } else {
                   8654:                 return (\@listing_results);
1.1135    raeburn  8655:             }
1.955     raeburn  8656:         } elsif(!$alternateRoot) {
1.1136    raeburn  8657:             my (%allusers,%listerror);
1.841     albertel 8658: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8659:  	    foreach my $tryserver (keys(%servers)) {
                   8660:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8661:                                   &escape($udom),$tryserver);
                   8662:                 if ($listing eq 'unknown_cmd') {
                   8663: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8664: 				      $udom, $tryserver);
                   8665:                 } else {
                   8666:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8667:                 }
1.841     albertel 8668: 		if ($listing eq 'unknown_cmd') {
                   8669: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8670: 				      $udom, $tryserver);
                   8671: 		    @listing_results = split(/:/,$listing);
                   8672: 		} else {
                   8673: 		    @listing_results =
                   8674: 			map { &unescape($_); } split(/:/,$listing);
                   8675: 		}
1.1136    raeburn  8676:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8677:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8678:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8679:                     $listerror{$tryserver} = $listing;
                   8680:                 } else {
1.841     albertel 8681: 		    foreach my $line (@listing_results) {
                   8682: 			my ($entry) = split(/&/,$line,2);
                   8683: 			$allusers{$entry} = 1;
                   8684: 		    }
                   8685: 		}
1.253     stredwic 8686:             }
1.1136    raeburn  8687:             my @alluserslist=();
1.800     albertel 8688:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8689:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8690:             }
1.1136    raeburn  8691:             return (\@alluserslist);
1.253     stredwic 8692:         } else {
1.1136    raeburn  8693:             return ([],'missing username');
1.253     stredwic 8694:         }
1.955     raeburn  8695:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8696:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8697:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8698:         return (\@all_domains);
1.955     raeburn  8699:     } else {
1.1136    raeburn  8700:         return ([],'missing domain');
1.275     stredwic 8701:     }
                   8702: }
                   8703: 
                   8704: # --------------------------------------------- GetFileTimestamp
                   8705: # This function utilizes dirlist and returns the date stamp for
                   8706: # when it was last modified.  It will also return an error of -1
                   8707: # if an error occurs
                   8708: 
                   8709: sub GetFileTimestamp {
1.955     raeburn  8710:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8711:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8712:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8713:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8714:                                     undef,$getuserdir);
                   8715:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8716:         return -1;
                   8717:     }
                   8718:     if (ref($fileref) eq 'ARRAY') {
                   8719:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8720:         # @stats contains first the filename, then the stat output
                   8721:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8722:     } else {
                   8723:         return -1;
1.253     stredwic 8724:     }
1.26      www      8725: }
                   8726: 
1.712     albertel 8727: sub stat_file {
                   8728:     my ($uri) = @_;
1.787     albertel 8729:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8730: 
1.955     raeburn  8731:     my ($udom,$uname,$file);
1.712     albertel 8732:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8733: 	($udom,$uname,$file) =
1.811     albertel 8734: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8735: 	$file = 'userfiles/'.$file;
                   8736:     }
                   8737:     if ($uri =~ m-^/res/-) {
                   8738: 	($udom,$uname) = 
1.807     albertel 8739: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8740: 	$file = $uri;
                   8741:     }
                   8742: 
                   8743:     if (!$udom || !$uname || !$file) {
                   8744: 	# unable to handle the uri
                   8745: 	return ();
                   8746:     }
1.956     raeburn  8747:     my $getpropath;
                   8748:     if ($file =~ /^userfiles\//) {
                   8749:         $getpropath = 1;
                   8750:     }
1.1136    raeburn  8751:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8752:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8753:         return ();
                   8754:     } else {
                   8755:         if (ref($listref) eq 'ARRAY') {
                   8756:             my @stats = split('&',$listref->[0]);
                   8757: 	    shift(@stats); #filename is first
                   8758: 	    return @stats;
                   8759:         }
1.712     albertel 8760:     }
                   8761:     return ();
                   8762: }
                   8763: 
1.26      www      8764: # -------------------------------------------------------- Value of a Condition
                   8765: 
1.713     albertel 8766: # gets the value of a specific preevaluated condition
                   8767: #    stored in the string  $env{user.state.<cid>}
                   8768: # or looks up a condition reference in the bighash and if if hasn't
                   8769: # already been evaluated recurses into docondval to get the value of
                   8770: # the condition, then memoizing it to 
                   8771: #   $env{user.state.<cid>.<condition>}
1.40      www      8772: sub directcondval {
                   8773:     my $number=shift;
1.620     albertel 8774:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8775: 	&Apache::lonuserstate::evalstate();
                   8776:     }
1.713     albertel 8777:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8778: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8779:     } elsif ($number =~ /^_/) {
                   8780: 	my $sub_condition;
                   8781: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8782: 		&GDBM_READER(),0640)) {
                   8783: 	    $sub_condition=$bighash{'conditions'.$number};
                   8784: 	    untie(%bighash);
                   8785: 	}
                   8786: 	my $value = &docondval($sub_condition);
1.949     raeburn  8787: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8788: 	return $value;
                   8789:     }
1.620     albertel 8790:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8791:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8792:     } else {
                   8793:        return 2;
                   8794:     }
                   8795: }
                   8796: 
1.713     albertel 8797: # get the collection of conditions for this resource
1.26      www      8798: sub condval {
                   8799:     my $condidx=shift;
1.54      www      8800:     my $allpathcond='';
1.713     albertel 8801:     foreach my $cond (split(/\|/,$condidx)) {
                   8802: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8803: 	    $allpathcond.=
                   8804: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8805: 	}
1.191     harris41 8806:     }
1.54      www      8807:     $allpathcond=~s/\|$//;
1.713     albertel 8808:     return &docondval($allpathcond);
                   8809: }
                   8810: 
                   8811: #evaluates an expression of conditions
                   8812: sub docondval {
                   8813:     my ($allpathcond) = @_;
                   8814:     my $result=0;
                   8815:     if ($env{'request.course.id'}
                   8816: 	&& defined($allpathcond)) {
                   8817: 	my $operand='|';
                   8818: 	my @stack;
                   8819: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8820: 	    if ($chunk eq '(') {
                   8821: 		push @stack,($operand,$result);
                   8822: 	    } elsif ($chunk eq ')') {
                   8823: 		my $before=pop @stack;
                   8824: 		if (pop @stack eq '&') {
                   8825: 		    $result=$result>$before?$before:$result;
                   8826: 		} else {
                   8827: 		    $result=$result>$before?$result:$before;
                   8828: 		}
                   8829: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8830: 		$operand=$chunk;
                   8831: 	    } else {
                   8832: 		my $new=directcondval($chunk);
                   8833: 		if ($operand eq '&') {
                   8834: 		    $result=$result>$new?$new:$result;
                   8835: 		} else {
                   8836: 		    $result=$result>$new?$result:$new;
                   8837: 		}
                   8838: 	    }
                   8839: 	}
1.26      www      8840:     }
                   8841:     return $result;
1.421     albertel 8842: }
                   8843: 
                   8844: # ---------------------------------------------------- Devalidate courseresdata
                   8845: 
                   8846: sub devalidatecourseresdata {
                   8847:     my ($coursenum,$coursedomain)=@_;
                   8848:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8849:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8850: }
                   8851: 
1.763     www      8852: 
1.200     www      8853: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8854: #
                   8855: #  Parameters:
                   8856: #      $coursenum    - Number of the course.
                   8857: #      $coursedomain - Domain at which the course was created.
                   8858: #  Returns:
                   8859: #     A hash of the course parameters along (I think) with timestamps
                   8860: #     and version info.
1.877     foxr     8861: 
1.624     albertel 8862: sub get_courseresdata {
                   8863:     my ($coursenum,$coursedomain)=@_;
1.200     www      8864:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8865:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8866:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8867:     my %dumpreply;
1.417     albertel 8868:     unless (defined($cached)) {
1.624     albertel 8869: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8870: 	$result=\%dumpreply;
1.251     albertel 8871: 	my ($tmp) = keys(%dumpreply);
                   8872: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8873: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8874: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8875: 	    return $tmp;
1.416     albertel 8876: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8877: 	    $result=undef;
1.599     albertel 8878: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8879: 	}
                   8880:     }
1.624     albertel 8881:     return $result;
                   8882: }
                   8883: 
1.633     albertel 8884: sub devalidateuserresdata {
                   8885:     my ($uname,$udom)=@_;
                   8886:     my $hashid="$udom:$uname";
                   8887:     &devalidate_cache_new('userres',$hashid);
                   8888: }
                   8889: 
1.624     albertel 8890: sub get_userresdata {
                   8891:     my ($uname,$udom)=@_;
                   8892:     #most student don\'t have any data set, check if there is some data
                   8893:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8894: 
                   8895:     my $hashid="$udom:$uname";
                   8896:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8897:     if (!defined($cached)) {
                   8898: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8899: 	$result=\%resourcedata;
                   8900: 	&do_cache_new('userres',$hashid,$result,600);
                   8901:     }
                   8902:     my ($tmp)=keys(%$result);
                   8903:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8904: 	return $result;
                   8905:     }
                   8906:     #error 2 occurs when the .db doesn't exist
                   8907:     if ($tmp!~/error: 2 /) {
1.672     albertel 8908: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8909: 		 " Trying to get resource data for ".
                   8910: 		 $uname." at ".$udom.": ".
                   8911: 		 $tmp."</font>");
                   8912:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8913: 	#&EXT_cache_set($udom,$uname);
                   8914: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8915: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8916:     }
                   8917:     return $tmp;
                   8918: }
1.879     foxr     8919: #----------------------------------------------- resdata - return resource data
                   8920: #  Purpose:
                   8921: #    Return resource data for either users or for a course.
                   8922: #  Parameters:
                   8923: #     $name      - Course/user name.
                   8924: #     $domain    - Name of the domain the user/course is registered on.
                   8925: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8926: #     @which     - Array of names of resources desired.
                   8927: #  Returns:
                   8928: #     The value of the first reasource in @which that is found in the
                   8929: #     resource hash.
                   8930: #  Exceptional Conditions:
                   8931: #     If the $type passed in is not valid (not the string 'course' or 
                   8932: #     'user', an undefined  reference is returned.
                   8933: #     If none of the resources are found, an undef is returned
1.624     albertel 8934: sub resdata {
                   8935:     my ($name,$domain,$type,@which)=@_;
                   8936:     my $result;
                   8937:     if ($type eq 'course') {
                   8938: 	$result=&get_courseresdata($name,$domain);
                   8939:     } elsif ($type eq 'user') {
                   8940: 	$result=&get_userresdata($name,$domain);
                   8941:     }
                   8942:     if (!ref($result)) { return $result; }    
1.251     albertel 8943:     foreach my $item (@which) {
1.927     albertel 8944: 	if (defined($result->{$item->[0]})) {
                   8945: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8946: 	}
1.250     albertel 8947:     }
1.291     albertel 8948:     return undef;
1.200     www      8949: }
                   8950: 
1.379     matthew  8951: #
                   8952: # EXT resource caching routines
                   8953: #
                   8954: 
                   8955: sub clear_EXT_cache_status {
1.383     albertel 8956:     &delenv('cache.EXT.');
1.379     matthew  8957: }
                   8958: 
                   8959: sub EXT_cache_status {
                   8960:     my ($target_domain,$target_user) = @_;
1.383     albertel 8961:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8962:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8963:         # We know already the user has no data
                   8964:         return 1;
                   8965:     } else {
                   8966:         return 0;
                   8967:     }
                   8968: }
                   8969: 
                   8970: sub EXT_cache_set {
                   8971:     my ($target_domain,$target_user) = @_;
1.383     albertel 8972:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8973:     #&appenv({$cachename => time});
1.379     matthew  8974: }
                   8975: 
1.28      www      8976: # --------------------------------------------------------- Value of a Variable
1.58      www      8977: sub EXT {
1.715     albertel 8978: 
1.395     albertel 8979:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8980:     unless ($varname) { return ''; }
1.218     albertel 8981:     #get real user name/domain, courseid and symb
                   8982:     my $courseid;
1.359     albertel 8983:     my $publicuser;
1.427     www      8984:     if ($symbparm) {
                   8985: 	$symbparm=&get_symb_from_alias($symbparm);
                   8986:     }
1.218     albertel 8987:     if (!($uname && $udom)) {
1.790     albertel 8988:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8989:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8990:     } else {
1.620     albertel 8991: 	$courseid=$env{'request.course.id'};
1.218     albertel 8992:     }
1.48      www      8993:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8994:     my $rest;
1.320     albertel 8995:     if (defined($therest[0])) {
1.48      www      8996:        $rest=join('.',@therest);
                   8997:     } else {
                   8998:        $rest='';
                   8999:     }
1.320     albertel 9000: 
1.57      www      9001:     my $qualifierrest=$qualifier;
                   9002:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9003:     my $spacequalifierrest=$space;
                   9004:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9005:     if ($realm eq 'user') {
1.48      www      9006: # --------------------------------------------------------------- user.resource
                   9007: 	if ($space eq 'resource') {
1.651     albertel 9008: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9009: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9010: 		 &&
1.744     albertel 9011: 		 ($symbparm eq &symbread()) ) {	
                   9012: 		# if we are in the middle of processing the resource the
                   9013: 		# get the value we are planning on committing
                   9014:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9015:                     return $Apache::lonhomework::results{$qualifierrest};
                   9016:                 } else {
                   9017:                     return $Apache::lonhomework::history{$qualifierrest};
                   9018:                 }
1.335     albertel 9019: 	    } else {
1.359     albertel 9020: 		my %restored;
1.620     albertel 9021: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9022: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9023: 		} else {
                   9024: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9025: 		}
1.335     albertel 9026: 		return $restored{$qualifierrest};
                   9027: 	    }
1.48      www      9028: # ----------------------------------------------------------------- user.access
                   9029:         } elsif ($space eq 'access') {
1.218     albertel 9030: 	    # FIXME - not supporting calls for a specific user
1.48      www      9031:             return &allowed($qualifier,$rest);
                   9032: # ------------------------------------------ user.preferences, user.environment
                   9033:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9034: 	    if (($uname eq $env{'user.name'}) &&
                   9035: 		($udom eq $env{'user.domain'})) {
                   9036: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9037: 	    } else {
1.359     albertel 9038: 		my %returnhash;
                   9039: 		if (!$publicuser) {
                   9040: 		    %returnhash=&userenvironment($udom,$uname,
                   9041: 						 $qualifierrest);
                   9042: 		}
1.218     albertel 9043: 		return $returnhash{$qualifierrest};
                   9044: 	    }
1.48      www      9045: # ----------------------------------------------------------------- user.course
                   9046:         } elsif ($space eq 'course') {
1.218     albertel 9047: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9048:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9049: # ------------------------------------------------------------------- user.role
                   9050:         } elsif ($space eq 'role') {
1.218     albertel 9051: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9052:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9053:             if ($qualifier eq 'value') {
                   9054: 		return $role;
                   9055:             } elsif ($qualifier eq 'extent') {
                   9056:                 return $where;
                   9057:             }
                   9058: # ----------------------------------------------------------------- user.domain
                   9059:         } elsif ($space eq 'domain') {
1.218     albertel 9060:             return $udom;
1.48      www      9061: # ------------------------------------------------------------------- user.name
                   9062:         } elsif ($space eq 'name') {
1.218     albertel 9063:             return $uname;
1.48      www      9064: # ---------------------------------------------------- Any other user namespace
1.29      www      9065:         } else {
1.359     albertel 9066: 	    my %reply;
                   9067: 	    if (!$publicuser) {
                   9068: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9069: 	    }
                   9070: 	    return $reply{$qualifierrest};
1.48      www      9071:         }
1.236     www      9072:     } elsif ($realm eq 'query') {
                   9073: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9074:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9075: 						[$spacequalifierrest]);
1.620     albertel 9076: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9077:    } elsif ($realm eq 'request') {
1.48      www      9078: # ------------------------------------------------------------- request.browser
                   9079:         if ($space eq 'browser') {
1.1145    bisitz   9080:             return $env{'browser.'.$qualifier};
1.57      www      9081: # ------------------------------------------------------------ request.filename
                   9082:         } else {
1.620     albertel 9083:             return $env{'request.'.$spacequalifierrest};
1.29      www      9084:         }
1.28      www      9085:     } elsif ($realm eq 'course') {
1.48      www      9086: # ---------------------------------------------------------- course.description
1.620     albertel 9087:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9088:     } elsif ($realm eq 'resource') {
1.165     www      9089: 
1.620     albertel 9090: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9091: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9092: 	}
1.693     albertel 9093: 
                   9094: 	if ($space eq 'title') {
                   9095: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9096: 	    return &gettitle($symbparm);
                   9097: 	}
                   9098: 	
                   9099: 	if ($space eq 'map') {
                   9100: 	    my ($map) = &decode_symb($symbparm);
                   9101: 	    return &symbread($map);
                   9102: 	}
1.905     albertel 9103: 	if ($space eq 'filename') {
                   9104: 	    if ($symbparm) {
                   9105: 		return &clutter((&decode_symb($symbparm))[2]);
                   9106: 	    }
                   9107: 	    return &hreflocation('',$env{'request.filename'});
                   9108: 	}
1.693     albertel 9109: 
                   9110: 	my ($section, $group, @groups);
1.593     albertel 9111: 	my ($courselevelm,$courselevel);
1.539     albertel 9112: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9113: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9114: 
1.218     albertel 9115: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9116: 
1.60      www      9117: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9118: 	    my $symbp=$symbparm;
1.735     albertel 9119: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9120: 
                   9121: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9122: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9123: 
1.620     albertel 9124: 	    if (($env{'user.name'} eq $uname) &&
                   9125: 		($env{'user.domain'} eq $udom)) {
                   9126: 		$section=$env{'request.course.sec'};
1.733     raeburn  9127:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9128:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9129: 	    } else {
1.539     albertel 9130: 		if (! defined($usection)) {
1.551     albertel 9131: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9132: 		} else {
                   9133: 		    $section = $usection;
                   9134: 		}
1.733     raeburn  9135:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9136: 	    }
                   9137: 
                   9138: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9139: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9140: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9141: 
1.593     albertel 9142: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9143: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9144: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9145: 
1.60      www      9146: # ----------------------------------------------------------- first, check user
1.624     albertel 9147: 
                   9148: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9149: 				       ([$courselevelr,'resource'],
                   9150: 					[$courselevelm,'map'     ],
                   9151: 					[$courselevel, 'course'  ]));
1.931     albertel 9152: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9153: 
1.594     albertel 9154: # ------------------------------------------------ second, check some of course
1.684     raeburn  9155:             my $coursereply;
1.691     raeburn  9156:             if (@groups > 0) {
                   9157:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9158:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9159:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9160:             }
1.96      www      9161: 
1.684     raeburn  9162: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9163: 				  $env{'course.'.$courseid.'.domain'},
                   9164: 				  'course',
                   9165: 				  ([$seclevelr,   'resource'],
                   9166: 				   [$seclevelm,   'map'     ],
                   9167: 				   [$seclevel,    'course'  ],
                   9168: 				   [$courselevelr,'resource']));
                   9169: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9170: 
1.60      www      9171: # ------------------------------------------------------ third, check map parms
1.218     albertel 9172: 	    my %parmhash=();
                   9173: 	    my $thisparm='';
                   9174: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9175: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9176: 		    &GDBM_READER(),0640)) {
1.218     albertel 9177: 		$thisparm=$parmhash{$symbparm};
                   9178: 		untie(%parmhash);
                   9179: 	    }
1.927     albertel 9180: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9181: 	}
1.594     albertel 9182: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9183: 
1.218     albertel 9184: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9185: 	my $filename;
                   9186: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9187: 	if ($symbparm) {
1.409     www      9188: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9189: 	} else {
1.620     albertel 9190: 	    $filename=$env{'request.filename'};
1.282     albertel 9191: 	}
                   9192: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9193: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9194: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9195: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9196: 
1.927     albertel 9197: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9198: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9199: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9200: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9201: 				     $env{'course.'.$courseid.'.domain'},
                   9202: 				     'course',
1.927     albertel 9203: 				     ([$courselevelm,'map'   ],
                   9204: 				      [$courselevel, 'course']));
                   9205: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9206: 	}
1.145     www      9207: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9208: 	unless ($space eq '0') {
1.336     albertel 9209: 	    my @parts=split(/_/,$space);
                   9210: 	    my $id=pop(@parts);
                   9211: 	    my $part=join('_',@parts);
                   9212: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9213: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9214: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9215: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9216: 	}
1.395     albertel 9217: 	if ($recurse) { return undef; }
                   9218: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9219: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9220: # ---------------------------------------------------- Any other user namespace
                   9221:     } elsif ($realm eq 'environment') {
                   9222: # ----------------------------------------------------------------- environment
1.620     albertel 9223: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9224: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9225: 	} else {
1.770     albertel 9226: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9227: 		return '';
                   9228: 	    }
1.219     albertel 9229: 	    my %returnhash=&userenvironment($udom,$uname,
                   9230: 					    $spacequalifierrest);
                   9231: 	    return $returnhash{$spacequalifierrest};
                   9232: 	}
1.28      www      9233:     } elsif ($realm eq 'system') {
1.48      www      9234: # ----------------------------------------------------------------- system.time
                   9235: 	if ($space eq 'time') {
                   9236: 	    return time;
                   9237:         }
1.696     albertel 9238:     } elsif ($realm eq 'server') {
                   9239: # ----------------------------------------------------------------- system.time
                   9240: 	if ($space eq 'name') {
                   9241: 	    return $ENV{'SERVER_NAME'};
                   9242:         }
1.28      www      9243:     }
1.48      www      9244:     return '';
1.61      www      9245: }
                   9246: 
1.927     albertel 9247: sub get_reply {
                   9248:     my ($reply_value) = @_;
1.940     raeburn  9249:     if (ref($reply_value) eq 'ARRAY') {
                   9250:         if (wantarray) {
                   9251: 	    return @$reply_value;
                   9252:         }
                   9253:         return $reply_value->[0];
                   9254:     } else {
                   9255:         return $reply_value;
1.927     albertel 9256:     }
                   9257: }
                   9258: 
1.691     raeburn  9259: sub check_group_parms {
                   9260:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9261:     my @groupitems = ();
                   9262:     my $resultitem;
1.927     albertel 9263:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9264:     foreach my $group (@{$groups}) {
                   9265:         foreach my $level (@levels) {
1.927     albertel 9266:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9267:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9268:         }
                   9269:     }
                   9270:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9271:                             $env{'course.'.$courseid.'.domain'},
                   9272:                                      'course',@groupitems);
                   9273:     return $coursereply;
                   9274: }
                   9275: 
                   9276: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9277:     my ($courseid,@groups) = @_;
                   9278:     @groups = sort(@groups);
1.691     raeburn  9279:     return @groups;
                   9280: }
                   9281: 
1.395     albertel 9282: sub packages_tab_default {
                   9283:     my ($uri,$varname)=@_;
                   9284:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9285: 
                   9286:     my (@extension,@specifics,$do_default);
                   9287:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9288: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9289: 	if ($pack_type eq 'default') {
                   9290: 	    $do_default=1;
                   9291: 	} elsif ($pack_type eq 'extension') {
                   9292: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9293: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9294: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9295: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9296: 	}
                   9297:     }
                   9298:     # first look for a package that matches the requested part id
                   9299:     foreach my $package (@specifics) {
                   9300: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9301: 	next if ($pack_part ne $part);
                   9302: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9303: 	    return $packagetab{"$pack_type&$name&default"};
                   9304: 	}
                   9305:     }
                   9306:     # look for any possible matching non extension_ package
                   9307:     foreach my $package (@specifics) {
                   9308: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9309: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9310: 	    return $packagetab{"$pack_type&$name&default"};
                   9311: 	}
1.585     albertel 9312: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9313: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9314: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9315: 	}
                   9316:     }
1.738     albertel 9317:     # look for any posible extension_ match
                   9318:     foreach my $package (@extension) {
                   9319: 	my ($package,$pack_type)=@{$package};
                   9320: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9321: 	    return $packagetab{"$pack_type&$name&default"};
                   9322: 	}
                   9323: 	if (defined($packagetab{$package."&$name&default"})) {
                   9324: 	    return $packagetab{$package."&$name&default"};
                   9325: 	}
                   9326:     }
                   9327:     # look for a global default setting
                   9328:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9329: 	return $packagetab{"default&$name&default"};
                   9330:     }
1.395     albertel 9331:     return undef;
                   9332: }
                   9333: 
1.334     albertel 9334: sub add_prefix_and_part {
                   9335:     my ($prefix,$part)=@_;
                   9336:     my $keyroot;
                   9337:     if (defined($prefix) && $prefix !~ /^__/) {
                   9338: 	# prefix that has a part already
                   9339: 	$keyroot=$prefix;
                   9340:     } elsif (defined($prefix)) {
                   9341: 	# prefix that is missing a part
                   9342: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9343:     } else {
                   9344: 	# no prefix at all
                   9345: 	if (defined($part)) { $keyroot='_'.$part; }
                   9346:     }
                   9347:     return $keyroot;
                   9348: }
                   9349: 
1.71      www      9350: # ---------------------------------------------------------------- Get metadata
                   9351: 
1.599     albertel 9352: my %metaentry;
1.1070    www      9353: my %importedpartids;
1.71      www      9354: sub metadata {
1.176     www      9355:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9356:     $uri=&declutter($uri);
1.288     albertel 9357:     # if it is a non metadata possible uri return quickly
1.529     albertel 9358:     if (($uri eq '') || 
                   9359: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9360: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9361:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9362: 	return undef;
                   9363:     }
1.1140    www      9364:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9365: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9366: 	return undef;
1.288     albertel 9367:     }
1.73      www      9368:     my $filename=$uri;
                   9369:     $uri=~s/\.meta$//;
1.172     www      9370: #
                   9371: # Is the metadata already cached?
1.177     www      9372: # Look at timestamp of caching
1.172     www      9373: # Everything is cached by the main uri, libraries are never directly cached
                   9374: #
1.428     albertel 9375:     if (!defined($liburi)) {
1.599     albertel 9376: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9377: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9378:     }
                   9379:     {
1.1069    www      9380: # Imported parts would go here
1.1070    www      9381:         my %importedids=();
                   9382:         my @origfileimportpartids=();
1.1069    www      9383:         my $importedparts=0;
1.172     www      9384: #
                   9385: # Is this a recursive call for a library?
                   9386: #
1.599     albertel 9387: #	if (! exists($metacache{$uri})) {
                   9388: #	    $metacache{$uri}={};
                   9389: #	}
1.924     albertel 9390: 	my $cachetime = 60*60;
1.171     www      9391:         if ($liburi) {
                   9392: 	    $liburi=&declutter($liburi);
                   9393:             $filename=$liburi;
1.401     bowersj2 9394:         } else {
1.599     albertel 9395: 	    &devalidate_cache_new('meta',$uri);
                   9396: 	    undef(%metaentry);
1.401     bowersj2 9397: 	}
1.140     www      9398:         my %metathesekeys=();
1.73      www      9399:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9400: 	my $metastring;
1.1140    www      9401: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9402: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9403: 	    $metastring = 
1.929     albertel 9404: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9405: 					  ('grade_target' => 'meta'));
                   9406: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9407: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9408:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9409: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9410: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9411: 	    $metastring=&getfile($file);
1.489     albertel 9412: 	}
1.208     albertel 9413:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9414:         my $token;
1.140     www      9415:         undef %metathesekeys;
1.71      www      9416:         while ($token=$parser->get_token) {
1.339     albertel 9417: 	    if ($token->[0] eq 'S') {
                   9418: 		if (defined($token->[2]->{'package'})) {
1.172     www      9419: #
                   9420: # This is a package - get package info
                   9421: #
1.339     albertel 9422: 		    my $package=$token->[2]->{'package'};
                   9423: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9424: 		    if (defined($token->[2]->{'id'})) { 
                   9425: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9426: 		    }
1.599     albertel 9427: 		    if ($metaentry{':packages'}) {
                   9428: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9429: 		    } else {
1.599     albertel 9430: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9431: 		    }
1.736     albertel 9432: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9433: 			my $part=$keyroot;
                   9434: 			$part=~s/^\_//;
1.736     albertel 9435: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9436: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9437: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9438: 			    # ignore package.tab specified default values
                   9439:                             # here &package_tab_default() will fetch those
                   9440: 			    if ($subp eq 'default') { next; }
1.736     albertel 9441: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9442: 			    my $unikey;
                   9443: 			    if ($pack =~ /_0$/) {
                   9444: 				$unikey='parameter_0_'.$name;
                   9445: 				$part=0;
                   9446: 			    } else {
                   9447: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9448: 			    }
1.339     albertel 9449: 			    if ($subp eq 'display') {
                   9450: 				$value.=' [Part: '.$part.']';
                   9451: 			    }
1.599     albertel 9452: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9453: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9454: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9455: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9456: 			    }
1.599     albertel 9457: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9458: 				$metaentry{':'.$unikey}=
                   9459: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9460: 			    }
1.339     albertel 9461: 			}
                   9462: 		    }
                   9463: 		} else {
1.172     www      9464: #
                   9465: # This is not a package - some other kind of start tag
1.339     albertel 9466: #
                   9467: 		    my $entry=$token->[1];
1.1068    www      9468: 		    my $unikey='';
1.175     www      9469: 
1.339     albertel 9470: 		    if ($entry eq 'import') {
1.175     www      9471: #
                   9472: # Importing a library here
1.339     albertel 9473: #
1.1067    www      9474:                         my $location=$parser->get_text('/import');
                   9475:                         my $dir=$filename;
                   9476:                         $dir=~s|[^/]*$||;
                   9477:                         $location=&filelocation($dir,$location);
1.1069    www      9478:                        
1.1068    www      9479:                         my $importmode=$token->[2]->{'importmode'};
                   9480:                         if ($importmode eq 'problem') {
1.1069    www      9481: # Import as problem/response
1.1068    www      9482:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9483:                         } elsif ($importmode eq 'part') {
                   9484: # Import as part(s)
1.1069    www      9485:                            $importedparts=1;
                   9486: # We need to get the original file and the imported file to get the part order correct
                   9487: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9488: # Load and inspect original file
1.1070    www      9489:                            if ($#origfileimportpartids<0) {
                   9490:                               undef(%importedpartids);
                   9491:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9492:                               my $origfile=&getfile($origfilelocation);
                   9493:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9494:                            }
                   9495: 
1.1069    www      9496: # Load and inspect imported file
                   9497:                            my $impfile=&getfile($location);
                   9498:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9499:                            if ($#impfilepartids>=0) {
                   9500: # This problem had parts
1.1070    www      9501:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9502:                            } else {
                   9503: # Importing by turning a single problem into a problem part
                   9504: # It gets the import-tags ID as part-ID
                   9505:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9506:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9507:                            }
1.1068    www      9508:                         } else {
                   9509: # Normal import
                   9510:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9511:                            if (defined($token->[2]->{'id'})) {
                   9512:                               $unikey.='_'.$token->[2]->{'id'};
                   9513:                            }
1.1067    www      9514:                         }
                   9515: 
1.339     albertel 9516: 			if ($depthcount<20) {
1.736     albertel 9517: 			    my $metadata = 
                   9518: 				&metadata($uri,'keys', $location,$unikey,
                   9519: 					  $depthcount+1);
                   9520: 			    foreach my $meta (split(',',$metadata)) {
                   9521: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9522: 				$metathesekeys{$meta}=1;
1.339     albertel 9523: 			    }
1.1068    www      9524: 			
                   9525:                         }
1.1067    www      9526: 		    } else {
                   9527: #
                   9528: # Not importing, some other kind of non-package, non-library start tag
                   9529: # 
                   9530:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9531:                         if (defined($token->[2]->{'id'})) {
                   9532:                             $unikey.='_'.$token->[2]->{'id'};
                   9533:                         }
1.339     albertel 9534: 			if (defined($token->[2]->{'name'})) { 
                   9535: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9536: 			}
                   9537: 			$metathesekeys{$unikey}=1;
1.736     albertel 9538: 			foreach my $param (@{$token->[3]}) {
                   9539: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9540: 				$token->[2]->{$param};
1.339     albertel 9541: 			}
                   9542: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9543: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9544: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9545: 		 # only ws inside the tag, and not in default, so use default
                   9546: 		 # as value
1.599     albertel 9547: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9548: 			} elsif ( $internaltext =~ /\S/ ) {
                   9549: 		  # something interesting inside the tag
                   9550: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9551: 			} else {
1.908     albertel 9552: 		  # no interesting values, don't set a default
1.339     albertel 9553: 			}
1.172     www      9554: # end of not-a-package not-a-library import
1.339     albertel 9555: 		    }
1.172     www      9556: # end of not-a-package start tag
1.339     albertel 9557: 		}
1.172     www      9558: # the next is the end of "start tag"
1.339     albertel 9559: 	    }
                   9560: 	}
1.483     albertel 9561: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9562: 	$extension = lc($extension);
                   9563: 	if ($extension eq 'htm') { $extension='html'; }
                   9564: 
1.737     albertel 9565: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9566: 	    #no specific packages #how's our extension
                   9567: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9568: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9569: 					 \%metathesekeys);
                   9570: 	}
1.883     albertel 9571: 
                   9572: 	if (!exists($metaentry{':packages'})
                   9573: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9574: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9575: 		#no specific packages well let's get default then
                   9576: 		if ($key!~/^default&/) { next; }
1.488     albertel 9577: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9578: 					     \%metathesekeys);
                   9579: 	    }
                   9580: 	}
1.338     www      9581: # are there custom rights to evaluate
1.599     albertel 9582: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9583: 
1.338     www      9584:     #
                   9585:     # Importing a rights file here
1.339     albertel 9586:     #
                   9587: 	    unless ($depthcount) {
1.599     albertel 9588: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9589: 		my $dir=$filename;
                   9590: 		$dir=~s|[^/]*$||;
                   9591: 		$location=&filelocation($dir,$location);
1.736     albertel 9592: 		my $rights_metadata =
                   9593: 		    &metadata($uri,'keys',$location,'_rights',
                   9594: 			      $depthcount+1);
                   9595: 		foreach my $rights (split(',',$rights_metadata)) {
                   9596: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9597: 		    $metathesekeys{$rights}=1;
1.339     albertel 9598: 		}
                   9599: 	    }
                   9600: 	}
1.737     albertel 9601: 	# uniqifiy package listing
                   9602: 	my %seen;
                   9603: 	my @uniq_packages =
                   9604: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9605: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9606: 
1.1070    www      9607:         if ($importedparts) {
                   9608: # We had imported parts and need to rebuild partorder
                   9609:            $metaentry{':partorder'}='';
                   9610:            $metathesekeys{'partorder'}=1;
                   9611:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9612:                if ($origfileimportpartids[$index] eq 'part') {
                   9613: # original part, part of the problem
                   9614:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9615:                } else {
                   9616: # we have imported parts at this position
                   9617:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9618:                }
                   9619:            }
                   9620:            $metaentry{':partorder'}=~s/^\,//;
                   9621:         }
                   9622: 
1.737     albertel 9623: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9624: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9625: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9626: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9627: # this is the end of "was not already recently cached
1.71      www      9628:     }
1.599     albertel 9629:     return $metaentry{':'.$what};
1.261     albertel 9630: }
                   9631: 
1.488     albertel 9632: sub metadata_create_package_def {
1.483     albertel 9633:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9634:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9635:     if ($subp eq 'default') { next; }
                   9636:     
1.599     albertel 9637:     if (defined($metaentry{':packages'})) {
                   9638: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9639:     } else {
1.599     albertel 9640: 	$metaentry{':packages'}=$package;
1.483     albertel 9641:     }
                   9642:     my $value=$packagetab{$key};
                   9643:     my $unikey;
                   9644:     $unikey='parameter_0_'.$name;
1.599     albertel 9645:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9646:     $$metathesekeys{$unikey}=1;
1.599     albertel 9647:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9648: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9649:     }
1.599     albertel 9650:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9651: 	$metaentry{':'.$unikey}=
                   9652: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9653:     }
                   9654: }
                   9655: 
1.261     albertel 9656: sub metadata_generate_part0 {
                   9657:     my ($metadata,$metacache,$uri) = @_;
                   9658:     my %allnames;
1.737     albertel 9659:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9660: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9661: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9662: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9663: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9664: 	    $allnames{$name}=$part;
                   9665: 	  }
                   9666: 	}
                   9667:     }
                   9668:     foreach my $name (keys(%allnames)) {
                   9669:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9670:       my $key=":parameter_0_$name";
1.261     albertel 9671:       $$metacache{"$key.part"}='0';
                   9672:       $$metacache{"$key.name"}=$name;
1.428     albertel 9673:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9674: 					   $allnames{$name}.'_'.$name.
                   9675: 					   '.type'};
1.428     albertel 9676:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9677: 			     '.display'};
1.644     www      9678:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9679:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9680:       $$metacache{"$key.display"}=$olddis;
                   9681:     }
1.71      www      9682: }
                   9683: 
1.764     albertel 9684: # ------------------------------------------------------ Devalidate title cache
                   9685: 
                   9686: sub devalidate_title_cache {
                   9687:     my ($url)=@_;
                   9688:     if (!$env{'request.course.id'}) { return; }
                   9689:     my $symb=&symbread($url);
                   9690:     if (!$symb) { return; }
                   9691:     my $key=$env{'request.course.id'}."\0".$symb;
                   9692:     &devalidate_cache_new('title',$key);
                   9693: }
                   9694: 
1.1014    droeschl 9695: # ------------------------------------------------- Get the title of a course
                   9696: 
                   9697: sub current_course_title {
                   9698:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9699: }
1.301     www      9700: # ------------------------------------------------- Get the title of a resource
                   9701: 
                   9702: sub gettitle {
                   9703:     my $urlsymb=shift;
                   9704:     my $symb=&symbread($urlsymb);
1.534     albertel 9705:     if ($symb) {
1.620     albertel 9706: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9707: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9708: 	if (defined($cached)) { 
                   9709: 	    return $result;
                   9710: 	}
1.534     albertel 9711: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9712: 	my $title='';
1.907     albertel 9713: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9714: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9715: 	} else {
                   9716: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9717: 		    &GDBM_READER(),0640)) {
                   9718: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9719: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9720: 		untie(%bighash);
                   9721: 	    }
1.534     albertel 9722: 	}
                   9723: 	$title=~s/\&colon\;/\:/gs;
                   9724: 	if ($title) {
1.1159    www      9725: # Remember both $symb and $title for dynamic metadata
                   9726:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9727:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9728: # Cache this title and then return it
1.599     albertel 9729: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9730: 	}
                   9731: 	$urlsymb=$url;
                   9732:     }
                   9733:     my $title=&metadata($urlsymb,'title');
                   9734:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9735:     return $title;
1.301     www      9736: }
1.613     albertel 9737: 
1.614     albertel 9738: sub get_slot {
                   9739:     my ($which,$cnum,$cdom)=@_;
                   9740:     if (!$cnum || !$cdom) {
1.790     albertel 9741: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9742: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9743: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9744:     }
1.703     albertel 9745:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9746:     my %slotinfo;
                   9747:     if (exists($remembered{$key})) {
                   9748: 	$slotinfo{$which} = $remembered{$key};
                   9749:     } else {
                   9750: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9751: 	&Apache::lonhomework::showhash(%slotinfo);
                   9752: 	my ($tmp)=keys(%slotinfo);
                   9753: 	if ($tmp=~/^error:/) { return (); }
                   9754: 	$remembered{$key} = $slotinfo{$which};
                   9755:     }
1.616     albertel 9756:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9757: 	return %{$slotinfo{$which}};
                   9758:     }
                   9759:     return $slotinfo{$which};
1.614     albertel 9760: }
1.1150    raeburn  9761: 
                   9762: sub get_reservable_slots {
                   9763:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9764:     my $now = time;
                   9765:     my $reservable_info;
                   9766:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9767:     if (exists($remembered{$key})) {
                   9768:         $reservable_info = $remembered{$key};
                   9769:     } else {
                   9770:         my %resv;
                   9771:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9772:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9773:         $reservable_info = \%resv;
                   9774:         $remembered{$key} = $reservable_info;
                   9775:     }
                   9776:     return $reservable_info;
                   9777: }
                   9778: 
                   9779: sub get_course_slots {
                   9780:     my ($cnum,$cdom) = @_;
                   9781:     my $hashid=$cnum.':'.$cdom;
                   9782:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9783:     if (defined($cached)) {
                   9784:         if (ref($result) eq 'HASH') {
                   9785:             return %{$result};
                   9786:         }
                   9787:     } else {
                   9788:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9789:         my ($tmp) = keys(%slots);
                   9790:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9791:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9792:             return %slots;
                   9793:         }
                   9794:     }
                   9795:     return;
                   9796: }
                   9797: 
                   9798: sub devalidate_slots_cache {
                   9799:     my ($cnum,$cdom)=@_;
                   9800:     my $hashid=$cnum.':'.$cdom;
                   9801:     &devalidate_cache_new('allslots',$hashid);
                   9802: }
                   9803: 
1.31      www      9804: # ------------------------------------------------- Update symbolic store links
                   9805: 
                   9806: sub symblist {
                   9807:     my ($mapname,%newhash)=@_;
1.438     www      9808:     $mapname=&deversion(&declutter($mapname));
1.31      www      9809:     my %hash;
1.620     albertel 9810:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9811:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9812:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9813: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9814: 		next if ($url eq 'last_known'
                   9815: 			 && $env{'form.no_update_last_known'});
                   9816: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9817: 						    $newhash{$url}->[1],
                   9818: 						    $newhash{$url}->[0]);
1.191     harris41 9819:             }
1.31      www      9820:             if (untie(%hash)) {
                   9821: 		return 'ok';
                   9822:             }
                   9823:         }
                   9824:     }
                   9825:     return 'error';
1.212     www      9826: }
                   9827: 
                   9828: # --------------------------------------------------------------- Verify a symb
                   9829: 
                   9830: sub symbverify {
1.510     www      9831:     my ($symb,$thisurl)=@_;
                   9832:     my $thisfn=$thisurl;
1.439     www      9833:     $thisfn=&declutter($thisfn);
1.215     www      9834: # direct jump to resource in page or to a sequence - will construct own symbs
                   9835:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9836: # check URL part
1.409     www      9837:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9838: 
1.431     www      9839:     unless ($url eq $thisfn) { return 0; }
1.213     www      9840: 
1.216     www      9841:     $symb=&symbclean($symb);
1.510     www      9842:     $thisurl=&deversion($thisurl);
1.439     www      9843:     $thisfn=&deversion($thisfn);
1.213     www      9844: 
                   9845:     my %bighash;
                   9846:     my $okay=0;
1.431     www      9847: 
1.620     albertel 9848:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9849:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9850:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9851:             $thisurl =~ s/\?.+$//;
                   9852:         }
1.510     www      9853:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9854:         unless ($ids) {
                   9855:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9856:             $ids=$bighash{$idkey};
1.216     www      9857:         }
                   9858:         if ($ids) {
                   9859: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9860: 	    foreach my $id (split(/\,/,$ids)) {
                   9861: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9862:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9863:                    $symb =~ s/\?.+$//;
                   9864:                }
1.216     www      9865:                if (
                   9866:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9867:    eq $symb) { 
1.620     albertel 9868: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9869: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9870:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9871: 		       $okay=1; 
                   9872: 		   }
                   9873: 	       }
1.216     www      9874: 	   }
                   9875:         }
1.213     www      9876: 	untie(%bighash);
                   9877:     }
                   9878:     return $okay;
1.31      www      9879: }
                   9880: 
1.210     www      9881: # --------------------------------------------------------------- Clean-up symb
                   9882: 
                   9883: sub symbclean {
                   9884:     my $symb=shift;
1.568     albertel 9885:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9886: # remove version from map
                   9887:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9888: 
1.210     www      9889: # remove version from URL
                   9890:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9891: 
1.507     www      9892: # remove wrapper
                   9893: 
1.510     www      9894:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9895:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9896:     return $symb;
1.409     www      9897: }
                   9898: 
                   9899: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9900: 
                   9901: sub encode_symb {
                   9902:     my ($map,$resid,$url)=@_;
                   9903:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9904: }
1.409     www      9905: 
                   9906: sub decode_symb {
1.568     albertel 9907:     my $symb=shift;
                   9908:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9909:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9910:     return (&fixversion($map),$resid,&fixversion($url));
                   9911: }
                   9912: 
                   9913: sub fixversion {
                   9914:     my $fn=shift;
1.609     banghart 9915:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9916:     my %bighash;
                   9917:     my $uri=&clutter($fn);
1.620     albertel 9918:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9919: # is this cached?
1.599     albertel 9920:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9921:     if (defined($cached)) { return $result; }
                   9922: # unfortunately not cached, or expired
1.620     albertel 9923:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9924: 	    &GDBM_READER(),0640)) {
                   9925:  	if ($bighash{'version_'.$uri}) {
                   9926:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9927:  	    unless (($version eq 'mostrecent') || 
                   9928: 		    ($version==&getversion($uri))) {
1.440     www      9929:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9930:  	    }
                   9931:  	}
                   9932:  	untie %bighash;
1.413     www      9933:     }
1.599     albertel 9934:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9935: }
                   9936: 
                   9937: sub deversion {
                   9938:     my $url=shift;
                   9939:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9940:     return $url;
1.210     www      9941: }
                   9942: 
1.31      www      9943: # ------------------------------------------------------ Return symb list entry
                   9944: 
                   9945: sub symbread {
1.249     www      9946:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9947:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9948:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9949: # no filename provided? try from environment
1.44      www      9950:     unless ($thisfn) {
1.620     albertel 9951:         if ($env{'request.symb'}) {
                   9952: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9953: 	}
1.620     albertel 9954: 	$thisfn=$env{'request.filename'};
1.44      www      9955:     }
1.569     albertel 9956:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9957: # is that filename actually a symb? Verify, clean, and return
                   9958:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9959: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9960: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9961: 	}
1.242     www      9962:     }
1.44      www      9963:     $thisfn=declutter($thisfn);
1.31      www      9964:     my %hash;
1.37      www      9965:     my %bighash;
                   9966:     my $syval='';
1.620     albertel 9967:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9968:         my $targetfn = $thisfn;
1.609     banghart 9969:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9970:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9971:         }
1.687     albertel 9972: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9973: 	    $targetfn=$1;
                   9974: 	}
1.620     albertel 9975:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9976:                       &GDBM_READER(),0640)) {
1.481     raeburn  9977: 	    $syval=$hash{$targetfn};
1.37      www      9978:             untie(%hash);
                   9979:         }
                   9980: # ---------------------------------------------------------- There was an entry
                   9981:         if ($syval) {
1.601     albertel 9982: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9983: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9984: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9985: 		    #return $env{$cache_str}='';
1.601     albertel 9986: 		#}    
                   9987: 		#$syval.=$1;
                   9988: 	    #}
1.37      www      9989:         } else {
                   9990: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9991:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9992:                             &GDBM_READER(),0640)) {
1.37      www      9993: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9994:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9995:               unless ($ids) { 
                   9996:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9997:               }
                   9998:               unless ($ids) {
                   9999: # alias?
                   10000: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10001:               }
1.37      www      10002:               if ($ids) {
                   10003: # ------------------------------------------------------------------- Has ID(s)
                   10004:                  my @possibilities=split(/\,/,$ids);
1.39      www      10005:                  if ($#possibilities==0) {
                   10006: # ----------------------------------------------- There is only one possibility
1.37      www      10007: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10008: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10009: 						    $resid,$thisfn);
1.249     www      10010:                  } elsif (!$donotrecurse) {
1.39      www      10011: # ------------------------------------------ There is more than one possibility
                   10012:                      my $realpossible=0;
1.800     albertel 10013:                      foreach my $id (@possibilities) {
                   10014: 			 my $file=$bighash{'src_'.$id};
1.39      www      10015:                          if (&allowed('bre',$file)) {
1.800     albertel 10016:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10017:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10018: 				$realpossible++;
1.626     albertel 10019:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10020: 						    $resid,$thisfn);
1.39      www      10021:                             }
                   10022: 			 }
1.191     harris41 10023:                      }
1.39      www      10024: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10025:                  } else {
                   10026:                      $syval='';
1.37      www      10027:                  }
                   10028: 	      }
                   10029:               untie(%bighash)
1.481     raeburn  10030:            }
1.31      www      10031:         }
1.62      www      10032:         if ($syval) {
1.620     albertel 10033: 	    return $env{$cache_str}=$syval;
1.62      www      10034:         }
1.31      www      10035:     }
1.949     raeburn  10036:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10037:     return $env{$cache_str}='';
1.31      www      10038: }
                   10039: 
                   10040: # ---------------------------------------------------------- Return random seed
                   10041: 
1.32      www      10042: sub numval {
                   10043:     my $txt=shift;
                   10044:     $txt=~tr/A-J/0-9/;
                   10045:     $txt=~tr/a-j/0-9/;
                   10046:     $txt=~tr/K-T/0-9/;
                   10047:     $txt=~tr/k-t/0-9/;
                   10048:     $txt=~tr/U-Z/0-5/;
                   10049:     $txt=~tr/u-z/0-5/;
                   10050:     $txt=~s/\D//g;
1.564     albertel 10051:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10052:     return int($txt);
1.368     albertel 10053: }
                   10054: 
1.484     albertel 10055: sub numval2 {
                   10056:     my $txt=shift;
                   10057:     $txt=~tr/A-J/0-9/;
                   10058:     $txt=~tr/a-j/0-9/;
                   10059:     $txt=~tr/K-T/0-9/;
                   10060:     $txt=~tr/k-t/0-9/;
                   10061:     $txt=~tr/U-Z/0-5/;
                   10062:     $txt=~tr/u-z/0-5/;
                   10063:     $txt=~s/\D//g;
                   10064:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10065:     my $total;
                   10066:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10067:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10068:     return int($total);
                   10069: }
                   10070: 
1.575     albertel 10071: sub numval3 {
                   10072:     use integer;
                   10073:     my $txt=shift;
                   10074:     $txt=~tr/A-J/0-9/;
                   10075:     $txt=~tr/a-j/0-9/;
                   10076:     $txt=~tr/K-T/0-9/;
                   10077:     $txt=~tr/k-t/0-9/;
                   10078:     $txt=~tr/U-Z/0-5/;
                   10079:     $txt=~tr/u-z/0-5/;
                   10080:     $txt=~s/\D//g;
                   10081:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10082:     my $total;
                   10083:     foreach my $val (@txts) { $total+=$val; }
                   10084:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10085:     return $total;
                   10086: }
                   10087: 
1.675     albertel 10088: sub digest {
                   10089:     my ($data)=@_;
                   10090:     my $digest=&Digest::MD5::md5($data);
                   10091:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10092:     my ($e,$f);
                   10093:     {
                   10094:         use integer;
                   10095:         $e=($a+$b);
                   10096:         $f=($c+$d);
                   10097:         if ($_64bit) {
                   10098:             $e=(($e<<32)>>32);
                   10099:             $f=(($f<<32)>>32);
                   10100:         }
                   10101:     }
                   10102:     if (wantarray) {
                   10103: 	return ($e,$f);
                   10104:     } else {
                   10105: 	my $g;
                   10106: 	{
                   10107: 	    use integer;
                   10108: 	    $g=($e+$f);
                   10109: 	    if ($_64bit) {
                   10110: 		$g=(($g<<32)>>32);
                   10111: 	    }
                   10112: 	}
                   10113: 	return $g;
                   10114:     }
                   10115: }
                   10116: 
1.368     albertel 10117: sub latest_rnd_algorithm_id {
1.675     albertel 10118:     return '64bit5';
1.366     albertel 10119: }
1.32      www      10120: 
1.503     albertel 10121: sub get_rand_alg {
                   10122:     my ($courseid)=@_;
1.790     albertel 10123:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10124:     if ($courseid) {
1.620     albertel 10125: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10126:     }
                   10127:     return &latest_rnd_algorithm_id();
                   10128: }
                   10129: 
1.562     albertel 10130: sub validCODE {
                   10131:     my ($CODE)=@_;
                   10132:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10133:     return 0;
                   10134: }
                   10135: 
1.491     albertel 10136: sub getCODE {
1.620     albertel 10137:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10138:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10139: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10140: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10141: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10142:     }
                   10143:     return undef;
                   10144: }
1.1133    foxr     10145: #
                   10146: #  Determines the random seed for a specific context:
                   10147: #
                   10148: # parameters:
                   10149: #   symb      - in course context the symb for the seed.
                   10150: #   course_id - The course id of the form domain_coursenum.
                   10151: #   domain    - Domain for the user.
                   10152: #   course    - Course for the user.
                   10153: #   cenv      - environment of the course.
                   10154: #
                   10155: # NOTE:
                   10156: #   All parameters are picked out of the environment if missing
                   10157: #   or not defined.
                   10158: #   If a symb cannot be determined the current time is used instead.
                   10159: #
                   10160: #  For a given well defined symb, courside, domain, username,
                   10161: #  and course environment, the seed is reproducible.
                   10162: #
1.31      www      10163: sub rndseed {
1.1133    foxr     10164:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10165:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10166:     if (!defined($symb)) {
1.366     albertel 10167: 	unless ($symb=$wsymb) { return time; }
                   10168:     }
1.1146    foxr     10169:     if (!defined $courseid) { 
                   10170: 	$courseid=$wcourseid; 
                   10171:     }
                   10172:     if (!defined $domain) { $domain=$wdomain; }
                   10173:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10174: 
                   10175:     my $which;
                   10176:     if (defined($cenv->{'rndseed'})) {
                   10177: 	$which = $cenv->{'rndseed'};
                   10178:     } else {
                   10179: 	$which =&get_rand_alg($courseid);
                   10180:     }
1.491     albertel 10181:     if (defined(&getCODE())) {
1.1133    foxr     10182: 
1.675     albertel 10183: 	if ($which eq '64bit5') {
                   10184: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10185: 	} elsif ($which eq '64bit4') {
1.575     albertel 10186: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10187: 	} else {
                   10188: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10189: 	}
1.675     albertel 10190:     } elsif ($which eq '64bit5') {
                   10191: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10192:     } elsif ($which eq '64bit4') {
                   10193: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10194:     } elsif ($which eq '64bit3') {
                   10195: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10196:     } elsif ($which eq '64bit2') {
                   10197: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10198:     } elsif ($which eq '64bit') {
                   10199: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10200:     }
                   10201:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10202: }
                   10203: 
                   10204: sub rndseed_32bit {
                   10205:     my ($symb,$courseid,$domain,$username)=@_;
                   10206:     {
                   10207: 	use integer;
                   10208: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10209: 	my $symbseed=numval($symb) << 22;
                   10210: 	my $namechck=unpack("%32C*",$username) << 17;
                   10211: 	my $nameseed=numval($username) << 12;
                   10212: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10213: 	my $courseseed=unpack("%32C*",$courseid);
                   10214: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10215: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10216: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10217: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10218: 	return $num;
                   10219:     }
                   10220: }
                   10221: 
                   10222: sub rndseed_64bit {
                   10223:     my ($symb,$courseid,$domain,$username)=@_;
                   10224:     {
                   10225: 	use integer;
                   10226: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10227: 	my $symbseed=numval($symb) << 10;
                   10228: 	my $namechck=unpack("%32S*",$username);
                   10229: 	
                   10230: 	my $nameseed=numval($username) << 21;
                   10231: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10232: 	my $courseseed=unpack("%32S*",$courseid);
                   10233: 	
                   10234: 	my $num1=$symbchck+$symbseed+$namechck;
                   10235: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10236: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10237: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10238: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10239: 	return "$num1,$num2";
1.155     albertel 10240:     }
1.366     albertel 10241: }
                   10242: 
1.443     albertel 10243: sub rndseed_64bit2 {
                   10244:     my ($symb,$courseid,$domain,$username)=@_;
                   10245:     {
                   10246: 	use integer;
                   10247: 	# strings need to be an even # of cahracters long, it it is odd the
                   10248:         # last characters gets thrown away
                   10249: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10250: 	my $symbseed=numval($symb) << 10;
                   10251: 	my $namechck=unpack("%32S*",$username.' ');
                   10252: 	
                   10253: 	my $nameseed=numval($username) << 21;
1.501     albertel 10254: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10255: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10256: 	
                   10257: 	my $num1=$symbchck+$symbseed+$namechck;
                   10258: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10259: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10260: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10261: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10262: 	return "$num1,$num2";
                   10263:     }
                   10264: }
                   10265: 
                   10266: sub rndseed_64bit3 {
                   10267:     my ($symb,$courseid,$domain,$username)=@_;
                   10268:     {
                   10269: 	use integer;
                   10270: 	# strings need to be an even # of cahracters long, it it is odd the
                   10271:         # last characters gets thrown away
                   10272: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10273: 	my $symbseed=numval2($symb) << 10;
                   10274: 	my $namechck=unpack("%32S*",$username.' ');
                   10275: 	
                   10276: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10277: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10278: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10279: 	
                   10280: 	my $num1=$symbchck+$symbseed+$namechck;
                   10281: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10282: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10283: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10284: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10285: 	
1.503     albertel 10286: 	return "$num1:$num2";
1.443     albertel 10287:     }
                   10288: }
                   10289: 
1.575     albertel 10290: sub rndseed_64bit4 {
                   10291:     my ($symb,$courseid,$domain,$username)=@_;
                   10292:     {
                   10293: 	use integer;
                   10294: 	# strings need to be an even # of cahracters long, it it is odd the
                   10295:         # last characters gets thrown away
                   10296: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10297: 	my $symbseed=numval3($symb) << 10;
                   10298: 	my $namechck=unpack("%32S*",$username.' ');
                   10299: 	
                   10300: 	my $nameseed=numval3($username) << 21;
                   10301: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10302: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10303: 	
                   10304: 	my $num1=$symbchck+$symbseed+$namechck;
                   10305: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10306: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10307: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10308: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10309: 	
1.575     albertel 10310: 	return "$num1:$num2";
                   10311:     }
                   10312: }
                   10313: 
1.675     albertel 10314: sub rndseed_64bit5 {
                   10315:     my ($symb,$courseid,$domain,$username)=@_;
                   10316:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10317:     return "$num1:$num2";
                   10318: }
                   10319: 
1.366     albertel 10320: sub rndseed_CODE_64bit {
                   10321:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10322:     {
1.366     albertel 10323: 	use integer;
1.443     albertel 10324: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10325: 	my $symbseed=numval2($symb);
1.491     albertel 10326: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10327: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10328: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10329: 	my $num1=$symbseed+$CODEchck;
                   10330: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10331: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10332: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10333: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10334: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10335: 	return "$num1:$num2";
1.366     albertel 10336:     }
                   10337: }
                   10338: 
1.575     albertel 10339: sub rndseed_CODE_64bit4 {
                   10340:     my ($symb,$courseid,$domain,$username)=@_;
                   10341:     {
                   10342: 	use integer;
                   10343: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10344: 	my $symbseed=numval3($symb);
                   10345: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10346: 	my $CODEseed=numval3(&getCODE());
                   10347: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10348: 	my $num1=$symbseed+$CODEchck;
                   10349: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10350: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10351: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10352: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10353: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10354: 	return "$num1:$num2";
                   10355:     }
                   10356: }
                   10357: 
1.675     albertel 10358: sub rndseed_CODE_64bit5 {
                   10359:     my ($symb,$courseid,$domain,$username)=@_;
                   10360:     my $code = &getCODE();
                   10361:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10362:     return "$num1:$num2";
                   10363: }
                   10364: 
1.366     albertel 10365: sub setup_random_from_rndseed {
                   10366:     my ($rndseed)=@_;
1.503     albertel 10367:     if ($rndseed =~/([,:])/) {
                   10368: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10369: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10370:     } else {
                   10371: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10372:     }
1.36      albertel 10373: }
                   10374: 
1.474     albertel 10375: sub latest_receipt_algorithm_id {
1.835     albertel 10376:     return 'receipt3';
1.474     albertel 10377: }
                   10378: 
1.480     www      10379: sub recunique {
                   10380:     my $fucourseid=shift;
                   10381:     my $unique;
1.835     albertel 10382:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10383: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10384: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10385:     } else {
                   10386: 	$unique=$perlvar{'lonReceipt'};
                   10387:     }
                   10388:     return unpack("%32C*",$unique);
                   10389: }
                   10390: 
                   10391: sub recprefix {
                   10392:     my $fucourseid=shift;
                   10393:     my $prefix;
1.835     albertel 10394:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10395: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10396: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10397:     } else {
                   10398: 	$prefix=$perlvar{'lonHostID'};
                   10399:     }
                   10400:     return unpack("%32C*",$prefix);
                   10401: }
                   10402: 
1.76      www      10403: sub ireceipt {
1.474     albertel 10404:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10405: 
                   10406:     my $return =&recprefix($fucourseid).'-';
                   10407: 
                   10408:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10409: 	$env{'request.state'} eq 'construct') {
                   10410: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10411: 	return $return;
                   10412:     }
                   10413: 
1.76      www      10414:     my $cuname=unpack("%32C*",$funame);
                   10415:     my $cudom=unpack("%32C*",$fudom);
                   10416:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10417:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10418:     my $cunique=&recunique($fucourseid);
1.474     albertel 10419:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10420:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10421: 
1.790     albertel 10422: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10423: 			       
                   10424: 	$return.= ($cunique%$cuname+
                   10425: 		   $cunique%$cudom+
                   10426: 		   $cusymb%$cuname+
                   10427: 		   $cusymb%$cudom+
                   10428: 		   $cucourseid%$cuname+
                   10429: 		   $cucourseid%$cudom+
                   10430: 		   $cpart%$cuname+
                   10431: 		   $cpart%$cudom);
                   10432:     } else {
                   10433: 	$return.= ($cunique%$cuname+
                   10434: 		   $cunique%$cudom+
                   10435: 		   $cusymb%$cuname+
                   10436: 		   $cusymb%$cudom+
                   10437: 		   $cucourseid%$cuname+
                   10438: 		   $cucourseid%$cudom);
                   10439:     }
                   10440:     return $return;
1.76      www      10441: }
                   10442: 
                   10443: sub receipt {
1.474     albertel 10444:     my ($part)=@_;
1.790     albertel 10445:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10446:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10447: }
1.260     ng       10448: 
1.790     albertel 10449: sub whichuser {
                   10450:     my ($passedsymb)=@_;
                   10451:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10452:     if (defined($env{'form.grade_symb'})) {
                   10453: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10454: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10455: 	if (!$allowed &&
                   10456: 	    exists($env{'request.course.sec'}) &&
                   10457: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10458: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10459: 			      '/'.$env{'request.course.sec'});
                   10460: 	}
                   10461: 	if ($allowed) {
                   10462: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10463: 	    $courseid=$tmp_courseid;
                   10464: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10465: 	    ($name)=&get_env_multiple('form.grade_username');
                   10466: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10467: 	}
                   10468:     }
                   10469:     if (!$passedsymb) {
                   10470: 	$symb=&symbread();
                   10471:     } else {
                   10472: 	$symb=$passedsymb;
                   10473:     }
                   10474:     $courseid=$env{'request.course.id'};
                   10475:     $domain=$env{'user.domain'};
                   10476:     $name=$env{'user.name'};
                   10477:     if ($name eq 'public' && $domain eq 'public') {
                   10478: 	if (!defined($env{'form.username'})) {
                   10479: 	    $env{'form.username'}.=time.rand(10000000);
                   10480: 	}
                   10481: 	$name.=$env{'form.username'};
                   10482:     }
                   10483:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10484: 
                   10485: }
                   10486: 
1.36      albertel 10487: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10488: # returns either the contents of the file or 
                   10489: # -1 if the file doesn't exist
1.481     raeburn  10490: #
                   10491: # if the target is a file that was uploaded via DOCS, 
                   10492: # a check will be made to see if a current copy exists on the local server,
                   10493: # if it does this will be served, otherwise a copy will be retrieved from
                   10494: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10495: # the local server.   
1.472     albertel 10496: 
1.36      albertel 10497: sub getfile {
1.538     albertel 10498:     my ($file) = @_;
1.609     banghart 10499:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10500:     &repcopy($file);
                   10501:     return &readfile($file);
                   10502: }
                   10503: 
                   10504: sub repcopy_userfile {
                   10505:     my ($file)=@_;
1.1142    raeburn  10506:     my $londocroot = $perlvar{'lonDocRoot'};
                   10507:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10508:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10509:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10510: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10511:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10512:     if (-e "$file") {
1.828     www      10513: # we already have a local copy, check it out
1.538     albertel 10514: 	my @fileinfo = stat($file);
1.828     www      10515: 	my $rtncode;
                   10516: 	my $info;
1.538     albertel 10517: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10518: 	if ($lwpresp ne 'ok') {
1.828     www      10519: # there is no such file anymore, even though we had a local copy
1.482     albertel 10520: 	    if ($rtncode eq '404') {
1.538     albertel 10521: 		unlink($file);
1.482     albertel 10522: 	    }
                   10523: 	    return -1;
                   10524: 	}
                   10525: 	if ($info < $fileinfo[9]) {
1.828     www      10526: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10527: 	    return 'ok';
1.828     www      10528: 	} else {
                   10529: # the file is outdated, get rid of it
                   10530: 	    unlink($file);
1.482     albertel 10531: 	}
1.828     www      10532:     }
                   10533: # one way or the other, at this point, we don't have the file
                   10534: # construct the correct path for the file
                   10535:     my @parts = ($cdom,$cnum); 
                   10536:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10537: 	push @parts, split(/\//,$1);
                   10538:     }
                   10539:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10540:     foreach my $part (@parts) {
                   10541: 	$path .= '/'.$part;
                   10542: 	if (!-e $path) {
                   10543: 	    mkdir($path,0770);
1.482     albertel 10544: 	}
                   10545:     }
1.828     www      10546: # now the path exists for sure
                   10547: # get a user agent
                   10548:     my $ua=new LWP::UserAgent;
                   10549:     my $transferfile=$file.'.in.transfer';
                   10550: # FIXME: this should flock
                   10551:     if (-e $transferfile) { return 'ok'; }
                   10552:     my $request;
                   10553:     $uri=~s/^\///;
1.980     raeburn  10554:     my $homeserver = &homeserver($cnum,$cdom);
                   10555:     my $protocol = $protocol{$homeserver};
                   10556:     $protocol = 'http' if ($protocol ne 'https');
                   10557:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10558:     my $response=$ua->request($request,$transferfile);
                   10559: # did it work?
                   10560:     if ($response->is_error()) {
                   10561: 	unlink($transferfile);
                   10562: 	&logthis("Userfile repcopy failed for $uri");
                   10563: 	return -1;
                   10564:     }
                   10565: # worked, rename the transfer file
                   10566:     rename($transferfile,$file);
1.607     raeburn  10567:     return 'ok';
1.481     raeburn  10568: }
                   10569: 
1.517     albertel 10570: sub tokenwrapper {
                   10571:     my $uri=shift;
1.980     raeburn  10572:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10573:     $uri=~s|^/||;
1.620     albertel 10574:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10575:     my $token=$1;
1.552     albertel 10576:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10577:     if ($udom && $uname && $file) {
                   10578: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10579:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10580:         my $homeserver = &homeserver($uname,$udom);
                   10581:         my $protocol = $protocol{$homeserver};
                   10582:         $protocol = 'http' if ($protocol ne 'https');
                   10583:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10584:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10585:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10586:     } else {
                   10587:         return '/adm/notfound.html';
                   10588:     }
                   10589: }
                   10590: 
1.828     www      10591: # call with reqtype HEAD: get last modification time
                   10592: # call with reqtype GET: get the file contents
                   10593: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10594: #
1.481     raeburn  10595: sub getuploaded {
                   10596:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10597:     $uri=~s/^\///;
1.980     raeburn  10598:     my $homeserver = &homeserver($cnum,$cdom);
                   10599:     my $protocol = $protocol{$homeserver};
                   10600:     $protocol = 'http' if ($protocol ne 'https');
                   10601:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10602:     my $ua=new LWP::UserAgent;
                   10603:     my $request=new HTTP::Request($reqtype,$uri);
                   10604:     my $response=$ua->request($request);
                   10605:     $$rtncode = $response->code;
1.482     albertel 10606:     if (! $response->is_success()) {
                   10607: 	return 'failed';
                   10608:     }      
                   10609:     if ($reqtype eq 'HEAD') {
1.486     www      10610: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10611:     } elsif ($reqtype eq 'GET') {
                   10612: 	$$info = $response->content;
1.472     albertel 10613:     }
1.482     albertel 10614:     return 'ok';
1.36      albertel 10615: }
                   10616: 
1.481     raeburn  10617: sub readfile {
                   10618:     my $file = shift;
                   10619:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10620:     my $fh;
                   10621:     open($fh,"<$file");
                   10622:     my $a='';
1.800     albertel 10623:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10624:     return $a;
                   10625: }
                   10626: 
1.36      albertel 10627: sub filelocation {
1.590     banghart 10628:     my ($dir,$file) = @_;
                   10629:     my $location;
                   10630:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10631: 
                   10632:     if ($file =~ m-^/adm/-) {
                   10633: 	$file=~s-^/adm/wrapper/-/-;
                   10634: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10635:     }
1.882     albertel 10636: 
1.1139    www      10637:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10638:         $location = $file;
1.609     banghart 10639:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10640:         my ($udom,$uname,$filename)=
1.811     albertel 10641:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10642:         my $home=&homeserver($uname,$udom);
                   10643:         my $is_me=0;
                   10644:         my @ids=&current_machine_ids();
                   10645:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10646:         if ($is_me) {
1.1117    foxr     10647:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10648:         } else {
                   10649:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10650:   	      $udom.'/'.$uname.'/'.$filename;
                   10651:         }
1.882     albertel 10652:     } elsif ($file =~ m-^/adm/-) {
                   10653: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10654:     } else {
                   10655:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10656:         $file=~s:^/(res|priv)/:/:;
                   10657:         my $space=$1;
1.590     banghart 10658:         if ( !( $file =~ m:^/:) ) {
                   10659:             $location = $dir. '/'.$file;
                   10660:         } else {
1.1142    raeburn  10661:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10662:         }
1.59      albertel 10663:     }
1.590     banghart 10664:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10665:     while ($location=~m{/\.\./}) {
                   10666: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10667: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10668: 	} else {
                   10669: 	    $location=~ s{/\.\./}{/}g;
                   10670: 	}
                   10671:     } #remove dir/..
1.590     banghart 10672:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10673:     return $location;
1.46      www      10674: }
1.36      albertel 10675: 
1.46      www      10676: sub hreflocation {
                   10677:     my ($dir,$file)=@_;
1.980     raeburn  10678:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10679: 	$file=filelocation($dir,$file);
1.700     albertel 10680:     } elsif ($file=~m-^/adm/-) {
                   10681: 	$file=~s-^/adm/wrapper/-/-;
                   10682: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10683:     }
                   10684:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10685: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10686:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10687: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10688: 	        {/uploaded/$1/$2/}x;
1.46      www      10689:     }
1.913     albertel 10690:     if ($file=~ m{^/userfiles/}) {
                   10691: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10692:     }
1.462     albertel 10693:     return $file;
1.465     albertel 10694: }
                   10695: 
1.1139    www      10696: 
                   10697: 
                   10698: 
                   10699: 
1.465     albertel 10700: sub current_machine_domains {
1.853     albertel 10701:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10702: }
                   10703: 
                   10704: sub machine_domains {
                   10705:     my ($hostname) = @_;
1.465     albertel 10706:     my @domains;
1.838     albertel 10707:     my %hostname = &all_hostnames();
1.465     albertel 10708:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10709: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10710: 	if ($hostname eq $name) {
1.844     albertel 10711: 	    push(@domains,&host_domain($id));
1.465     albertel 10712: 	}
                   10713:     }
                   10714:     return @domains;
                   10715: }
                   10716: 
                   10717: sub current_machine_ids {
1.853     albertel 10718:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10719: }
                   10720: 
                   10721: sub machine_ids {
                   10722:     my ($hostname) = @_;
                   10723:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10724:     my @ids;
1.888     albertel 10725:     my %name_to_host = &all_names();
1.889     albertel 10726:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10727: 	return @{ $name_to_host{$hostname} };
                   10728:     }
                   10729:     return;
1.31      www      10730: }
                   10731: 
1.824     raeburn  10732: sub additional_machine_domains {
                   10733:     my @domains;
                   10734:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10735:     while( my $line = <$fh>) {
                   10736:         $line =~ s/\s//g;
                   10737:         push(@domains,$line);
                   10738:     }
                   10739:     return @domains;
                   10740: }
                   10741: 
                   10742: sub default_login_domain {
                   10743:     my $domain = $perlvar{'lonDefDomain'};
                   10744:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10745:     foreach my $posdom (&current_machine_domains(),
                   10746:                         &additional_machine_domains()) {
                   10747:         if (lc($posdom) eq lc($testdomain)) {
                   10748:             $domain=$posdom;
                   10749:             last;
                   10750:         }
                   10751:     }
                   10752:     return $domain;
                   10753: }
                   10754: 
1.31      www      10755: # ------------------------------------------------------------- Declutters URLs
                   10756: 
                   10757: sub declutter {
                   10758:     my $thisfn=shift;
1.569     albertel 10759:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10760:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10761:     $thisfn=~s/^\///;
1.697     albertel 10762:     $thisfn=~s|^adm/wrapper/||;
                   10763:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10764:     $thisfn=~s/^res\///;
1.1172    bisitz   10765:     $thisfn=~s/^priv\///;
1.1032    raeburn  10766:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10767:         $thisfn=~s/\?.+$//;
                   10768:     }
1.268     www      10769:     return $thisfn;
                   10770: }
                   10771: 
                   10772: # ------------------------------------------------------------- Clutter up URLs
                   10773: 
                   10774: sub clutter {
                   10775:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10776:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10777: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10778:        $thisfn='/res'.$thisfn; 
                   10779:     }
1.1031    raeburn  10780:     if ($thisfn !~m|^/adm|) {
                   10781: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10782: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10783: 	} else {
                   10784: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10785: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10786: 	    if ($embstyle eq 'ssi'
                   10787: 		|| ($embstyle eq 'hdn')
                   10788: 		|| ($embstyle eq 'rat')
                   10789: 		|| ($embstyle eq 'prv')
                   10790: 		|| ($embstyle eq 'ign')) {
                   10791: 		#do nothing with these
                   10792: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10793: 		|| ($embstyle eq 'emb')
                   10794: 		|| ($embstyle eq 'wrp')) {
                   10795: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10796: 	    } elsif ($embstyle eq 'unk'
                   10797: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10798: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10799: 	    } else {
1.718     www      10800: #		&logthis("Got a blank emb style");
1.695     albertel 10801: 	    }
1.694     albertel 10802: 	}
                   10803:     }
1.31      www      10804:     return $thisfn;
1.12      www      10805: }
                   10806: 
1.787     albertel 10807: sub clutter_with_no_wrapper {
                   10808:     my $uri = &clutter(shift);
                   10809:     if ($uri =~ m-^/adm/-) {
                   10810: 	$uri =~ s-^/adm/wrapper/-/-;
                   10811: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10812:     }
                   10813:     return $uri;
                   10814: }
                   10815: 
1.557     albertel 10816: sub freeze_escape {
                   10817:     my ($value)=@_;
                   10818:     if (ref($value)) {
                   10819: 	$value=&nfreeze($value);
                   10820: 	return '__FROZEN__'.&escape($value);
                   10821:     }
                   10822:     return &escape($value);
                   10823: }
                   10824: 
1.11      www      10825: 
1.557     albertel 10826: sub thaw_unescape {
                   10827:     my ($value)=@_;
                   10828:     if ($value =~ /^__FROZEN__/) {
                   10829: 	substr($value,0,10,undef);
                   10830: 	$value=&unescape($value);
                   10831: 	return &thaw($value);
                   10832:     }
                   10833:     return &unescape($value);
                   10834: }
                   10835: 
1.436     albertel 10836: sub correct_line_ends {
                   10837:     my ($result)=@_;
                   10838:     $$result =~s/\r\n/\n/mg;
                   10839:     $$result =~s/\r/\n/mg;
1.415     albertel 10840: }
1.1       albertel 10841: # ================================================================ Main Program
                   10842: 
1.184     www      10843: sub goodbye {
1.204     albertel 10844:    &logthis("Starting Shut down");
1.443     albertel 10845: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10846:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10847: #converted
1.599     albertel 10848: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10849:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10850: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10851: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10852: #1.1 only
1.870     albertel 10853: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10854: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10855: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10856: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10857:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10858:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10859:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10860:    &flushcourselogs();
                   10861:    &logthis("Shutting down");
                   10862: }
                   10863: 
1.852     albertel 10864: sub get_dns {
1.869     albertel 10865:     my ($url,$func,$ignore_cache) = @_;
                   10866:     if (!$ignore_cache) {
                   10867: 	my ($content,$cached)=
                   10868: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10869: 	if ($cached) {
                   10870: 	    &$func($content);
                   10871: 	    return;
                   10872: 	}
                   10873:     }
                   10874: 
                   10875:     my %alldns;
1.852     albertel 10876:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10877:     foreach my $dns (<$config>) {
                   10878: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10879:         my $line = $1;
                   10880:         my ($host,$protocol) = split(/:/,$line);
                   10881:         if ($protocol ne 'https') {
                   10882:             $protocol = 'http';
                   10883:         }
                   10884: 	$alldns{$host} = $protocol;
1.869     albertel 10885:     }
                   10886:     while (%alldns) {
                   10887: 	my ($dns) = keys(%alldns);
1.852     albertel 10888: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10889:         $ua->timeout(30);
1.979     raeburn  10890: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10891: 	my $response=$ua->request($request);
1.979     raeburn  10892:         delete($alldns{$dns});
1.852     albertel 10893: 	next if ($response->is_error());
                   10894: 	my @content = split("\n",$response->content);
1.869     albertel 10895: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10896: 	&$func(\@content);
1.869     albertel 10897: 	return;
1.852     albertel 10898:     }
                   10899:     close($config);
1.871     albertel 10900:     my $which = (split('/',$url))[3];
                   10901:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10902:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10903:     my @content = <$config>;
                   10904:     &$func(\@content);
                   10905:     return;
1.852     albertel 10906: }
1.327     albertel 10907: # ------------------------------------------------------------ Read domain file
                   10908: {
1.852     albertel 10909:     my $loaded;
1.846     albertel 10910:     my %domain;
                   10911: 
1.852     albertel 10912:     sub parse_domain_tab {
                   10913: 	my ($lines) = @_;
                   10914: 	foreach my $line (@$lines) {
                   10915: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10916: 
1.846     albertel 10917: 	    chomp($line);
1.852     albertel 10918: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10919: 	    my %this_domain;
                   10920: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10921: 			       'lang_def', 'city', 'longi', 'lati',
                   10922: 			       'primary') {
                   10923: 		$this_domain{$field} = shift(@elements);
                   10924: 	    }
                   10925: 	    $domain{$name} = \%this_domain;
1.852     albertel 10926: 	}
                   10927:     }
1.864     albertel 10928: 
                   10929:     sub reset_domain_info {
                   10930: 	undef($loaded);
                   10931: 	undef(%domain);
                   10932:     }
                   10933: 
1.852     albertel 10934:     sub load_domain_tab {
1.869     albertel 10935: 	my ($ignore_cache) = @_;
                   10936: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10937: 	my $fh;
                   10938: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10939: 	    my @lines = <$fh>;
                   10940: 	    &parse_domain_tab(\@lines);
1.448     albertel 10941: 	}
1.852     albertel 10942: 	close($fh);
                   10943: 	$loaded = 1;
1.327     albertel 10944:     }
1.846     albertel 10945: 
                   10946:     sub domain {
1.852     albertel 10947: 	&load_domain_tab() if (!$loaded);
                   10948: 
1.846     albertel 10949: 	my ($name,$what) = @_;
                   10950: 	return if ( !exists($domain{$name}) );
                   10951: 
                   10952: 	if (!$what) {
                   10953: 	    return $domain{$name}{'description'};
                   10954: 	}
                   10955: 	return $domain{$name}{$what};
                   10956:     }
1.974     raeburn  10957: 
                   10958:     sub domain_info {
                   10959:         &load_domain_tab() if (!$loaded);
                   10960:         return %domain;
                   10961:     }
                   10962: 
1.327     albertel 10963: }
                   10964: 
                   10965: 
1.1       albertel 10966: # ------------------------------------------------------------- Read hosts file
                   10967: {
1.838     albertel 10968:     my %hostname;
1.844     albertel 10969:     my %hostdom;
1.845     albertel 10970:     my %libserv;
1.852     albertel 10971:     my $loaded;
1.888     albertel 10972:     my %name_to_host;
1.1074    raeburn  10973:     my %internetdom;
1.1107    raeburn  10974:     my %LC_dns_serv;
1.852     albertel 10975: 
                   10976:     sub parse_hosts_tab {
                   10977: 	my ($file) = @_;
                   10978: 	foreach my $configline (@$file) {
                   10979: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10980:             chomp($configline);
                   10981: 	    if ($configline =~ /^\^/) {
                   10982:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10983:                     $LC_dns_serv{$1} = 1;
                   10984:                 }
                   10985:                 next;
                   10986:             }
1.1074    raeburn  10987: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10988: 	    $name=~s/\s//g;
                   10989: 	    if ($id && $domain && $role && $name) {
                   10990: 		$hostname{$id}=$name;
1.888     albertel 10991: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10992: 		$hostdom{$id}=$domain;
                   10993: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10994:                 if (defined($protocol)) {
                   10995:                     if ($protocol eq 'https') {
                   10996:                         $protocol{$id} = $protocol;
                   10997:                     } else {
                   10998:                         $protocol{$id} = 'http'; 
                   10999:                     }
1.968     raeburn  11000:                 } else {
1.969     raeburn  11001:                     $protocol{$id} = 'http';
1.968     raeburn  11002:                 }
1.1074    raeburn  11003:                 if (defined($intdom)) {
                   11004:                     $internetdom{$id} = $intdom;
                   11005:                 }
1.852     albertel 11006: 	    }
                   11007: 	}
                   11008:     }
1.864     albertel 11009:     
                   11010:     sub reset_hosts_info {
1.897     albertel 11011: 	&purge_remembered();
1.864     albertel 11012: 	&reset_domain_info();
                   11013: 	&reset_hosts_ip_info();
1.892     albertel 11014: 	undef(%name_to_host);
1.864     albertel 11015: 	undef(%hostname);
                   11016: 	undef(%hostdom);
                   11017: 	undef(%libserv);
                   11018: 	undef($loaded);
                   11019:     }
1.1       albertel 11020: 
1.852     albertel 11021:     sub load_hosts_tab {
1.869     albertel 11022: 	my ($ignore_cache) = @_;
                   11023: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11024: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11025: 	my @config = <$config>;
                   11026: 	&parse_hosts_tab(\@config);
                   11027: 	close($config);
                   11028: 	$loaded=1;
1.1       albertel 11029:     }
1.852     albertel 11030: 
1.838     albertel 11031:     sub hostname {
1.852     albertel 11032: 	&load_hosts_tab() if (!$loaded);
                   11033: 
1.838     albertel 11034: 	my ($lonid) = @_;
                   11035: 	return $hostname{$lonid};
                   11036:     }
1.845     albertel 11037: 
1.838     albertel 11038:     sub all_hostnames {
1.852     albertel 11039: 	&load_hosts_tab() if (!$loaded);
                   11040: 
1.838     albertel 11041: 	return %hostname;
                   11042:     }
1.845     albertel 11043: 
1.888     albertel 11044:     sub all_names {
                   11045: 	&load_hosts_tab() if (!$loaded);
                   11046: 
                   11047: 	return %name_to_host;
                   11048:     }
                   11049: 
1.974     raeburn  11050:     sub all_host_domain {
                   11051:         &load_hosts_tab() if (!$loaded);
                   11052:         return %hostdom;
                   11053:     }
                   11054: 
1.845     albertel 11055:     sub is_library {
1.852     albertel 11056: 	&load_hosts_tab() if (!$loaded);
                   11057: 
1.845     albertel 11058: 	return exists($libserv{$_[0]});
                   11059:     }
                   11060: 
                   11061:     sub all_library {
1.852     albertel 11062: 	&load_hosts_tab() if (!$loaded);
                   11063: 
1.845     albertel 11064: 	return %libserv;
                   11065:     }
                   11066: 
1.1062    droeschl 11067:     sub unique_library {
                   11068: 	#2x reverse removes all hostnames that appear more than once
                   11069:         my %unique = reverse &all_library();
                   11070:         return reverse %unique;
                   11071:     }
                   11072: 
1.841     albertel 11073:     sub get_servers {
1.852     albertel 11074: 	&load_hosts_tab() if (!$loaded);
                   11075: 
1.841     albertel 11076: 	my ($domain,$type) = @_;
                   11077: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11078: 	                                          : %hostname;
                   11079: 	my %result;
1.842     albertel 11080: 	if (ref($domain) eq 'ARRAY') {
                   11081: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11082: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11083: 		    $result{$host} = $hostname;
                   11084: 		}
                   11085: 	    }
                   11086: 	} else {
                   11087: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11088: 		if ($hostdom{$host} eq $domain) {
                   11089: 		    $result{$host} = $hostname;
                   11090: 		}
1.841     albertel 11091: 	    }
                   11092: 	}
                   11093: 	return %result;
                   11094:     }
1.845     albertel 11095: 
1.1062    droeschl 11096:     sub get_unique_servers {
                   11097:         my %unique = reverse &get_servers(@_);
                   11098: 	return reverse %unique;
                   11099:     }
                   11100: 
1.844     albertel 11101:     sub host_domain {
1.852     albertel 11102: 	&load_hosts_tab() if (!$loaded);
                   11103: 
1.844     albertel 11104: 	my ($lonid) = @_;
                   11105: 	return $hostdom{$lonid};
                   11106:     }
                   11107: 
1.841     albertel 11108:     sub all_domains {
1.852     albertel 11109: 	&load_hosts_tab() if (!$loaded);
                   11110: 
1.841     albertel 11111: 	my %seen;
                   11112: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11113: 	return @uniq;
                   11114:     }
1.1074    raeburn  11115: 
                   11116:     sub internet_dom {
                   11117:         &load_hosts_tab() if (!$loaded);
                   11118: 
                   11119:         my ($lonid) = @_;
                   11120:         return $internetdom{$lonid};
                   11121:     }
1.1107    raeburn  11122: 
                   11123:     sub is_LC_dns {
                   11124:         &load_hosts_tab() if (!$loaded);
                   11125: 
                   11126:         my ($hostname) = @_;
                   11127:         return exists($LC_dns_serv{$hostname});
                   11128:     }
                   11129: 
1.1       albertel 11130: }
                   11131: 
1.847     albertel 11132: { 
                   11133:     my %iphost;
1.856     albertel 11134:     my %name_to_ip;
                   11135:     my %lonid_to_ip;
1.869     albertel 11136: 
1.847     albertel 11137:     sub get_hosts_from_ip {
                   11138: 	my ($ip) = @_;
                   11139: 	my %iphosts = &get_iphost();
                   11140: 	if (ref($iphosts{$ip})) {
                   11141: 	    return @{$iphosts{$ip}};
                   11142: 	}
                   11143: 	return;
1.839     albertel 11144:     }
1.864     albertel 11145:     
                   11146:     sub reset_hosts_ip_info {
                   11147: 	undef(%iphost);
                   11148: 	undef(%name_to_ip);
                   11149: 	undef(%lonid_to_ip);
                   11150:     }
1.856     albertel 11151: 
                   11152:     sub get_host_ip {
                   11153: 	my ($lonid) = @_;
                   11154: 	if (exists($lonid_to_ip{$lonid})) {
                   11155: 	    return $lonid_to_ip{$lonid};
                   11156: 	}
                   11157: 	my $name=&hostname($lonid);
                   11158:    	my $ip = gethostbyname($name);
                   11159: 	return if (!$ip || length($ip) ne 4);
                   11160: 	$ip=inet_ntoa($ip);
                   11161: 	$name_to_ip{$name}   = $ip;
                   11162: 	$lonid_to_ip{$lonid} = $ip;
                   11163: 	return $ip;
                   11164:     }
1.847     albertel 11165:     
                   11166:     sub get_iphost {
1.869     albertel 11167: 	my ($ignore_cache) = @_;
1.894     albertel 11168: 
1.869     albertel 11169: 	if (!$ignore_cache) {
                   11170: 	    if (%iphost) {
                   11171: 		return %iphost;
                   11172: 	    }
                   11173: 	    my ($ip_info,$cached)=
                   11174: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11175: 	    if ($cached) {
                   11176: 		%iphost      = %{$ip_info->[0]};
                   11177: 		%name_to_ip  = %{$ip_info->[1]};
                   11178: 		%lonid_to_ip = %{$ip_info->[2]};
                   11179: 		return %iphost;
                   11180: 	    }
                   11181: 	}
1.894     albertel 11182: 
                   11183: 	# get yesterday's info for fallback
                   11184: 	my %old_name_to_ip;
                   11185: 	my ($ip_info,$cached)=
                   11186: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11187: 	if ($cached) {
                   11188: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11189: 	}
                   11190: 
1.888     albertel 11191: 	my %name_to_host = &all_names();
                   11192: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11193: 	    my $ip;
                   11194: 	    if (!exists($name_to_ip{$name})) {
                   11195: 		$ip = gethostbyname($name);
                   11196: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11197: 		    if (defined($old_name_to_ip{$name})) {
                   11198: 			$ip = $old_name_to_ip{$name};
                   11199: 			&logthis("Can't find $name defaulting to old $ip");
                   11200: 		    } else {
                   11201: 			&logthis("Name $name no IP found");
                   11202: 			next;
                   11203: 		    }
                   11204: 		} else {
                   11205: 		    $ip=inet_ntoa($ip);
1.847     albertel 11206: 		}
                   11207: 		$name_to_ip{$name} = $ip;
                   11208: 	    } else {
                   11209: 		$ip = $name_to_ip{$name};
1.653     albertel 11210: 	    }
1.888     albertel 11211: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11212: 		$lonid_to_ip{$id} = $ip;
                   11213: 	    }
                   11214: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11215: 	}
1.869     albertel 11216: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11217: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11218: 				      48*60*60);
1.869     albertel 11219: 
1.847     albertel 11220: 	return %iphost;
1.598     albertel 11221:     }
                   11222: 
1.992     raeburn  11223:     #
                   11224:     #  Given a DNS returns the loncapa host name for that DNS 
                   11225:     # 
                   11226:     sub host_from_dns {
                   11227:         my ($dns) = @_;
                   11228:         my @hosts;
                   11229:         my $ip;
                   11230: 
1.993     raeburn  11231:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11232:             $ip = $name_to_ip{$dns};
                   11233:         }
                   11234:         if (!$ip) {
                   11235:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11236:             if (length($ip) == 4) { 
                   11237: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11238:             }
                   11239:         }
                   11240:         if ($ip) {
                   11241: 	    @hosts = get_hosts_from_ip($ip);
                   11242: 	    return $hosts[0];
                   11243:         }
                   11244:         return undef;
1.986     foxr     11245:     }
1.992     raeburn  11246: 
1.1074    raeburn  11247:     sub get_internet_names {
                   11248:         my ($lonid) = @_;
                   11249:         return if ($lonid eq '');
                   11250:         my ($idnref,$cached)=
                   11251:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11252:         if ($cached) {
                   11253:             return $idnref;
                   11254:         }
                   11255:         my $ip = &get_host_ip($lonid);
                   11256:         my @hosts = &get_hosts_from_ip($ip);
                   11257:         my %iphost = &get_iphost();
                   11258:         my (@idns,%seen);
                   11259:         foreach my $id (@hosts) {
                   11260:             my $dom = &host_domain($id);
                   11261:             my $prim_id = &domain($dom,'primary');
                   11262:             my $prim_ip = &get_host_ip($prim_id);
                   11263:             next if ($seen{$prim_ip});
                   11264:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11265:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11266:                     my $intdom = &internet_dom($id);
                   11267:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11268:                         push(@idns,$intdom);
                   11269:                     }
                   11270:                 }
                   11271:             }
                   11272:             $seen{$prim_ip} = 1;
                   11273:         }
                   11274:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11275:     }
                   11276: 
1.986     foxr     11277: }
                   11278: 
1.1079    raeburn  11279: sub all_loncaparevs {
                   11280:     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);
                   11281: }
                   11282: 
1.862     albertel 11283: BEGIN {
                   11284: 
                   11285: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11286:     unless ($readit) {
                   11287: {
                   11288:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11289:     %perlvar = (%perlvar,%{$configvars});
                   11290: }
                   11291: 
                   11292: 
1.1       albertel 11293: # ------------------------------------------------------ Read spare server file
                   11294: {
1.448     albertel 11295:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11296: 
                   11297:     while (my $configline=<$config>) {
                   11298:        chomp($configline);
1.284     matthew  11299:        if ($configline) {
1.784     albertel 11300: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11301: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11302: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11303:        }
                   11304:     }
1.448     albertel 11305:     close($config);
1.1       albertel 11306: }
1.11      www      11307: # ------------------------------------------------------------ Read permissions
                   11308: {
1.448     albertel 11309:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11310: 
                   11311:     while (my $configline=<$config>) {
1.448     albertel 11312: 	chomp($configline);
                   11313: 	if ($configline) {
                   11314: 	    my ($role,$perm)=split(/ /,$configline);
                   11315: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11316: 	}
1.11      www      11317:     }
1.448     albertel 11318:     close($config);
1.11      www      11319: }
                   11320: 
                   11321: # -------------------------------------------- Read plain texts for permissions
                   11322: {
1.448     albertel 11323:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11324: 
                   11325:     while (my $configline=<$config>) {
1.448     albertel 11326: 	chomp($configline);
                   11327: 	if ($configline) {
1.742     raeburn  11328: 	    my ($short,@plain)=split(/:/,$configline);
                   11329:             %{$prp{$short}} = ();
                   11330: 	    if (@plain > 0) {
                   11331:                 $prp{$short}{'std'} = $plain[0];
                   11332:                 for (my $i=1; $i<@plain; $i++) {
                   11333:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11334:                 }
                   11335:             }
1.448     albertel 11336: 	}
1.135     www      11337:     }
1.448     albertel 11338:     close($config);
1.135     www      11339: }
                   11340: 
                   11341: # ---------------------------------------------------------- Read package table
                   11342: {
1.448     albertel 11343:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11344: 
                   11345:     while (my $configline=<$config>) {
1.483     albertel 11346: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11347: 	chomp($configline);
                   11348: 	my ($short,$plain)=split(/:/,$configline);
                   11349: 	my ($pack,$name)=split(/\&/,$short);
                   11350: 	if ($plain ne '') {
                   11351: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11352: 	    $packagetab{$short}=$plain; 
                   11353: 	}
1.11      www      11354:     }
1.448     albertel 11355:     close($config);
1.329     matthew  11356: }
                   11357: 
1.1073    raeburn  11358: # ---------------------------------------------------------- Read loncaparev table
                   11359: {
                   11360:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11361:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11362:             while (my $configline=<$config>) {
                   11363:                 chomp($configline);
                   11364:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11365:                 $loncaparevs{$hostid}=$loncaparev;
                   11366:             }
                   11367:             close($config);
                   11368:         }
                   11369:     }
                   11370: }
                   11371: 
1.1074    raeburn  11372: # ---------------------------------------------------------- Read serverhostID table
                   11373: {
                   11374:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11375:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11376:             while (my $configline=<$config>) {
                   11377:                 chomp($configline);
                   11378:                 my ($name,$id)=split(/:/,$configline);
                   11379:                 $serverhomeIDs{$name}=$id;
                   11380:             }
                   11381:             close($config);
                   11382:         }
                   11383:     }
                   11384: }
                   11385: 
1.1079    raeburn  11386: {
                   11387:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11388:     if (-e $file) {
                   11389:         my $parser = HTML::LCParser->new($file);
                   11390:         while (my $token = $parser->get_token()) {
                   11391:             if ($token->[0] eq 'S') {
                   11392:                 my $item = $token->[1];
                   11393:                 my $name = $token->[2]{'name'};
                   11394:                 my $value = $token->[2]{'value'};
                   11395:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11396:                     my $release = $parser->get_text();
                   11397:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11398:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11399:                 }
                   11400:             }
                   11401:         }
                   11402:     }
1.1073    raeburn  11403: }
                   11404: 
1.1138    raeburn  11405: # ---------------------------------------------------------- Read managers table
                   11406: {
                   11407:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11408:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11409:             while (my $configline=<$config>) {
                   11410:                 chomp($configline);
                   11411:                 next if ($configline =~ /^\#/);
                   11412:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11413:                     $managerstab{$configline} = 1;
                   11414:                 }
                   11415:             }
                   11416:             close($config);
                   11417:         }
                   11418:     }
                   11419: }
                   11420: 
1.329     matthew  11421: # ------------- set up temporary directory
                   11422: {
1.1117    foxr     11423:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11424: 
1.11      www      11425: }
                   11426: 
1.794     albertel 11427: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11428: 				'compress_threshold'=> 20_000,
                   11429:  			        });
1.185     www      11430: 
1.281     www      11431: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11432: $dumpcount=0;
1.958     www      11433: $locknum=0;
1.22      www      11434: 
1.163     harris41 11435: &logtouch();
1.672     albertel 11436: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11437: $readit=1;
1.564     albertel 11438:     {
                   11439: 	use integer;
                   11440: 	my $test=(2**32)+1;
1.568     albertel 11441: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11442: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11443:     }
1.195     www      11444: }
1.1       albertel 11445: }
1.179     www      11446: 
1.1       albertel 11447: 1;
1.191     harris41 11448: __END__
                   11449: 
1.243     albertel 11450: =pod
                   11451: 
1.191     harris41 11452: =head1 NAME
                   11453: 
1.243     albertel 11454: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11455: 
                   11456: =head1 SYNOPSIS
                   11457: 
1.243     albertel 11458: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11459: 
                   11460:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11461: 
1.243     albertel 11462: Common parameters:
                   11463: 
                   11464: =over 4
                   11465: 
                   11466: =item *
                   11467: 
                   11468: $uname : an internal username (if $cname expecting a course Id specifically)
                   11469: 
                   11470: =item *
                   11471: 
                   11472: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11473: 
                   11474: =item *
                   11475: 
                   11476: $symb : a resource instance identifier
                   11477: 
                   11478: =item *
                   11479: 
                   11480: $namespace : the name of a .db file that contains the data needed or
                   11481: being set.
                   11482: 
                   11483: =back
                   11484: 
1.394     bowersj2 11485: =head1 OVERVIEW
1.191     harris41 11486: 
1.394     bowersj2 11487: lonnet provides subroutines which interact with the
                   11488: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11489: about classes, users, and resources.
1.243     albertel 11490: 
                   11491: For many of these objects you can also use this to store data about
                   11492: them or modify them in various ways.
1.191     harris41 11493: 
1.394     bowersj2 11494: =head2 Symbs
1.191     harris41 11495: 
1.394     bowersj2 11496: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11497: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11498: map, the resource number of the resource in the map, and the URL of
                   11499: the resource itself. The latter is somewhat redundant, but might help
                   11500: if maps change.
                   11501: 
                   11502: An example is
                   11503: 
                   11504:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11505: 
                   11506: The respective map entry is
                   11507: 
                   11508:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11509:   title="Problem 2">
                   11510:  </resource>
                   11511: 
                   11512: Symbs are used by the random number generator, as well as to store and
                   11513: restore data specific to a certain instance of for example a problem.
                   11514: 
                   11515: =head2 Storing And Retrieving Data
                   11516: 
                   11517: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11518: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11519: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11520: is is the non-critical message twin of cstore. These functions are for
                   11521: handlers to store a perl hash to a user's permanent data space in an
                   11522: easy manner, and to retrieve it again on another call. It is expected
                   11523: that a handler would use this once at the beginning to retrieve data,
                   11524: and then again once at the end to send only the new data back.
                   11525: 
                   11526: The data is stored in the user's data directory on the user's
                   11527: homeserver under the ID of the course.
                   11528: 
                   11529: The hash that is returned by restore will have all of the previous
                   11530: value for all of the elements of the hash.
                   11531: 
                   11532: Example:
                   11533: 
                   11534:  #creating a hash
                   11535:  my %hash;
                   11536:  $hash{'foo'}='bar';
                   11537: 
                   11538:  #storing it
                   11539:  &Apache::lonnet::cstore(\%hash);
                   11540: 
                   11541:  #changing a value
                   11542:  $hash{'foo'}='notbar';
                   11543: 
                   11544:  #adding a new value
                   11545:  $hash{'bar'}='foo';
                   11546:  &Apache::lonnet::cstore(\%hash);
                   11547: 
                   11548:  #retrieving the hash
                   11549:  my %history=&Apache::lonnet::restore();
                   11550: 
                   11551:  #print the hash
                   11552:  foreach my $key (sort(keys(%history))) {
                   11553:    print("\%history{$key} = $history{$key}");
                   11554:  }
                   11555: 
                   11556: Will print out:
1.191     harris41 11557: 
1.394     bowersj2 11558:  %history{1:foo} = bar
                   11559:  %history{1:keys} = foo:timestamp
                   11560:  %history{1:timestamp} = 990455579
                   11561:  %history{2:bar} = foo
                   11562:  %history{2:foo} = notbar
                   11563:  %history{2:keys} = foo:bar:timestamp
                   11564:  %history{2:timestamp} = 990455580
                   11565:  %history{bar} = foo
                   11566:  %history{foo} = notbar
                   11567:  %history{timestamp} = 990455580
                   11568:  %history{version} = 2
                   11569: 
                   11570: Note that the special hash entries C<keys>, C<version> and
                   11571: C<timestamp> were added to the hash. C<version> will be equal to the
                   11572: total number of versions of the data that have been stored. The
                   11573: C<timestamp> attribute will be the UNIX time the hash was
                   11574: stored. C<keys> is available in every historical section to list which
                   11575: keys were added or changed at a specific historical revision of a
                   11576: hash.
                   11577: 
                   11578: B<Warning>: do not store the hash that restore returns directly. This
                   11579: will cause a mess since it will restore the historical keys as if the
                   11580: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11581: 
1.394     bowersj2 11582: Calling convention:
1.191     harris41 11583: 
1.394     bowersj2 11584:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11585:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11586: 
1.394     bowersj2 11587: For more detailed information, see lonnet specific documentation.
1.191     harris41 11588: 
1.394     bowersj2 11589: =head1 RETURN MESSAGES
1.191     harris41 11590: 
1.394     bowersj2 11591: =over 4
1.191     harris41 11592: 
1.394     bowersj2 11593: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11594: 
1.394     bowersj2 11595: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11596: when the connection is brought back up
1.191     harris41 11597: 
1.394     bowersj2 11598: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11599: for later delivery
1.191     harris41 11600: 
1.967     bisitz   11601: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11602: 
1.394     bowersj2 11603: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11604: that was requested
1.191     harris41 11605: 
1.243     albertel 11606: =back
1.191     harris41 11607: 
1.243     albertel 11608: =head1 PUBLIC SUBROUTINES
1.191     harris41 11609: 
1.243     albertel 11610: =head2 Session Environment Functions
1.191     harris41 11611: 
1.243     albertel 11612: =over 4
1.191     harris41 11613: 
1.394     bowersj2 11614: =item * 
                   11615: X<appenv()>
1.949     raeburn  11616: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11617: the user envirnoment file, and will be restored for each access this
1.620     albertel 11618: user makes during this session, also modifies the %env for the current
1.949     raeburn  11619: process. Optional rolesarrayref - if defined contains a reference to an array
                   11620: of roles which are exempt from the restriction on modifying user.role entries 
                   11621: in the user's environment.db and in %env.    
1.191     harris41 11622: 
                   11623: =item *
1.394     bowersj2 11624: X<delenv()>
1.987     raeburn  11625: B<delenv($delthis,$regexp)>: removes all items from the session
                   11626: environment file that begin with $delthis. If the 
                   11627: optional second arg - $regexp - is true, $delthis is treated as a 
                   11628: regular expression, otherwise \Q$delthis\E is used. 
                   11629: The values are also deleted from the current processes %env.
1.191     harris41 11630: 
1.795     albertel 11631: =item * get_env_multiple($name) 
                   11632: 
                   11633: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11634: values may be defined and end up as an array ref.
                   11635: 
                   11636: returns an array of values
                   11637: 
1.243     albertel 11638: =back
                   11639: 
                   11640: =head2 User Information
1.191     harris41 11641: 
1.243     albertel 11642: =over 4
1.191     harris41 11643: 
                   11644: =item *
1.394     bowersj2 11645: X<queryauthenticate()>
                   11646: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11647: authentication scheme
                   11648: 
                   11649: =item *
1.394     bowersj2 11650: X<authenticate()>
1.1073    raeburn  11651: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11652: authenticate user from domain's lib servers (first use the current
                   11653: one). C<$upass> should be the users password.
1.1073    raeburn  11654: $checkdefauth is optional (value is 1 if a check should be made to
                   11655:    authenticate user using default authentication method, and allow
                   11656:    account creation if username does not have account in the domain).
                   11657: $clientcancheckhost is optional (value is 1 if checking whether the
                   11658:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11659: 
                   11660: =item *
1.394     bowersj2 11661: X<homeserver()>
                   11662: B<homeserver($uname,$udom)>: find the server which has
                   11663: the user's directory and files (there must be only one), this caches
                   11664: the answer, and also caches if there is a borken connection.
1.191     harris41 11665: 
                   11666: =item *
1.394     bowersj2 11667: X<idget()>
                   11668: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11669: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11670: username, and only 1 username per ID in a specific domain) (returns
                   11671: hash: id=>name,id=>name)
1.191     harris41 11672: 
                   11673: =item *
1.394     bowersj2 11674: X<idrget()>
                   11675: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11676: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11677: 
                   11678: =item *
1.394     bowersj2 11679: X<idput()>
                   11680: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11681: 
                   11682: =item *
1.394     bowersj2 11683: X<rolesinit()>
1.1169    droeschl 11684: B<rolesinit($udom,$username)>: get user privileges.
                   11685: returns user role, first access and timer interval hashes
1.243     albertel 11686: 
                   11687: =item *
1.1171    droeschl 11688: X<privileged()>
                   11689: B<privileged($username,$domain)>: returns a true if user has a
                   11690: privileged and active role (i.e. su or dc), false otherwise.
                   11691: 
                   11692: =item *
1.551     albertel 11693: X<getsection()>
                   11694: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11695: course $cname, return section name/number or '' for "not in course"
                   11696: and '-1' for "no section"
                   11697: 
                   11698: =item *
1.394     bowersj2 11699: X<userenvironment()>
                   11700: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11701: passed in @what from the requested user's environment, returns a hash
                   11702: 
1.858     raeburn  11703: =item * 
                   11704: X<userlog_query()>
1.859     albertel 11705: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11706: activity.log file. %filters defines filters applied when parsing the
                   11707: log file. These can be start or end timestamps, or the type of action
                   11708: - log to look for Login or Logout events, check for Checkin or
                   11709: Checkout, role for role selection. The response is in the form
                   11710: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11711: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11712: 
1.243     albertel 11713: =back
                   11714: 
                   11715: =head2 User Roles
                   11716: 
                   11717: =over 4
                   11718: 
                   11719: =item *
                   11720: 
1.810     raeburn  11721: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11722:  F: full access
                   11723:  U,I,K: authentication modes (cxx only)
                   11724:  '': forbidden
                   11725:  1: user needs to choose course
                   11726:  2: browse allowed
1.766     albertel 11727:  A: passphrase authentication needed
1.243     albertel 11728: 
                   11729: =item *
                   11730: 
                   11731: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11732: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11733: and course level
                   11734: 
                   11735: =item *
                   11736: 
1.988     raeburn  11737: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11738: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11739: $type is Course (default) or Community.
1.988     raeburn  11740: If $forcedefault evaluates to true, text returned will be default 
                   11741: text for $type. Otherwise, if this is a course, the text returned 
                   11742: will be a custom name for the role (if defined in the course's 
                   11743: environment).  If no custom name is defined the default is returned.
                   11744:    
1.832     raeburn  11745: =item *
                   11746: 
1.935     raeburn  11747: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11748: All arguments are optional. Returns a hash of a roles, either for
                   11749: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11750: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11751: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11752: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11753: For each key, value is set to colon-separated start and end times for
                   11754: the role.  If no username and domain are specified, will default to
1.934     raeburn  11755: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11756: of role statuses (active, future or previous), roles 
                   11757: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11758: to restrict the list of roles reported. If no array ref is 
                   11759: provided for types, will default to return only active roles.
1.834     albertel 11760: 
1.243     albertel 11761: =back
                   11762: 
                   11763: =head2 User Modification
                   11764: 
                   11765: =over 4
                   11766: 
                   11767: =item *
                   11768: 
1.957     raeburn  11769: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11770: user for the level given by URL.  Optional start and end dates (leave empty
                   11771: string or zero for "no date")
1.191     harris41 11772: 
                   11773: =item *
                   11774: 
1.243     albertel 11775: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11776: change a users, password, possible return values are: ok,
                   11777: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11778: refused
1.191     harris41 11779: 
                   11780: =item *
                   11781: 
1.243     albertel 11782: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11783: 
                   11784: =item *
                   11785: 
1.1058    raeburn  11786: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11787:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11788: 
                   11789: will update user information (firstname,middlename,lastname,generation,
                   11790: permanentemail), and if forceid is true, student/employee ID also.
                   11791: A user's institutional affiliation(s) can also be updated.
                   11792: User information fields will not be overwritten with empty entries 
                   11793: unless the field is included in the $candelete array reference.
                   11794: This array is included when a single user is modified via "Manage Users",
                   11795: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11796: 
                   11797: =item *
                   11798: 
1.286     matthew  11799: modifystudent
                   11800: 
1.957     raeburn  11801: modify a student's enrollment and identification information.
1.286     matthew  11802: The course id is resolved based on the current users environment.  
                   11803: This means the envoking user must be a course coordinator or otherwise
                   11804: associated with a course.
                   11805: 
1.297     matthew  11806: This call is essentially a wrapper for lonnet::modifyuser and
                   11807: lonnet::modify_student_enrollment
1.286     matthew  11808: 
                   11809: Inputs: 
                   11810: 
                   11811: =over 4
                   11812: 
1.957     raeburn  11813: =item B<$udom> Student's loncapa domain
1.286     matthew  11814: 
1.957     raeburn  11815: =item B<$uname> Student's loncapa login name
1.286     matthew  11816: 
1.964     bisitz   11817: =item B<$uid> Student/Employee ID
1.286     matthew  11818: 
1.957     raeburn  11819: =item B<$umode> Student's authentication mode
1.286     matthew  11820: 
1.957     raeburn  11821: =item B<$upass> Student's password
1.286     matthew  11822: 
1.957     raeburn  11823: =item B<$first> Student's first name
1.286     matthew  11824: 
1.957     raeburn  11825: =item B<$middle> Student's middle name
1.286     matthew  11826: 
1.957     raeburn  11827: =item B<$last> Student's last name
1.286     matthew  11828: 
1.957     raeburn  11829: =item B<$gene> Student's generation
1.286     matthew  11830: 
1.957     raeburn  11831: =item B<$usec> Student's section in course
1.286     matthew  11832: 
                   11833: =item B<$end> Unix time of the roles expiration
                   11834: 
                   11835: =item B<$start> Unix time of the roles start date
                   11836: 
                   11837: =item B<$forceid> If defined, allow $uid to be changed
                   11838: 
                   11839: =item B<$desiredhome> server to use as home server for student
                   11840: 
1.957     raeburn  11841: =item B<$email> Student's permanent e-mail address
                   11842: 
                   11843: =item B<$type> Type of enrollment (auto or manual)
                   11844: 
1.963     raeburn  11845: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11846: 
                   11847: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11848: 
1.963     raeburn  11849: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11850: 
1.963     raeburn  11851: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11852: 
1.963     raeburn  11853: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11854: 
1.286     matthew  11855: =back
1.297     matthew  11856: 
                   11857: =item *
                   11858: 
                   11859: modify_student_enrollment
                   11860: 
                   11861: Change a students enrollment status in a class.  The environment variable
                   11862: 'role.request.course' must be defined for this function to proceed.
                   11863: 
                   11864: Inputs:
                   11865: 
                   11866: =over 4
                   11867: 
                   11868: =item $udom, students domain
                   11869: 
                   11870: =item $uname, students name
                   11871: 
                   11872: =item $uid, students user id
                   11873: 
                   11874: =item $first, students first name
                   11875: 
                   11876: =item $middle
                   11877: 
                   11878: =item $last
                   11879: 
                   11880: =item $gene
                   11881: 
                   11882: =item $usec
                   11883: 
                   11884: =item $end
                   11885: 
                   11886: =item $start
                   11887: 
1.957     raeburn  11888: =item $type
                   11889: 
                   11890: =item $locktype
                   11891: 
                   11892: =item $cid
                   11893: 
                   11894: =item $selfenroll
                   11895: 
                   11896: =item $context
                   11897: 
1.297     matthew  11898: =back
                   11899: 
1.191     harris41 11900: 
                   11901: =item *
                   11902: 
1.243     albertel 11903: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11904: custom role; give a custom role to a user for the level given by URL.  Specify
                   11905: name and domain of role author, and role name
1.191     harris41 11906: 
                   11907: =item *
                   11908: 
1.243     albertel 11909: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11910: 
                   11911: =item *
                   11912: 
1.243     albertel 11913: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11914: 
                   11915: =back
                   11916: 
                   11917: =head2 Course Infomation
                   11918: 
                   11919: =over 4
1.191     harris41 11920: 
                   11921: =item *
                   11922: 
1.1118    foxr     11923: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11924: specified course id, including all environment settings for the
                   11925: course, the description of the course will be in the hash under the
                   11926: key 'description'
1.191     harris41 11927: 
1.1118    foxr     11928: $options is an optional parameter that if supplied is a hash reference that controls
                   11929: what how this function works.  It has the following key/values:
                   11930: 
                   11931: =over 4
                   11932: 
                   11933: =item freshen_cache
                   11934: 
                   11935: If defined, and the environment cache for the course is valid, it is 
                   11936: returned in the returned hash.
                   11937: 
                   11938: =item one_time
                   11939: 
                   11940: If defined, the last cache time is set to _now_
                   11941: 
                   11942: =item user
                   11943: 
                   11944: If defined, the supplied username is used instead of the current user.
                   11945: 
                   11946: 
                   11947: =back
                   11948: 
1.191     harris41 11949: =item *
                   11950: 
1.624     albertel 11951: resdata($name,$domain,$type,@which) : request for current parameter
                   11952: setting for a specific $type, where $type is either 'course' or 'user',
                   11953: @what should be a list of parameters to ask about. This routine caches
                   11954: answers for 5 minutes.
1.243     albertel 11955: 
1.877     foxr     11956: =item *
                   11957: 
                   11958: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11959: data base, returning a hash that is keyed by the resource name and has
                   11960: values that are the resource value.  I believe that the timestamps and
                   11961: versions are also returned.
                   11962: 
                   11963: 
1.243     albertel 11964: =back
                   11965: 
                   11966: =head2 Course Modification
                   11967: 
                   11968: =over 4
1.191     harris41 11969: 
                   11970: =item *
                   11971: 
1.243     albertel 11972: writecoursepref($courseid,%prefs) : write preferences (environment
                   11973: database) for a course
1.191     harris41 11974: 
                   11975: =item *
                   11976: 
1.1011    raeburn  11977: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11978: 
                   11979: =item *
                   11980: 
1.1038    raeburn  11981: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11982: 
1.1167    droeschl 11983: =item *
                   11984: 
                   11985: is_course($courseid), is_course($cdom, $cnum)
                   11986: 
                   11987: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   11988: two component version $cdom, $cnum. It checks if the specified course exists.
                   11989: 
                   11990: Returns:
                   11991:     undef if the course doesn't exist, otherwise
                   11992:     in scalar context the combined courseid.
                   11993:     in list context the two components of the course identifier, domain and 
                   11994:     courseid.    
                   11995: 
1.243     albertel 11996: =back
                   11997: 
                   11998: =head2 Resource Subroutines
                   11999: 
                   12000: =over 4
1.191     harris41 12001: 
                   12002: =item *
                   12003: 
1.243     albertel 12004: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12005: 
                   12006: =item *
                   12007: 
1.243     albertel 12008: repcopy($filename) : subscribes to the requested file, and attempts to
                   12009: replicate from the owning library server, Might return
1.607     raeburn  12010: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12011: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12012: resource. Expects the local filesystem pathname
                   12013: (/home/httpd/html/res/....)
                   12014: 
                   12015: =back
                   12016: 
                   12017: =head2 Resource Information
                   12018: 
                   12019: =over 4
1.191     harris41 12020: 
                   12021: =item *
                   12022: 
1.243     albertel 12023: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12024: a vairety of different possible values, $varname should be a request
                   12025: string, and the other parameters can be used to specify who and what
                   12026: one is asking about.
                   12027: 
                   12028: Possible values for $varname are environment.lastname (or other item
                   12029: from the envirnment hash), user.name (or someother aspect about the
                   12030: user), resource.0.maxtries (or some other part and parameter of a
                   12031: resource)
1.204     albertel 12032: 
                   12033: =item *
                   12034: 
1.243     albertel 12035: directcondval($number) : get current value of a condition; reads from a state
                   12036: string
1.204     albertel 12037: 
                   12038: =item *
                   12039: 
1.243     albertel 12040: condval($condidx) : value of condition index based on state
1.204     albertel 12041: 
                   12042: =item *
                   12043: 
1.243     albertel 12044: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12045: resource's metadata, $what should be either a specific key, or either
                   12046: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12047: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12048: 
                   12049: this function automatically caches all requests
1.191     harris41 12050: 
                   12051: =item *
                   12052: 
1.243     albertel 12053: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12054: network of library servers; returns file handle of where SQL and regex results
                   12055: will be stored for query
1.191     harris41 12056: 
                   12057: =item *
                   12058: 
1.243     albertel 12059: symbread($filename) : return symbolic list entry (filename argument optional);
                   12060: returns the data handle
1.191     harris41 12061: 
                   12062: =item *
                   12063: 
1.243     albertel 12064: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12065: a possible symb for the URL in $thisfn, and if is an encryypted
                   12066: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12067: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12068: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12069: 
1.191     harris41 12070: 
                   12071: =item *
                   12072: 
1.243     albertel 12073: symbclean($symb) : removes versions numbers from a symb, returns the
                   12074: cleaned symb
1.191     harris41 12075: 
                   12076: =item *
                   12077: 
1.243     albertel 12078: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12079: course map, user must be in a course for it to work.
1.191     harris41 12080: 
                   12081: =item *
                   12082: 
1.243     albertel 12083: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12084: 
                   12085: =item *
                   12086: 
1.243     albertel 12087: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12088: a random seed, all arguments are optional, if they aren't sent it uses the
                   12089: environment to derive them. Note: if symb isn't sent and it can't get one
                   12090: from &symbread it will use the current time as its return value
1.191     harris41 12091: 
                   12092: =item *
                   12093: 
1.243     albertel 12094: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12095: unfakeable, receipt
1.191     harris41 12096: 
                   12097: =item *
                   12098: 
1.620     albertel 12099: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12100: 
                   12101: =item *
                   12102: 
1.243     albertel 12103: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12104: 
                   12105: =item *
                   12106: 
1.243     albertel 12107: 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 12108: 
                   12109: =item *
                   12110: 
1.243     albertel 12111: 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 12112: 
                   12113: =item *
                   12114: 
1.243     albertel 12115: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12116: 
                   12117: =item *
                   12118: 
1.243     albertel 12119: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12120: forcing spreadsheet to reevaluate the resource scores next time.
                   12121: 
                   12122: =back
                   12123: 
                   12124: =head2 Storing/Retreiving Data
                   12125: 
                   12126: =over 4
1.191     harris41 12127: 
                   12128: =item *
                   12129: 
1.243     albertel 12130: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12131: for this url; hashref needs to be given and should be a \%hashname; the
                   12132: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12133: be derived from the env
1.191     harris41 12134: 
                   12135: =item *
                   12136: 
1.243     albertel 12137: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12138: uses critical subroutine
1.191     harris41 12139: 
                   12140: =item *
                   12141: 
1.243     albertel 12142: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12143: all args are optional
1.191     harris41 12144: 
                   12145: =item *
                   12146: 
1.717     albertel 12147: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12148: dumps the complete (or key matching regexp) namespace into a hash
                   12149: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12150: normally &store()ed into
                   12151: 
                   12152: $range should be either an integer '100' (give me the first 100
                   12153:                                            matching records)
                   12154:               or be  two integers sperated by a - with no spaces
                   12155:                  '30-50' (give me the 30th through the 50th matching
                   12156:                           records)
                   12157: 
                   12158: 
                   12159: =item *
                   12160: 
                   12161: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12162: replaces a &store() version of data with a replacement set of data
                   12163: for a particular resource in a namespace passed in the $storehash hash 
                   12164: reference
                   12165: 
                   12166: =item *
                   12167: 
1.243     albertel 12168: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12169: works very similar to store/cstore, but all data is stored in a
                   12170: temporary location and can be reset using tmpreset, $storehash should
                   12171: be a hash reference, returns nothing on success
1.191     harris41 12172: 
                   12173: =item *
                   12174: 
1.243     albertel 12175: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12176: similar to restore, but all data is stored in a temporary location and
                   12177: can be reset using tmpreset. Returns a hash of values on success,
                   12178: error string otherwise.
1.191     harris41 12179: 
                   12180: =item *
                   12181: 
1.243     albertel 12182: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12183: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12184: 
                   12185: =item *
                   12186: 
1.243     albertel 12187: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12188: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12189: 
                   12190: =item *
                   12191: 
1.243     albertel 12192: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12193: namesp ($udom and $uname are optional)
1.191     harris41 12194: 
                   12195: =item *
                   12196: 
1.702     albertel 12197: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12198: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12199: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12200: 
1.702     albertel 12201: $range should be either an integer '100' (give me the first 100
                   12202:                                            matching records)
                   12203:               or be  two integers sperated by a - with no spaces
                   12204:                  '30-50' (give me the 30th through the 50th matching
                   12205:                           records)
1.449     matthew  12206: =item *
                   12207: 
                   12208: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12209: $store can be a scalar, an array reference, or if the amount to be 
                   12210: incremented is > 1, a hash reference.
                   12211: 
                   12212: ($udom and $uname are optional)
1.191     harris41 12213: 
                   12214: =item *
                   12215: 
1.243     albertel 12216: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12217: ($udom and $uname are optional)
1.191     harris41 12218: 
                   12219: =item *
                   12220: 
1.243     albertel 12221: cput($namespace,$storehash,$udom,$uname) : critical put
                   12222: ($udom and $uname are optional)
1.191     harris41 12223: 
                   12224: =item *
                   12225: 
1.748     albertel 12226: newput($namespace,$storehash,$udom,$uname) :
                   12227: 
                   12228: Attempts to store the items in the $storehash, but only if they don't
                   12229: currently exist, if this succeeds you can be certain that you have 
                   12230: successfully created a new key value pair in the $namespace db.
                   12231: 
                   12232: 
                   12233: Args:
                   12234:  $namespace: name of database to store values to
                   12235:  $storehash: hashref to store to the db
                   12236:  $udom: (optional) domain of user containing the db
                   12237:  $uname: (optional) name of user caontaining the db
                   12238: 
                   12239: Returns:
                   12240:  'ok' -> succeeded in storing all keys of $storehash
                   12241:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12242:                         least <key> already existed in the db (other
                   12243:                         requested keys may also already exist)
1.967     bisitz   12244:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12245:  'con_lost' -> unable to contact request server
                   12246:  'refused' -> action was not allowed by remote machine
                   12247: 
                   12248: 
                   12249: =item *
                   12250: 
1.243     albertel 12251: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12252: reference filled in from namesp (encrypts the return communication)
                   12253: ($udom and $uname are optional)
1.191     harris41 12254: 
                   12255: =item *
                   12256: 
1.243     albertel 12257: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12258: critical subroutine
                   12259: 
1.806     raeburn  12260: =item *
                   12261: 
1.860     raeburn  12262: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12263: array reference filled in from namespace found in domain level on either
                   12264: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12265: 
                   12266: =item *
                   12267: 
1.860     raeburn  12268: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12269: domain level either on specified domain server ($uhome) or primary domain 
                   12270: server ($udom and $uhome are optional)
1.806     raeburn  12271: 
1.943     raeburn  12272: =item * 
                   12273: 
                   12274: get_domain_defaults($target_domain) : returns hash with defaults for
                   12275: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12276: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12277: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12278: Values are retrieved from cache (if current), or from domain's configuration.db
                   12279: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12280: or lonTabs/domain.tab. 
                   12281: 
                   12282: %domdefaults = &get_auth_defaults($target_domain);
                   12283: 
1.243     albertel 12284: =back
                   12285: 
                   12286: =head2 Network Status Functions
                   12287: 
                   12288: =over 4
1.191     harris41 12289: 
                   12290: =item *
                   12291: 
1.1137    raeburn  12292: dirlist() : return directory list based on URI (first arg).
                   12293: 
                   12294: Inputs: 1 required, 5 optional.
                   12295: 
                   12296: =over
                   12297: 
                   12298: =item 
                   12299: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12300: 
                   12301: =item
                   12302: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12303: 
                   12304: =item
                   12305: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12306: 
                   12307: =item
                   12308: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12309: 
                   12310: =item
                   12311: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12312: 
                   12313: =item 
                   12314: $alternateRoot - path to prepend in place of path from $uri.
                   12315: 
                   12316: =back
                   12317: 
                   12318: Returns: Array of up to two items.
                   12319: 
                   12320: =over
                   12321: 
                   12322: a reference to an array of files/subdirectories
                   12323: 
                   12324: =over
                   12325: 
                   12326: Each element in the array of files/subdirectories is a & separated list of
                   12327: item name and the result of running stat on the item.  If dirlist was requested
                   12328: for a file instead of a directory, the item name will be ''. For a directory 
                   12329: listing, if the item is a metadata file, the element will end &N&M 
                   12330: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12331: default copyright set (1).  
                   12332: 
                   12333: =back
                   12334: 
                   12335: a scalar containing error condition (if encountered).
                   12336: 
                   12337: =over
                   12338: 
                   12339: =item 
                   12340: no_host (no homeserver identified for $username:$domain).
                   12341: 
                   12342: =item 
                   12343: no_such_host (server contacted for listing not identified as valid host).
                   12344: 
                   12345: =item 
                   12346: con_lost (connection to remote server failed).
                   12347: 
                   12348: =item 
                   12349: refused (invalid $username:$domain received on lond side).
                   12350: 
                   12351: =item 
                   12352: no_such_dir (directory at specified path on lond side does not exist). 
                   12353: 
                   12354: =item 
                   12355: empty (directory at specified path on lond side is empty).
                   12356: 
                   12357: =over
                   12358: 
                   12359: This is currently not encountered because the &ls3, &ls2, 
                   12360: &ls (_handler) routines on the lond side do not filter out
                   12361: . and .. from a directory listing. 
                   12362: 
                   12363: =back
                   12364: 
                   12365: =back
                   12366: 
                   12367: =back
1.191     harris41 12368: 
                   12369: =item *
                   12370: 
1.243     albertel 12371: spareserver() : find server with least workload from spare.tab
                   12372: 
1.986     foxr     12373: 
                   12374: =item *
                   12375: 
                   12376: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12377: if there is no corresponding loncapa host.
                   12378: 
1.243     albertel 12379: =back
                   12380: 
1.986     foxr     12381: 
1.243     albertel 12382: =head2 Apache Request
                   12383: 
                   12384: =over 4
1.191     harris41 12385: 
                   12386: =item *
                   12387: 
1.243     albertel 12388: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12389: localhost, posts hash
                   12390: 
                   12391: =back
                   12392: 
                   12393: =head2 Data to String to Data
                   12394: 
                   12395: =over 4
1.191     harris41 12396: 
                   12397: =item *
                   12398: 
1.243     albertel 12399: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12400: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12401: 
                   12402: =item *
                   12403: 
1.243     albertel 12404: hashref2str($hashref) : convert a hashref into a string complete with
                   12405: escaping and '=' and '&' separators, supports elements that are
                   12406: arrayrefs and hashrefs
1.191     harris41 12407: 
                   12408: =item *
                   12409: 
1.243     albertel 12410: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12411: with escaping and '&' separators, supports elements that are arrayrefs
                   12412: and hashrefs
1.191     harris41 12413: 
                   12414: =item *
                   12415: 
1.243     albertel 12416: str2hash($string) : convert string to hash using unescaping and
                   12417: splitting on '=' and '&', supports elements that are arrayrefs and
                   12418: hashrefs
1.191     harris41 12419: 
                   12420: =item *
                   12421: 
1.243     albertel 12422: str2array($string) : convert string to hash using unescaping and
                   12423: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12424: 
                   12425: =back
                   12426: 
                   12427: =head2 Logging Routines
                   12428: 
                   12429: 
                   12430: These routines allow one to make log messages in the lonnet.log and
                   12431: lonnet.perm logfiles.
1.191     harris41 12432: 
1.1119    foxr     12433: =over 4
                   12434: 
1.191     harris41 12435: =item *
                   12436: 
1.243     albertel 12437: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12438: 
                   12439: =item *
                   12440: 
1.243     albertel 12441: logthis() : append message to the normal lonnet.log file, it gets
                   12442: preiodically rolled over and deleted.
1.191     harris41 12443: 
                   12444: =item *
                   12445: 
1.243     albertel 12446: logperm() : append a permanent message to lonnet.perm.log, this log
                   12447: file never gets deleted by any automated portion of the system, only
                   12448: messages of critical importance should go in here.
                   12449: 
1.1119    foxr     12450: 
1.243     albertel 12451: =back
                   12452: 
                   12453: =head2 General File Helper Routines
                   12454: 
                   12455: =over 4
1.191     harris41 12456: 
                   12457: =item *
                   12458: 
1.481     raeburn  12459: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12460: (a) files in /uploaded
                   12461:   (i) If a local copy of the file exists - 
                   12462:       compares modification date of local copy with last-modified date for 
                   12463:       definitive version stored on home server for course. If local copy is 
                   12464:       stale, requests a new version from the home server and stores it. 
                   12465:       If the original has been removed from the home server, then local copy 
                   12466:       is unlinked.
                   12467:   (ii) If local copy does not exist -
                   12468:       requests the file from the home server and stores it. 
                   12469:   
                   12470:   If $caller is 'uploadrep':  
                   12471:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12472:     for request for files originally uploaded via DOCS. 
                   12473:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12474:   
                   12475:   Otherwise:
                   12476:      This indicates a call from the content generation phase of the request.
                   12477:      -  returns the entire contents of the file or -1.
                   12478:      
                   12479: (b) files in /res
                   12480:    - returns the entire contents of a file or -1; 
                   12481:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12482: 
1.712     albertel 12483: 
                   12484: =item *
                   12485: 
                   12486: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12487:                   reference
                   12488: 
                   12489: returns either a stat() list of data about the file or an empty list
                   12490: if the file doesn't exist or couldn't find out about it (connection
                   12491: problems or user unknown)
                   12492: 
1.191     harris41 12493: =item *
                   12494: 
1.243     albertel 12495: filelocation($dir,$file) : returns file system location of a file
                   12496: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12497: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12498: and a file of ../bob will become /a/bob)
1.191     harris41 12499: 
                   12500: =item *
                   12501: 
                   12502: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12503: filelocation except for hrefs
                   12504: 
                   12505: =item *
                   12506: 
                   12507: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12508: 
1.243     albertel 12509: =back
                   12510: 
1.608     albertel 12511: =head2 Usererfile file routines (/uploaded*)
                   12512: 
                   12513: =over 4
                   12514: 
                   12515: =item *
                   12516: 
                   12517: userfileupload(): main rotine for putting a file in a user or course's
                   12518:                   filespace, arguments are,
                   12519: 
1.620     albertel 12520:  formname - required - this is the name of the element in $env where the
1.608     albertel 12521:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12522:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12523:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12524:  context - if coursedoc, store the file in the course of the active role
                   12525:              of the current user; 
                   12526:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12527:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12528:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12529:          if undefined, it will be placed in "unknown"
                   12530: 
                   12531:  (This routine calls clean_filename() to remove any dangerous
                   12532:  characters from the filename, and then calls finuserfileupload() to
                   12533:  complete the transaction)
                   12534: 
                   12535:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12536:  and /adm/notfound.html if unsuccessful
                   12537: 
                   12538: =item *
                   12539: 
                   12540: clean_filename(): routine for cleaing a filename up for storage in
                   12541:                  userfile space, argument is:
                   12542: 
                   12543:  filename - proposed filename
                   12544: 
                   12545: returns: the new clean filename
                   12546: 
                   12547: =item *
                   12548: 
1.1090    raeburn  12549: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12550: userspace, probably shouldn't be called directly
                   12551: 
                   12552:   docuname: username or courseid of destination for the file
                   12553:   docudom: domain of user/course of destination for the file
                   12554:   formname: same as for userfileupload()
1.1090    raeburn  12555:   fname: filename (including subdirectories) for the file
                   12556:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12557:   allfiles: reference to hash used to store objects found by parser
                   12558:   codebase: reference to hash used for codebases of java objects found by parser
                   12559:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12560:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12561:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12562:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12563:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12564:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12565:   mimetype: reference to scalar to accommodate mime type determined
                   12566:             from File::MMagic if $parser = parse.
1.608     albertel 12567: 
                   12568:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12569:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12570:  was 'overwrite').
                   12571:  
1.608     albertel 12572: 
                   12573: =item *
                   12574: 
                   12575: renameuserfile(): renames an existing userfile to a new name
                   12576: 
                   12577:   Args:
                   12578:    docuname: username or courseid of destination for the file
                   12579:    docudom: domain of user/course of destination for the file
                   12580:    old: current file name (including any subdirs under userfiles)
                   12581:    new: desired file name (including any subdirs under userfiles)
                   12582: 
                   12583: =item *
                   12584: 
                   12585: mkdiruserfile(): creates a directory is a userfiles dir
                   12586: 
                   12587:   Args:
                   12588:    docuname: username or courseid of destination for the file
                   12589:    docudom: domain of user/course of destination for the file
                   12590:    dir: dir to create (including any subdirs under userfiles)
                   12591: 
                   12592: =item *
                   12593: 
                   12594: removeuserfile(): removes a file that exists in userfiles
                   12595: 
                   12596:   Args:
                   12597:    docuname: username or courseid of destination for the file
                   12598:    docudom: domain of user/course of destination for the file
                   12599:    fname: filname to delete (including any subdirs under userfiles)
                   12600: 
                   12601: =item *
                   12602: 
                   12603: removeuploadedurl(): convience function for removeuserfile()
                   12604: 
                   12605:   Args:
                   12606:    url:  a full /uploaded/... url to delete
                   12607: 
1.747     albertel 12608: =item * 
                   12609: 
                   12610: get_portfile_permissions():
                   12611:   Args:
                   12612:     domain: domain of user or course contain the portfolio files
                   12613:     user: name of user or num of course contain the portfolio files
                   12614:   Returns:
                   12615:     hashref of a dump of the proper file_permissions.db
                   12616:    
                   12617: 
                   12618: =item * 
                   12619: 
                   12620: get_access_controls():
                   12621: 
                   12622: Args:
                   12623:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12624:   group: (optional) the group you want the files associated with
                   12625:   file: (optional) the file you want access info on
                   12626: 
                   12627: Returns:
1.749     raeburn  12628:     a hash (keys are file names) of hashes containing
                   12629:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12630:         values are XML containing access control settings (see below) 
1.747     albertel 12631: 
                   12632: Internal notes:
                   12633: 
1.749     raeburn  12634:  access controls are stored in file_permissions.db as key=value pairs.
                   12635:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12636:         where scope -> public,guest,course,group,domains or users.
                   12637:               end -> UNIX time for end of access (0 -> no end date)
                   12638:               start -> UNIX time for start of access
                   12639: 
                   12640:     value -> XML description of access control
                   12641:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12642:             <start></start>
                   12643:             <end></end>
                   12644: 
                   12645:             <password></password>  for scope type = guest
                   12646: 
                   12647:             <domain></domain>     for scope type = course or group
                   12648:             <number></number>
                   12649:             <roles id="">
                   12650:              <role></role>
                   12651:              <access></access>
                   12652:              <section></section>
                   12653:              <group></group>
                   12654:             </roles>
                   12655: 
                   12656:             <dom></dom>         for scope type = domains
                   12657: 
                   12658:             <users>             for scope type = users
                   12659:              <user>
                   12660:               <uname></uname>
                   12661:               <udom></udom>
                   12662:              </user>
                   12663:             </users>
                   12664:            </scope> 
                   12665:               
                   12666:  Access data is also aggregated for each file in an additional key=value pair:
                   12667:  key -> path to file/file_name\0accesscontrol 
                   12668:  value -> reference to hash
                   12669:           hash contains key = value pairs
                   12670:           where key = uniqueID:scope_end_start
                   12671:                 value = UNIX time record was last updated
                   12672: 
                   12673:           Used to improve speed of look-ups of access controls for each file.  
                   12674:  
                   12675:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12676: 
                   12677: modify_access_controls():
                   12678: 
                   12679: Modifies access controls for a portfolio file
                   12680: Args
                   12681: 1. file name
                   12682: 2. reference to hash of required changes,
                   12683: 3. domain
                   12684: 4. username
                   12685:   where domain,username are the domain of the portfolio owner 
                   12686:   (either a user or a course) 
                   12687: 
                   12688: Returns:
                   12689: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12690: 2. result of deletions ('ok' or 'error', with error message).
                   12691: 3. reference to hash of any new or updated access controls.
                   12692: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12693:    key = integer (inbound ID)
                   12694:    value = uniqueID  
1.747     albertel 12695: 
1.608     albertel 12696: =back
                   12697: 
1.243     albertel 12698: =head2 HTTP Helper Routines
                   12699: 
                   12700: =over 4
                   12701: 
1.191     harris41 12702: =item *
                   12703: 
                   12704: escape() : unpack non-word characters into CGI-compatible hex codes
                   12705: 
                   12706: =item *
                   12707: 
                   12708: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12709: 
1.243     albertel 12710: =back
                   12711: 
                   12712: =head1 PRIVATE SUBROUTINES
                   12713: 
                   12714: =head2 Underlying communication routines (Shouldn't call)
                   12715: 
                   12716: =over 4
                   12717: 
                   12718: =item *
                   12719: 
                   12720: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12721: 
                   12722: =item *
                   12723: 
                   12724: reply() : uses subreply to send a message to remote machine, logs all failures
                   12725: 
                   12726: =item *
                   12727: 
                   12728: critical() : passes a critical message to another server; if cannot
                   12729: get through then place message in connection buffer directory and
                   12730: returns con_delayed, if incapable of saving message, returns
                   12731: con_failed
                   12732: 
                   12733: =item *
                   12734: 
                   12735: reconlonc() : tries to reconnect lonc client processes.
                   12736: 
                   12737: =back
                   12738: 
                   12739: =head2 Resource Access Logging
                   12740: 
                   12741: =over 4
                   12742: 
                   12743: =item *
                   12744: 
                   12745: flushcourselogs() : flush (save) buffer logs and access logs
                   12746: 
                   12747: =item *
                   12748: 
                   12749: courselog($what) : save message for course in hash
                   12750: 
                   12751: =item *
                   12752: 
                   12753: courseacclog($what) : save message for course using &courselog().  Perform
                   12754: special processing for specific resource types (problems, exams, quizzes, etc).
                   12755: 
1.191     harris41 12756: =item *
                   12757: 
                   12758: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12759: as a PerlChildExitHandler
1.243     albertel 12760: 
                   12761: =back
                   12762: 
                   12763: =head2 Other
                   12764: 
                   12765: =over 4
                   12766: 
                   12767: =item *
                   12768: 
                   12769: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12770: 
                   12771: =back
                   12772: 
                   12773: =cut
1.877     foxr     12774: 

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