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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1127  ! raeburn     4: # $Id: lonnet.pm,v 1.1126 2011/08/09 00:28:51 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1117    foxr       98: 
1.1090    raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1106    raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1073    raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1073    raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   258:                     $ua->timeout(4);
1.1073    raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1081    raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1081    raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   274:                 $loncaparev = $1;
                    275:             }
1.993     raeburn   276:         }
1.1073    raeburn   277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   278:     }
                    279: }
                    280: 
1.1074    raeburn   281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    285:         if (defined($cached)) {
                    286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') { 
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
                    299:         }
                    300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
                    305:     }
                    306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    307: }
                    308: 
1.1121    raeburn   309: sub get_remote_globals {
                    310:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   311:     my ($result,%returnhash,%whatneeded);
                    312:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   313:         foreach my $what (sort(keys(%{$whathash}))) {
                    314:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   315:             my ($response,$cached);
1.1121    raeburn   316:             unless ($ignore_cache) {
1.1125    raeburn   317:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   318:             }
                    319:             if (defined($cached)) {
1.1125    raeburn   320:                 $returnhash{$what} = $response;
1.1121    raeburn   321:             } else {
1.1125    raeburn   322:                 $whatneeded{$what} = 1;
1.1121    raeburn   323:             }
                    324:         }
1.1125    raeburn   325:         if (keys(%whatneeded) == 0) {
                    326:             $result = 'ok';
                    327:         } else {
1.1121    raeburn   328:             my $requested = &freeze_escape(\%whatneeded);
                    329:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   330:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    331:                 ($rep eq 'unknown_cmd')) {
                    332:                 $result = $rep;
                    333:             } else {
                    334:                 $result = 'ok';
1.1121    raeburn   335:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   336:                 foreach my $item (@pairs) {
                    337:                     my ($key,$value)=split(/=/,$item,2);
                    338:                     my $what = &unescape($key);
                    339:                     my $hashid = $lonhost.'-'.$what;
                    340:                     $returnhash{$what}=&thaw_unescape($value);
                    341:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   342:                 }
                    343:             }
                    344:         }
                    345:     }
1.1125    raeburn   346:     return ($result,\%returnhash);
1.1121    raeburn   347: }
                    348: 
1.1124    raeburn   349: sub remote_devalidate_cache {
                    350:     my ($lonhost,$name,$id) = @_;
                    351:     my $response = &reply('devalidatecache',&escape($name).':'.&escape($id),$lonhost);
                    352:     return $response;
                    353: }
                    354: 
1.1       albertel  355: # -------------------------------------------------- Non-critical communication
                    356: sub subreply {
                    357:     my ($cmd,$server)=@_;
1.838     albertel  358:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      359:     #
                    360:     #  With loncnew process trimming, there's a timing hole between lonc server
                    361:     #  process exit and the master server picking up the listen on the AF_UNIX
                    362:     #  socket.  In that time interval, a lock file will exist:
                    363: 
                    364:     my $lockfile=$peerfile.".lock";
                    365:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    366: 	sleep(1);
                    367:     }
                    368:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      369:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      370:     #
1.550     foxr      371:     #   We'll give the connection a few tries before abandoning it.  If
                    372:     #   connection is not possible, we'll con_lost back to the client.
                    373:     #   
                    374:     my $client;
                    375:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    376: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    377: 				      Type    => SOCK_STREAM,
                    378: 				      Timeout => 10);
1.869     albertel  379: 	if ($client) {
1.550     foxr      380: 	    last;		# Connected!
1.850     albertel  381: 	} else {
1.853     albertel  382: 	    &create_connection(&hostname($server),$server);
1.550     foxr      383: 	}
1.850     albertel  384:         sleep(1);		# Try again later if failed connection.
1.550     foxr      385:     }
                    386:     my $answer;
                    387:     if ($client) {
1.704     albertel  388: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      389: 	$answer=<$client>;
                    390: 	if (!$answer) { $answer="con_lost"; }
                    391: 	chomp($answer);
                    392:     } else {
                    393: 	$answer = 'con_lost';	# Failed connection.
                    394:     }
1.1       albertel  395:     return $answer;
                    396: }
                    397: 
                    398: sub reply {
                    399:     my ($cmd,$server)=@_;
1.838     albertel  400:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  401:     my $answer=subreply($cmd,$server);
1.65      www       402:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  403:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       404:                 " $cmd to $server returned $answer</font>");
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: # ----------------------------------------------------------- Send USR1 to lonc
                    410: 
                    411: sub reconlonc {
1.891     albertel  412:     my ($lonid) = @_;
                    413:     my $hostname = &hostname($lonid);
                    414:     if ($lonid) {
                    415: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    416: 	if ($hostname && -e $peerfile) {
                    417: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    418: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    419: 					     Type    => SOCK_STREAM,
                    420: 					     Timeout => 10);
                    421: 	    if ($client) {
                    422: 		print $client ("reset_retries\n");
                    423: 		my $answer=<$client>;
                    424: 		#reset just this one.
                    425: 	    }
                    426: 	}
                    427: 	return;
                    428:     }
                    429: 
1.836     www       430:     &logthis("Trying to reconnect lonc");
1.1       albertel  431:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  432:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  433: 	my $loncpid=<$fh>;
                    434:         chomp($loncpid);
                    435:         if (kill 0 => $loncpid) {
                    436: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    437:             kill USR1 => $loncpid;
                    438:             sleep 1;
1.836     www       439:          } else {
1.12      www       440: 	    &logthis(
1.672     albertel  441:                "<font color=\"blue\">WARNING:".
1.12      www       442:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  443:         }
                    444:     } else {
1.836     www       445: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  446:     }
                    447: }
                    448: 
                    449: # ------------------------------------------------------ Critical communication
1.12      www       450: 
1.1       albertel  451: sub critical {
                    452:     my ($cmd,$server)=@_;
1.838     albertel  453:     unless (&hostname($server)) {
1.672     albertel  454:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       455:                " Critical message to unknown server ($server)</font>");
                    456:         return 'no_such_host';
                    457:     }
1.1       albertel  458:     my $answer=reply($cmd,$server);
                    459:     if ($answer eq 'con_lost') {
                    460: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  461: 	my $answer=reply($cmd,$server);
1.1       albertel  462:         if ($answer eq 'con_lost') {
                    463:             my $now=time;
                    464:             my $middlename=$cmd;
1.5       www       465:             $middlename=substr($middlename,0,16);
1.1       albertel  466:             $middlename=~s/\W//g;
                    467:             my $dfilename=
1.305     www       468:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    469:             $dumpcount++;
1.1       albertel  470:             {
1.448     albertel  471: 		my $dfh;
                    472: 		if (open($dfh,">$dfilename")) {
                    473: 		    print $dfh "$cmd\n"; 
                    474: 		    close($dfh);
                    475: 		}
1.1       albertel  476:             }
                    477:             sleep 2;
                    478:             my $wcmd='';
                    479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,"<$dfilename")) {
                    482: 		    $wcmd=<$dfh>; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             chomp($wcmd);
1.7       www       487:             if ($wcmd eq $cmd) {
1.672     albertel  488: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       489:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  490:                 &logperm("D:$server:$cmd");
                    491: 	        return 'con_delayed';
                    492:             } else {
1.672     albertel  493:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       494:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  495:                 &logperm("F:$server:$cmd");
                    496:                 return 'con_failed';
                    497:             }
                    498:         }
                    499:     }
                    500:     return $answer;
1.405     albertel  501: }
                    502: 
1.755     albertel  503: # ------------------------------------------- check if return value is an error
                    504: 
                    505: sub error {
                    506:     my ($result) = @_;
1.756     albertel  507:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  508: 	if ($2 == 2) { return undef; }
                    509: 	return $1;
                    510:     }
                    511:     return undef;
                    512: }
                    513: 
1.783     albertel  514: sub convert_and_load_session_env {
                    515:     my ($lonidsdir,$handle)=@_;
                    516:     my @profile;
                    517:     {
1.917     albertel  518: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    519: 	if (!$opened) {
1.915     albertel  520: 	    return 0;
                    521: 	}
1.783     albertel  522: 	flock($idf,LOCK_SH);
                    523: 	@profile=<$idf>;
                    524: 	close($idf);
                    525:     }
                    526:     my %temp_env;
                    527:     foreach my $line (@profile) {
1.786     albertel  528: 	if ($line !~ m/=/) {
                    529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	chomp($line);
                    532: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    533: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    534:     }
                    535:     unlink("$lonidsdir/$handle.id");
                    536:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    537: 	    0640)) {
                    538: 	%disk_env = %temp_env;
                    539: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    540: 	untie(%disk_env);
                    541:     }
1.786     albertel  542:     return 1;
1.783     albertel  543: }
                    544: 
1.374     www       545: # ------------------------------------------- Transfer profile into environment
1.780     albertel  546: my $env_loaded;
                    547: sub transfer_profile_to_env {
1.788     albertel  548:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    549:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       550: 
1.720     albertel  551:     if (!defined($lonidsdir)) {
                    552: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    553:     }
                    554:     if (!defined($handle)) {
                    555:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    556:     }
                    557: 
1.786     albertel  558:     my $convert;
                    559:     {
1.917     albertel  560:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561: 	if (!$opened) {
1.915     albertel  562: 	    return;
                    563: 	}
1.786     albertel  564: 	flock($idf,LOCK_SH);
                    565: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 		&GDBM_READER(),0640)) {
                    567: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    568: 	    untie(%disk_env);
                    569: 	} else {
                    570: 	    $convert = 1;
                    571: 	}
                    572:     }
                    573:     if ($convert) {
                    574: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    575: 	    &logthis("Failed to load session, or convert session.");
                    576: 	}
1.374     www       577:     }
1.783     albertel  578: 
1.786     albertel  579:     my %remove;
1.783     albertel  580:     while ( my $envname = each(%env) ) {
1.433     matthew   581:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    582:             if ($time < time-300) {
1.783     albertel  583:                 $remove{$key}++;
1.433     matthew   584:             }
                    585:         }
                    586:     }
1.783     albertel  587: 
1.619     albertel  588:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  589:     $env_loaded=1;
1.783     albertel  590:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   591:         &delenv($expired_key);
1.374     www       592:     }
1.1       albertel  593: }
                    594: 
1.916     albertel  595: # ---------------------------------------------------- Check for valid session 
                    596: sub check_for_valid_session {
                    597:     my ($r) = @_;
                    598:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    599:     my $lonid=$cookies{'lonID'};
                    600:     return undef if (!$lonid);
                    601: 
                    602:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    603:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    604:     return undef if (!-e "$lonidsdir/$handle.id");
                    605: 
1.917     albertel  606:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    607:     return undef if (!$opened);
1.916     albertel  608: 
                    609:     flock($idf,LOCK_SH);
                    610:     my %disk_env;
                    611:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    612: 	    &GDBM_READER(),0640)) {
                    613: 	return undef;	
                    614:     }
                    615: 
                    616:     if (!defined($disk_env{'user.name'})
                    617: 	|| !defined($disk_env{'user.domain'})) {
                    618: 	return undef;
                    619:     }
                    620:     return $handle;
                    621: }
                    622: 
1.830     albertel  623: sub timed_flock {
                    624:     my ($file,$lock_type) = @_;
                    625:     my $failed=0;
                    626:     eval {
                    627: 	local $SIG{__DIE__}='DEFAULT';
                    628: 	local $SIG{ALRM}=sub {
                    629: 	    $failed=1;
                    630: 	    die("failed lock");
                    631: 	};
                    632: 	alarm(13);
                    633: 	flock($file,$lock_type);
                    634: 	alarm(0);
                    635:     };
                    636:     if ($failed) {
                    637: 	return undef;
                    638:     } else {
                    639: 	return 1;
                    640:     }
                    641: }
                    642: 
1.5       www       643: # ---------------------------------------------------------- Append Environment
                    644: 
                    645: sub appenv {
1.949     raeburn   646:     my ($newenv,$roles) = @_;
                    647:     if (ref($newenv) eq 'HASH') {
                    648:         foreach my $key (keys(%{$newenv})) {
                    649:             my $refused = 0;
                    650: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    651:                 $refused = 1;
                    652:                 if (ref($roles) eq 'ARRAY') {
                    653:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    654:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    655:                         $refused = 0;
                    656:                     }
                    657:                 }
                    658:             }
                    659:             if ($refused) {
                    660:                 &logthis("<font color=\"blue\">WARNING: ".
                    661:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    662:                          .'</font>');
                    663: 	        delete($newenv->{$key});
                    664:             } else {
                    665:                 $env{$key}=$newenv->{$key};
                    666:             }
                    667:         }
                    668:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    669:         if ($opened
                    670: 	    && &timed_flock($env_file,LOCK_EX)
                    671: 	    &&
                    672: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    673: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    674: 	    while (my ($key,$value) = each(%{$newenv})) {
                    675: 	        $disk_env{$key} = $value;
                    676: 	    }
                    677: 	    untie(%disk_env);
1.35      www       678:         }
1.191     harris41  679:     }
1.56      www       680:     return 'ok';
                    681: }
                    682: # ----------------------------------------------------- Delete from Environment
                    683: 
                    684: sub delenv {
1.1104    raeburn   685:     my ($delthis,$regexp,$roles) = @_;
                    686:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    687:         my $refused = 1;
                    688:         if (ref($roles) eq 'ARRAY') {
                    689:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    690:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    691:                 $refused = 0;
                    692:             }
                    693:         }
                    694:         if ($refused) {
                    695:             &logthis("<font color=\"blue\">WARNING: ".
                    696:                      "Attempt to delete from environment ".$delthis);
                    697:             return 'error';
                    698:         }
1.56      www       699:     }
1.917     albertel  700:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:     if ($opened
1.915     albertel  702: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  703: 	&&
                    704: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  706: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   707: 	    if ($regexp) {
                    708:                 if ($key=~/^$delthis/) {
                    709:                     delete($env{$key});
                    710:                     delete($disk_env{$key});
                    711:                 } 
                    712:             } else {
                    713:                 if ($key=~/^\Q$delthis\E/) {
                    714: 		    delete($env{$key});
                    715: 		    delete($disk_env{$key});
                    716: 	        }
                    717:             }
1.448     albertel  718: 	}
1.783     albertel  719: 	untie(%disk_env);
1.5       www       720:     }
                    721:     return 'ok';
1.369     albertel  722: }
                    723: 
1.790     albertel  724: sub get_env_multiple {
                    725:     my ($name) = @_;
                    726:     my @values;
                    727:     if (defined($env{$name})) {
                    728:         # exists is it an array
                    729:         if (ref($env{$name})) {
                    730:             @values=@{ $env{$name} };
                    731:         } else {
                    732:             $values[0]=$env{$name};
                    733:         }
                    734:     }
                    735:     return(@values);
                    736: }
                    737: 
1.958     www       738: # ------------------------------------------------------------------- Locking
                    739: 
                    740: sub set_lock {
                    741:     my ($text)=@_;
                    742:     $locknum++;
                    743:     my $id=$$.'-'.$locknum;
                    744:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    745:              'session.lock.'.$id => $text});
                    746:     return $id;
                    747: }
                    748: 
                    749: sub get_locks {
                    750:     my $num=0;
                    751:     my %texts=();
                    752:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    753:        if ($lock=~/\w/) {
                    754:           $num++;
                    755:           $texts{$lock}=$env{'session.lock.'.$lock};
                    756:        }
                    757:    }
                    758:    return ($num,%texts);
                    759: }
                    760: 
                    761: sub remove_lock {
                    762:     my ($id)=@_;
                    763:     my $newlocks='';
                    764:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    765:        if (($lock=~/\w/) && ($lock ne $id)) {
                    766:           $newlocks.=','.$lock;
                    767:        }
                    768:     }
                    769:     &appenv({'session.locks' => $newlocks});
                    770:     &delenv('session.lock.'.$id);
                    771: }
                    772: 
                    773: sub remove_all_locks {
                    774:     my $activelocks=$env{'session.locks'};
                    775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    776:        if ($lock=~/\w/) {
                    777:           &remove_lock($lock);
                    778:        }
                    779:     }
                    780: }
                    781: 
                    782: 
1.369     albertel  783: # ------------------------------------------ Find out current server userload
                    784: sub userload {
                    785:     my $numusers=0;
                    786:     {
                    787: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    788: 	my $filename;
                    789: 	my $curtime=time;
                    790: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  791: 	    next if ($filename eq '.' || $filename eq '..');
                    792: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  793: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  794: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  795: 	}
                    796: 	closedir(LONIDS);
                    797:     }
                    798:     my $userloadpercent=0;
                    799:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    800:     if ($maxuserload) {
1.371     albertel  801: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  802:     }
1.372     albertel  803:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  804:     return $userloadpercent;
1.283     www       805: }
                    806: 
1.1       albertel  807: # ------------------------------ Find server with least workload from spare.tab
1.11      www       808: 
1.1       albertel  809: sub spareserver {
1.1083    raeburn   810:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  811:     my $spare_server;
1.370     albertel  812:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  813:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    814:                                                      :  $userloadpercent;
1.1083    raeburn   815:     my ($uint_dom,$remotesessions);
                    816:     if (($udom ne '') && (&domain($udom) ne '')) {
                    817:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    818:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    819:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    820:         $remotesessions = $udomdefaults{'remotesessions'};
                    821:     }
1.1123    raeburn   822:     my $spareshash = &this_host_spares($udom);
                    823:     if (ref($spareshash) eq 'HASH') {
                    824:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    825:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    826:                 if ($uint_dom) {
                    827:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    828:                                                  $try_server));
                    829:                 }
                    830: 	        ($spare_server, $lowest_load) =
                    831: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    832:             }
1.1083    raeburn   833:         }
1.784     albertel  834: 
1.1123    raeburn   835:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    836: 
                    837:         if (!$found_server) {
                    838:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    839: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    840:                     if ($uint_dom) {
                    841:                         next unless (&spare_can_host($udom,$uint_dom,
                    842:                                                      $remotesessions,$try_server));
                    843:                     }
                    844: 	            ($spare_server, $lowest_load) =
                    845: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    846:                 }
                    847: 	    }
                    848:         }
1.784     albertel  849:     }
                    850: 
                    851:     if (!$want_server_name) {
1.968     raeburn   852:         my $protocol = 'http';
                    853:         if ($protocol{$spare_server} eq 'https') {
                    854:             $protocol = $protocol{$spare_server};
                    855:         }
1.1001    raeburn   856:         if (defined($spare_server)) {
                    857:             my $hostname = &hostname($spare_server);
1.1083    raeburn   858:             if (defined($hostname)) {
1.1001    raeburn   859: 	        $spare_server = $protocol.'://'.$hostname;
                    860:             }
                    861:         }
1.784     albertel  862:     }
                    863:     return $spare_server;
                    864: }
                    865: 
                    866: sub compare_server_load {
                    867:     my ($try_server, $spare_server, $lowest_load) = @_;
                    868: 
                    869:     my $loadans     = &reply('load',    $try_server);
                    870:     my $userloadans = &reply('userload',$try_server);
                    871: 
                    872:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   873: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  874:     }
                    875: 
                    876:     my $load;
                    877:     if ($loadans =~ /\d/) {
                    878: 	if ($userloadans =~ /\d/) {
                    879: 	    #both are numbers, pick the bigger one
                    880: 	    $load = ($loadans > $userloadans) ? $loadans 
                    881: 		                              : $userloadans;
1.411     albertel  882: 	} else {
1.784     albertel  883: 	    $load = $loadans;
1.411     albertel  884: 	}
1.784     albertel  885:     } else {
                    886: 	$load = $userloadans;
                    887:     }
                    888: 
                    889:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    890: 	$spare_server = $try_server;
                    891: 	$lowest_load  = $load;
1.370     albertel  892:     }
1.784     albertel  893:     return ($spare_server,$lowest_load);
1.202     matthew   894: }
1.914     albertel  895: 
                    896: # --------------------------- ask offload servers if user already has a session
                    897: sub find_existing_session {
                    898:     my ($udom,$uname) = @_;
1.1123    raeburn   899:     my $spareshash = &this_host_spares($udom);
                    900:     if (ref($spareshash) eq 'HASH') {
                    901:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    902:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    903:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    904:             }
                    905:         }
                    906:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    907:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    908:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    909:             }
                    910:         }
1.914     albertel  911:     }
                    912:     return;
                    913: }
                    914: 
                    915: # -------------------------------- ask if server already has a session for user
                    916: sub has_user_session {
                    917:     my ($lonid,$udom,$uname) = @_;
                    918:     my $result = &reply(join(':','userhassession',
                    919: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    920:     return 1 if ($result eq 'ok');
                    921: 
                    922:     return 0;
                    923: }
                    924: 
1.1076    raeburn   925: # --------- determine least loaded server in a user's domain which allows login
                    926: 
                    927: sub choose_server {
1.1115    raeburn   928:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   929:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   930:     my %servers = &get_servers($udom);
1.1076    raeburn   931:     my $lowest_load = 30000;
1.1116    raeburn   932:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   933:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   934:         my $loginvia;
                    935:         if ($checkloginvia) {
                    936:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   937:             if ($loginvia) {
                    938:                 my ($server,$path) = split(/:/,$loginvia);
                    939:                 ($login_host, $lowest_load) =
                    940:                     &compare_server_load($server, $login_host, $lowest_load);
                    941:                 if ($login_host eq $server) {
                    942:                     $portal_path = $path;
                    943:                 }
                    944:             } else {
                    945:                 ($login_host, $lowest_load) =
                    946:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    947:                 if ($login_host eq $lonhost) {
                    948:                     $portal_path = '';
                    949:                 }
                    950:             }
                    951:         } else {
1.1076    raeburn   952:             ($login_host, $lowest_load) =
1.1116    raeburn   953:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   954:         }
                    955:     }
                    956:     if ($login_host ne '') {
1.1116    raeburn   957:         $hostname = &hostname($login_host);
1.1076    raeburn   958:     }
1.1116    raeburn   959:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   960: }
                    961: 
1.202     matthew   962: # --------------------------------------------- Try to change a user's password
                    963: 
                    964: sub changepass {
1.799     raeburn   965:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   966:     $currentpass = &escape($currentpass);
                    967:     $newpass     = &escape($newpass);
1.1030    raeburn   968:     my $lonhost = $perlvar{'lonHostID'};
                    969:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   970: 		       $server);
                    971:     if (! $answer) {
                    972: 	&logthis("No reply on password change request to $server ".
                    973: 		 "by $uname in domain $udom.");
                    974:     } elsif ($answer =~ "^ok") {
                    975:         &logthis("$uname in $udom successfully changed their password ".
                    976: 		 "on $server.");
                    977:     } elsif ($answer =~ "^pwchange_failure") {
                    978: 	&logthis("$uname in $udom was unable to change their password ".
                    979: 		 "on $server.  The action was blocked by either lcpasswd ".
                    980: 		 "or pwchange");
                    981:     } elsif ($answer =~ "^non_authorized") {
                    982:         &logthis("$uname in $udom did not get their password correct when ".
                    983: 		 "attempting to change it on $server.");
                    984:     } elsif ($answer =~ "^auth_mode_error") {
                    985:         &logthis("$uname in $udom attempted to change their password despite ".
                    986: 		 "not being locally or internally authenticated on $server.");
                    987:     } elsif ($answer =~ "^unknown_user") {
                    988:         &logthis("$uname in $udom attempted to change their password ".
                    989: 		 "on $server but were unable to because $server is not ".
                    990: 		 "their home server.");
                    991:     } elsif ($answer =~ "^refused") {
                    992: 	&logthis("$server refused to change $uname in $udom password because ".
                    993: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   994:     } elsif ($answer =~ "invalid_client") {
                    995:         &logthis("$server refused to change $uname in $udom password because ".
                    996:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   997:     }
                    998:     return $answer;
1.1       albertel  999: }
                   1000: 
1.169     harris41 1001: # ----------------------- Try to determine user's current authentication scheme
                   1002: 
                   1003: sub queryauthenticate {
                   1004:     my ($uname,$udom)=@_;
1.456     albertel 1005:     my $uhome=&homeserver($uname,$udom);
                   1006:     if (!$uhome) {
                   1007: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1008: 	return 'no_host';
                   1009:     }
                   1010:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1011:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1012: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1013:     }
1.456     albertel 1014:     return $answer;
1.169     harris41 1015: }
                   1016: 
1.1       albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1018: 
1.1       albertel 1019: sub authenticate {
1.1073    raeburn  1020:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1021:     $upass=&escape($upass);
                   1022:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1023:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1024:     my $newhome;
1.836     www      1025:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1026: # Maybe the machine was offline and only re-appeared again recently?
                   1027:         &reconlonc();
                   1028: # One more
1.952     raeburn  1029: 	$uhome=&homeserver($uname,$udom,1);
                   1030:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1031:             if (defined(&domain($udom,'primary'))) {
                   1032:                 $newhome=&domain($udom,'primary');
                   1033:             }
                   1034:             if ($newhome ne '') {
                   1035:                 $uhome = $newhome;
                   1036:             }
                   1037:         }
1.836     www      1038: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1039: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1040: 	    return 'no_host';
                   1041:         }
1.1       albertel 1042:     }
1.1073    raeburn  1043:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1044:     if ($answer eq 'authorized') {
1.952     raeburn  1045:         if ($newhome) {
                   1046:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1047:             return 'no_account_on_host'; 
                   1048:         } else {
                   1049:             &logthis("User $uname at $udom authorized by $uhome");
                   1050:             return $uhome;
                   1051:         }
1.471     albertel 1052:     }
                   1053:     if ($answer eq 'non_authorized') {
                   1054: 	&logthis("User $uname at $udom rejected by $uhome");
                   1055: 	return 'no_host'; 
1.9       www      1056:     }
1.471     albertel 1057:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1058:     return 'no_host';
                   1059: }
                   1060: 
1.1073    raeburn  1061: sub can_host_session {
1.1074    raeburn  1062:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1063:     my $canhost = 1;
1.1074    raeburn  1064:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1065:     if (ref($remotesessions) eq 'HASH') {
                   1066:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1067:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1068:                 $canhost = 0;
                   1069:             } else {
                   1070:                 $canhost = 1;
                   1071:             }
                   1072:         }
                   1073:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1074:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1075:                 $canhost = 1;
                   1076:             } else {
                   1077:                 $canhost = 0;
                   1078:             }
                   1079:         }
                   1080:         if ($canhost) {
                   1081:             if ($remotesessions->{'version'} ne '') {
                   1082:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1083:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1084:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1085:                         my $major = $1;
                   1086:                         my $minor = $2;
                   1087:                         if (($major < $reqmajor ) ||
                   1088:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1089:                             $canhost = 0;
                   1090:                         }
                   1091:                     } else {
                   1092:                         $canhost = 0;
                   1093:                     }
                   1094:                 }
                   1095:             }
                   1096:         }
                   1097:     }
                   1098:     if ($canhost) {
                   1099:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1100:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1101:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1102:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1103:                 if (($uint_dom ne '') && 
                   1104:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1105:                     $canhost = 0;
                   1106:                 } else {
                   1107:                     $canhost = 1;
                   1108:                 }
                   1109:             }
                   1110:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1111:                 if (($uint_dom ne '') && 
                   1112:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1113:                     $canhost = 1;
                   1114:                 } else {
                   1115:                     $canhost = 0;
                   1116:                 }
                   1117:             }
                   1118:         }
                   1119:     }
                   1120:     return $canhost;
                   1121: }
                   1122: 
1.1083    raeburn  1123: sub spare_can_host {
                   1124:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1125:     my $canhost=1;
                   1126:     my @intdoms;
                   1127:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1128:     if (ref($internet_names) eq 'ARRAY') {
                   1129:         @intdoms = @{$internet_names};
                   1130:     }
                   1131:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1132:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1133:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1134:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1135:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1136:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1137:                                      $remotesessions,
                   1138:                                      $defdomdefaults{'hostedsessions'});
                   1139:     }
                   1140:     return $canhost;
                   1141: }
                   1142: 
1.1123    raeburn  1143: sub this_host_spares {
                   1144:     my ($dom) = @_;
1.1126    raeburn  1145:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1146:     my @hosts = &current_machine_ids();
                   1147:     foreach my $lonhost (@hosts) {
                   1148:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1149:             $dom_in_use = $dom;
                   1150:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1151:             last;
                   1152:         }
                   1153:     }
1.1126    raeburn  1154:     if ($dom_in_use ne '') {
                   1155:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1156:     }
                   1157:     if (ref($result) ne 'HASH') {
                   1158:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1159:         $dom_in_use = &host_domain($lonhost_in_use);
                   1160:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1161:         if (ref($result) ne 'HASH') {
                   1162:             $result = \%spareid;
                   1163:         }
                   1164:     }
                   1165:     return $result;
                   1166: }
                   1167: 
                   1168: sub spares_for_offload  {
                   1169:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1170:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1171:     if (defined($cached)) {
                   1172:         return $result;
                   1173:     } else {
1.1126    raeburn  1174:         my $cachetime = 60*60*24;
                   1175:         my %domconfig =
                   1176:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1177:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1178:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1179:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1180:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1181:                 }
                   1182:             }
                   1183:         }
                   1184:     }
1.1126    raeburn  1185:     return;
1.1123    raeburn  1186: }
                   1187: 
1.1127  ! raeburn  1188: sub internet_dom_servers {
        !          1189:     my ($dom) = @_;
        !          1190:     my (%uniqservers,%servers);
        !          1191:     my $primaryserver = &hostname(&domain($dom,'primary'));
        !          1192:     my @machinedoms = &machine_domains($primaryserver);
        !          1193:     foreach my $mdom (@machinedoms) {
        !          1194:         my %currservers = %servers;
        !          1195:         my %server = &get_servers($mdom);
        !          1196:         %servers = (%currservers,%server);
        !          1197:     }
        !          1198:     my %by_hostname;
        !          1199:     foreach my $id (keys(%servers)) {
        !          1200:         push(@{$by_hostname{$servers{$id}}},$id);
        !          1201:     }
        !          1202:     foreach my $hostname (sort(keys(%by_hostname))) {
        !          1203:         if (@{$by_hostname{$hostname}} > 1) {
        !          1204:             my $match = 0;
        !          1205:             foreach my $id (@{$by_hostname{$hostname}}) {
        !          1206:                 if (&host_domain($id) eq $dom) {
        !          1207:                     $uniqservers{$id} = $hostname;
        !          1208:                     $match = 1;
        !          1209:                 }
        !          1210:             }
        !          1211:             unless ($match) {
        !          1212:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
        !          1213:             }
        !          1214:         } else {
        !          1215:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
        !          1216:         }
        !          1217:     }
        !          1218:     return %uniqservers;
        !          1219: }
        !          1220: 
1.1       albertel 1221: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1222: 
1.599     albertel 1223: my %homecache;
1.1       albertel 1224: sub homeserver {
1.230     stredwic 1225:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1226:     my $index="$uname:$udom";
1.426     albertel 1227: 
1.599     albertel 1228:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1229: 
                   1230:     my %servers = &get_servers($udom,'library');
                   1231:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1232:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1233: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1234: 
                   1235: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1236: 	if ($answer eq 'found') {
                   1237: 	    delete($badServerCache{$tryserver}); 
                   1238: 	    return $homecache{$index}=$tryserver;
                   1239: 	} elsif ($answer eq 'no_host') {
                   1240: 	    $badServerCache{$tryserver}=1;
                   1241: 	}
1.1       albertel 1242:     }    
                   1243:     return 'no_host';
1.70      www      1244: }
                   1245: 
                   1246: # ------------------------------------- Find the usernames behind a list of IDs
                   1247: 
                   1248: sub idget {
                   1249:     my ($udom,@ids)=@_;
                   1250:     my %returnhash=();
                   1251:     
1.841     albertel 1252:     my %servers = &get_servers($udom,'library');
                   1253:     foreach my $tryserver (keys(%servers)) {
                   1254: 	my $idlist=join('&',@ids);
                   1255: 	$idlist=~tr/A-Z/a-z/; 
                   1256: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1257: 	my @answer=();
                   1258: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1259: 	    @answer=split(/\&/,$reply);
                   1260: 	}                    ;
                   1261: 	my $i;
                   1262: 	for ($i=0;$i<=$#ids;$i++) {
                   1263: 	    if ($answer[$i]) {
                   1264: 		$returnhash{$ids[$i]}=$answer[$i];
                   1265: 	    } 
                   1266: 	}
                   1267:     } 
1.70      www      1268:     return %returnhash;
                   1269: }
                   1270: 
                   1271: # ------------------------------------- Find the IDs behind a list of usernames
                   1272: 
                   1273: sub idrget {
                   1274:     my ($udom,@unames)=@_;
                   1275:     my %returnhash=();
1.800     albertel 1276:     foreach my $uname (@unames) {
                   1277:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1278:     }
1.70      www      1279:     return %returnhash;
                   1280: }
                   1281: 
                   1282: # ------------------------------- Store away a list of names and associated IDs
                   1283: 
                   1284: sub idput {
                   1285:     my ($udom,%ids)=@_;
                   1286:     my %servers=();
1.800     albertel 1287:     foreach my $uname (keys(%ids)) {
                   1288: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1289:         my $uhom=&homeserver($uname,$udom);
1.70      www      1290:         if ($uhom ne 'no_host') {
1.800     albertel 1291:             my $id=&escape($ids{$uname});
1.70      www      1292:             $id=~tr/A-Z/a-z/;
1.800     albertel 1293:             my $esc_unam=&escape($uname);
1.70      www      1294: 	    if ($servers{$uhom}) {
1.800     albertel 1295: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1296:             } else {
1.800     albertel 1297:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1298:             }
                   1299:         }
1.191     harris41 1300:     }
1.800     albertel 1301:     foreach my $server (keys(%servers)) {
                   1302:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1303:     }
1.344     www      1304: }
                   1305: 
1.1023    raeburn  1306: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1307: sub dump_dom {
1.1023    raeburn  1308:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1309:     if (!$udom) {
                   1310:         $udom=$env{'user.domain'};
                   1311:     }
                   1312:     my %returnhash;
1.1023    raeburn  1313:     if ($udom) {
                   1314:         my $uname = &get_domainconfiguser($udom);
                   1315:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1316:     }
                   1317:     return %returnhash;
                   1318: }
                   1319: 
1.1023    raeburn  1320: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1321: 
                   1322: sub get_dom {
1.860     raeburn  1323:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1324:     my $items='';
                   1325:     foreach my $item (@$storearr) {
                   1326:         $items.=&escape($item).'&';
                   1327:     }
                   1328:     $items=~s/\&$//;
1.860     raeburn  1329:     if (!$udom) {
                   1330:         $udom=$env{'user.domain'};
                   1331:         if (defined(&domain($udom,'primary'))) {
                   1332:             $uhome=&domain($udom,'primary');
                   1333:         } else {
1.874     albertel 1334:             undef($uhome);
1.860     raeburn  1335:         }
                   1336:     } else {
                   1337:         if (!$uhome) {
                   1338:             if (defined(&domain($udom,'primary'))) {
                   1339:                 $uhome=&domain($udom,'primary');
                   1340:             }
                   1341:         }
                   1342:     }
                   1343:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1344:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1345:         my %returnhash;
1.875     albertel 1346:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1347:             return %returnhash;
                   1348:         }
1.806     raeburn  1349:         my @pairs=split(/\&/,$rep);
                   1350:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1351:             return @pairs;
                   1352:         }
                   1353:         my $i=0;
                   1354:         foreach my $item (@$storearr) {
                   1355:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1356:             $i++;
                   1357:         }
                   1358:         return %returnhash;
                   1359:     } else {
1.880     banghart 1360:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1361:     }
                   1362: }
                   1363: 
                   1364: # -------------------------------------------- put items in domain db files 
                   1365: 
                   1366: sub put_dom {
1.860     raeburn  1367:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1368:     if (!$udom) {
                   1369:         $udom=$env{'user.domain'};
                   1370:         if (defined(&domain($udom,'primary'))) {
                   1371:             $uhome=&domain($udom,'primary');
                   1372:         } else {
1.874     albertel 1373:             undef($uhome);
1.860     raeburn  1374:         }
                   1375:     } else {
                   1376:         if (!$uhome) {
                   1377:             if (defined(&domain($udom,'primary'))) {
                   1378:                 $uhome=&domain($udom,'primary');
                   1379:             }
                   1380:         }
                   1381:     } 
                   1382:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1383:         my $items='';
                   1384:         foreach my $item (keys(%$storehash)) {
                   1385:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1386:         }
                   1387:         $items=~s/\&$//;
                   1388:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1389:     } else {
1.860     raeburn  1390:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1391:     }
                   1392: }
                   1393: 
1.1023    raeburn  1394: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1395: sub newput_dom {
1.1023    raeburn  1396:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1397:     my $result;
                   1398:     if (!$udom) {
                   1399:         $udom=$env{'user.domain'};
                   1400:     }
1.1023    raeburn  1401:     if ($udom) {
                   1402:         my $uname = &get_domainconfiguser($udom);
                   1403:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1404:     }
                   1405:     return $result;
                   1406: }
                   1407: 
1.1023    raeburn  1408: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1409: sub del_dom {
1.1023    raeburn  1410:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1411:     if (ref($storearr) eq 'ARRAY') {
                   1412:         if (!$udom) {
                   1413:             $udom=$env{'user.domain'};
                   1414:         }
1.1023    raeburn  1415:         if ($udom) {
                   1416:             my $uname = &get_domainconfiguser($udom); 
                   1417:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1418:         }
                   1419:     }
                   1420: }
                   1421: 
1.1023    raeburn  1422: # ----------------------------------construct domainconfig user for a domain 
                   1423: sub get_domainconfiguser {
                   1424:     my ($udom) = @_;
                   1425:     return $udom.'-domainconfig';
                   1426: }
                   1427: 
1.837     raeburn  1428: sub retrieve_inst_usertypes {
                   1429:     my ($udom) = @_;
                   1430:     my (%returnhash,@order);
1.989     raeburn  1431:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1432:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1433:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1434:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1435:         @order = @{$domdefs{'inststatusorder'}};
                   1436:     } else {
                   1437:         if (defined(&domain($udom,'primary'))) {
                   1438:             my $uhome=&domain($udom,'primary');
                   1439:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1440:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1441:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1442:                 return (\%returnhash,\@order);
                   1443:             }
                   1444:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1445:             my @pairs=split(/\&/,$hashitems);
                   1446:             foreach my $item (@pairs) {
                   1447:                 my ($key,$value)=split(/=/,$item,2);
                   1448:                 $key = &unescape($key);
                   1449:                 next if ($key =~ /^error: 2 /);
                   1450:                 $returnhash{$key}=&thaw_unescape($value);
                   1451:             }
                   1452:             my @esc_order = split(/\&/,$orderitems);
                   1453:             foreach my $item (@esc_order) {
                   1454:                 push(@order,&unescape($item));
                   1455:             }
                   1456:         } else {
                   1457:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1458:         }
                   1459:     }
                   1460:     return (\%returnhash,\@order);
                   1461: }
                   1462: 
1.868     raeburn  1463: sub is_domainimage {
                   1464:     my ($url) = @_;
                   1465:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1466:         if (&domain($1) ne '') {
                   1467:             return '1';
                   1468:         }
                   1469:     }
                   1470:     return;
                   1471: }
                   1472: 
1.899     raeburn  1473: sub inst_directory_query {
                   1474:     my ($srch) = @_;
                   1475:     my $udom = $srch->{'srchdomain'};
                   1476:     my %results;
                   1477:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1478:     my $outcome;
1.899     raeburn  1479:     if ($homeserver ne '') {
1.904     albertel 1480: 	my $queryid=&reply("querysend:instdirsearch:".
                   1481: 			   &escape($srch->{'srchby'}).':'.
                   1482: 			   &escape($srch->{'srchterm'}).':'.
                   1483: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1484: 	my $host=&hostname($homeserver);
                   1485: 	if ($queryid !~/^\Q$host\E\_/) {
                   1486: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1487: 	    return;
                   1488: 	}
                   1489: 	my $response = &get_query_reply($queryid);
                   1490: 	my $maxtries = 5;
                   1491: 	my $tries = 1;
                   1492: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1493: 	    $response = &get_query_reply($queryid);
                   1494: 	    $tries ++;
                   1495: 	}
                   1496: 
                   1497:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1498:             if ($response eq 'unavailable') {
                   1499:                 $outcome = $response;
                   1500:             } else {
                   1501:                 $outcome = 'ok';
                   1502:                 my @matches = split(/\n/,$response);
                   1503:                 foreach my $match (@matches) {
                   1504:                     my ($key,$value) = split(/=/,$match);
                   1505:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1506:                 }
1.899     raeburn  1507:             }
                   1508:         }
                   1509:     }
1.909     raeburn  1510:     return ($outcome,%results);
1.899     raeburn  1511: }
                   1512: 
                   1513: sub usersearch {
                   1514:     my ($srch) = @_;
                   1515:     my $dom = $srch->{'srchdomain'};
                   1516:     my %results;
                   1517:     my %libserv = &all_library();
                   1518:     my $query = 'usersearch';
                   1519:     foreach my $tryserver (keys(%libserv)) {
                   1520:         if (&host_domain($tryserver) eq $dom) {
                   1521:             my $host=&hostname($tryserver);
                   1522:             my $queryid=
1.911     raeburn  1523:                 &reply("querysend:".&escape($query).':'.
                   1524:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1525:                        &escape($srch->{'srchtype'}).':'.
                   1526:                        &escape($srch->{'srchterm'}),$tryserver);
                   1527:             if ($queryid !~/^\Q$host\E\_/) {
                   1528:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1529:                 next;
1.899     raeburn  1530:             }
                   1531:             my $reply = &get_query_reply($queryid);
                   1532:             my $maxtries = 1;
                   1533:             my $tries = 1;
                   1534:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1535:                 $reply = &get_query_reply($queryid);
                   1536:                 $tries ++;
                   1537:             }
                   1538:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1539:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1540:             } else {
1.911     raeburn  1541:                 my @matches;
                   1542:                 if ($reply =~ /\n/) {
                   1543:                     @matches = split(/\n/,$reply);
                   1544:                 } else {
                   1545:                     @matches = split(/\&/,$reply);
                   1546:                 }
1.899     raeburn  1547:                 foreach my $match (@matches) {
                   1548:                     my ($uname,$udom,%userhash);
1.911     raeburn  1549:                     foreach my $entry (split(/:/,$match)) {
                   1550:                         my ($key,$value) =
                   1551:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1552:                         $userhash{$key} = $value;
                   1553:                         if ($key eq 'username') {
                   1554:                             $uname = $value;
                   1555:                         } elsif ($key eq 'domain') {
                   1556:                             $udom = $value;
1.911     raeburn  1557:                         }
1.899     raeburn  1558:                     }
                   1559:                     $results{$uname.':'.$udom} = \%userhash;
                   1560:                 }
                   1561:             }
                   1562:         }
                   1563:     }
                   1564:     return %results;
                   1565: }
                   1566: 
1.912     raeburn  1567: sub get_instuser {
                   1568:     my ($udom,$uname,$id) = @_;
                   1569:     my $homeserver = &domain($udom,'primary');
                   1570:     my ($outcome,%results);
                   1571:     if ($homeserver ne '') {
                   1572:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1573:                            &escape($id).':'.&escape($udom),$homeserver);
                   1574:         my $host=&hostname($homeserver);
                   1575:         if ($queryid !~/^\Q$host\E\_/) {
                   1576:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1577:             return;
                   1578:         }
                   1579:         my $response = &get_query_reply($queryid);
                   1580:         my $maxtries = 5;
                   1581:         my $tries = 1;
                   1582:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1583:             $response = &get_query_reply($queryid);
                   1584:             $tries ++;
                   1585:         }
                   1586:         if (!&error($response) && $response ne 'refused') {
                   1587:             if ($response eq 'unavailable') {
                   1588:                 $outcome = $response;
                   1589:             } else {
                   1590:                 $outcome = 'ok';
                   1591:                 my @matches = split(/\n/,$response);
                   1592:                 foreach my $match (@matches) {
                   1593:                     my ($key,$value) = split(/=/,$match);
                   1594:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1595:                 }
                   1596:             }
                   1597:         }
                   1598:     }
                   1599:     my %userinfo;
                   1600:     if (ref($results{$uname}) eq 'HASH') {
                   1601:         %userinfo = %{$results{$uname}};
                   1602:     } 
                   1603:     return ($outcome,%userinfo);
                   1604: }
                   1605: 
                   1606: sub inst_rulecheck {
1.923     raeburn  1607:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1608:     my %returnhash;
                   1609:     if ($udom ne '') {
                   1610:         if (ref($rules) eq 'ARRAY') {
                   1611:             @{$rules} = map {&escape($_);} (@{$rules});
                   1612:             my $rulestr = join(':',@{$rules});
                   1613:             my $homeserver=&domain($udom,'primary');
                   1614:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1615:                 my $response;
                   1616:                 if ($item eq 'username') {                
                   1617:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1618:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1619:                                               $homeserver));
1.923     raeburn  1620:                 } elsif ($item eq 'id') {
                   1621:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1622:                                               ':'.&escape($id).':'.$rulestr,
                   1623:                                               $homeserver));
1.945     raeburn  1624:                 } elsif ($item eq 'selfcreate') {
                   1625:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1626:                                                &escape($udom).':'.&escape($uname).
                   1627:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1628:                 }
1.912     raeburn  1629:                 if ($response ne 'refused') {
                   1630:                     my @pairs=split(/\&/,$response);
                   1631:                     foreach my $item (@pairs) {
                   1632:                         my ($key,$value)=split(/=/,$item,2);
                   1633:                         $key = &unescape($key);
                   1634:                         next if ($key =~ /^error: 2 /);
                   1635:                         $returnhash{$key}=&thaw_unescape($value);
                   1636:                     }
                   1637:                 }
                   1638:             }
                   1639:         }
                   1640:     }
                   1641:     return %returnhash;
                   1642: }
                   1643: 
                   1644: sub inst_userrules {
1.923     raeburn  1645:     my ($udom,$check) = @_;
1.912     raeburn  1646:     my (%ruleshash,@ruleorder);
                   1647:     if ($udom ne '') {
                   1648:         my $homeserver=&domain($udom,'primary');
                   1649:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1650:             my $response;
                   1651:             if ($check eq 'id') {
                   1652:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1653:                                  $homeserver);
1.943     raeburn  1654:             } elsif ($check eq 'email') {
                   1655:                 $response=&reply('instemailrules:'.&escape($udom),
                   1656:                                  $homeserver);
1.923     raeburn  1657:             } else {
                   1658:                 $response=&reply('instuserrules:'.&escape($udom),
                   1659:                                  $homeserver);
                   1660:             }
1.912     raeburn  1661:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1662:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1663:                 ($response ne 'no_such_host')) {
                   1664:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1665:                 my @pairs=split(/\&/,$hashitems);
                   1666:                 foreach my $item (@pairs) {
                   1667:                     my ($key,$value)=split(/=/,$item,2);
                   1668:                     $key = &unescape($key);
                   1669:                     next if ($key =~ /^error: 2 /);
                   1670:                     $ruleshash{$key}=&thaw_unescape($value);
                   1671:                 }
                   1672:                 my @esc_order = split(/\&/,$orderitems);
                   1673:                 foreach my $item (@esc_order) {
                   1674:                     push(@ruleorder,&unescape($item));
                   1675:                 }
                   1676:             }
                   1677:         }
                   1678:     }
                   1679:     return (\%ruleshash,\@ruleorder);
                   1680: }
                   1681: 
1.976     raeburn  1682: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1683: 
                   1684: sub get_domain_defaults {
                   1685:     my ($domain) = @_;
                   1686:     my $cachetime = 60*60*24;
                   1687:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1688:     if (defined($cached)) {
                   1689:         if (ref($result) eq 'HASH') {
                   1690:             return %{$result};
                   1691:         }
                   1692:     }
                   1693:     my %domdefaults;
                   1694:     my %domconfig =
1.989     raeburn  1695:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1696:                                   'requestcourses','inststatus',
1.1073    raeburn  1697:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1698:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1699:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1700:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1701:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1702:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1703:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1704:     } else {
                   1705:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1706:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1707:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1708:     }
1.976     raeburn  1709:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1710:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1711:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1712:         } else {
                   1713:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1714:         } 
                   1715:         my @usertools = ('aboutme','blog','portfolio');
                   1716:         foreach my $item (@usertools) {
                   1717:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1718:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1719:             }
                   1720:         }
                   1721:     }
1.985     raeburn  1722:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1723:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1724:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1725:         }
                   1726:     }
1.989     raeburn  1727:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1728:         foreach my $item ('inststatustypes','inststatusorder') {
                   1729:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1730:         }
                   1731:     }
1.1047    raeburn  1732:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1733:         foreach my $item ('canuse_pdfforms') {
                   1734:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1735:         }
                   1736:     }
1.1073    raeburn  1737:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1738:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1739:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1740:         }
                   1741:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1742:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1743:         }
                   1744:     }
1.943     raeburn  1745:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1746:                                   $cachetime);
                   1747:     return %domdefaults;
                   1748: }
                   1749: 
1.344     www      1750: # --------------------------------------------------- Assign a key to a student
                   1751: 
                   1752: sub assign_access_key {
1.364     www      1753: #
                   1754: # a valid key looks like uname:udom#comments
                   1755: # comments are being appended
                   1756: #
1.498     www      1757:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1758:     $kdom=
1.620     albertel 1759:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1760:     $knum=
1.620     albertel 1761:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1762:     $cdom=
1.620     albertel 1763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1764:     $cnum=
1.620     albertel 1765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1766:     $udom=$env{'user.name'} unless (defined($udom));
                   1767:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1768:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1769:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1770:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1771:                                                   # assigned to this person
                   1772:                                                   # - this should not happen,
1.345     www      1773:                                                   # unless something went wrong
                   1774:                                                   # the first time around
                   1775: # ready to assign
1.364     www      1776:         $logentry=$1.'; '.$logentry;
1.496     www      1777:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1778:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1779: # key now belongs to user
1.346     www      1780: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1781:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1782:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1783:                 return 'ok';
                   1784:             } else {
                   1785:                 return 
                   1786:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1787: 	    }
                   1788:         } else {
                   1789:             return 'error: Could not assign key, try again later.';
                   1790:         }
1.364     www      1791:     } elsif (!$existing{$ckey}) {
1.345     www      1792: # the key does not exist
                   1793: 	return 'error: The key does not exist';
                   1794:     } else {
                   1795: # the key is somebody else's
                   1796: 	return 'error: The key is already in use';
                   1797:     }
1.344     www      1798: }
                   1799: 
1.364     www      1800: # ------------------------------------------ put an additional comment on a key
                   1801: 
                   1802: sub comment_access_key {
                   1803: #
                   1804: # a valid key looks like uname:udom#comments
                   1805: # comments are being appended
                   1806: #
                   1807:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1808:     $cdom=
1.620     albertel 1809:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1810:     $cnum=
1.620     albertel 1811:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1812:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1813:     if ($existing{$ckey}) {
                   1814:         $existing{$ckey}.='; '.$logentry;
                   1815: # ready to assign
1.367     www      1816:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1817:                                                  $cdom,$cnum) eq 'ok') {
                   1818: 	    return 'ok';
                   1819:         } else {
                   1820: 	    return 'error: Count not store comment.';
                   1821:         }
                   1822:     } else {
                   1823: # the key does not exist
                   1824: 	return 'error: The key does not exist';
                   1825:     }
                   1826: }
                   1827: 
1.344     www      1828: # ------------------------------------------------------ Generate a set of keys
                   1829: 
                   1830: sub generate_access_keys {
1.364     www      1831:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1832:     $cdom=
1.620     albertel 1833:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1834:     $cnum=
1.620     albertel 1835:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1836:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1837:     unless (($cdom) && ($cnum)) { return 0; }
                   1838:     if ($number>10000) { return 0; }
                   1839:     sleep(2); # make sure don't get same seed twice
                   1840:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1841:     my $total=0;
                   1842:     for (my $i=1;$i<=$number;$i++) {
                   1843:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1844:                   sprintf("%lx",int(100000*rand)).'-'.
                   1845:                   sprintf("%lx",int(100000*rand));
                   1846:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1847:        $newkey=~s/0/h/g; # and also 0 and O
                   1848:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1849:        if ($existing{$newkey}) {
                   1850:            $i--;
                   1851:        } else {
1.364     www      1852: 	  if (&put('accesskeys',
                   1853:               { $newkey => '# generated '.localtime().
1.620     albertel 1854:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1855:                            '; '.$logentry },
                   1856: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1857:               $total++;
                   1858: 	  }
                   1859:        }
                   1860:     }
1.620     albertel 1861:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1862:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1863:     return $total;
                   1864: }
                   1865: 
                   1866: # ------------------------------------------------------- Validate an accesskey
                   1867: 
                   1868: sub validate_access_key {
                   1869:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1870:     $cdom=
1.620     albertel 1871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1872:     $cnum=
1.620     albertel 1873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1874:     $udom=$env{'user.domain'} unless (defined($udom));
                   1875:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1876:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1877:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1878: }
                   1879: 
                   1880: # ------------------------------------- Find the section of student in a course
1.652     albertel 1881: sub devalidate_getsection_cache {
                   1882:     my ($udom,$unam,$courseid)=@_;
                   1883:     my $hashid="$udom:$unam:$courseid";
                   1884:     &devalidate_cache_new('getsection',$hashid);
                   1885: }
1.298     matthew  1886: 
1.815     albertel 1887: sub courseid_to_courseurl {
                   1888:     my ($courseid) = @_;
                   1889:     #already url style courseid
                   1890:     return $courseid if ($courseid =~ m{^/});
                   1891: 
                   1892:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1893: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1894: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1895: 	return "/$cdom/$cnum";
                   1896:     }
                   1897: 
                   1898:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1899:     if (exists($courseinfo{'num'})) {
                   1900: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1901:     }
                   1902: 
                   1903:     return undef;
                   1904: }
                   1905: 
1.298     matthew  1906: sub getsection {
                   1907:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1908:     my $cachetime=1800;
1.551     albertel 1909: 
                   1910:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1911:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1912:     if (defined($cached)) { return $result; }
                   1913: 
1.298     matthew  1914:     my %Pending; 
                   1915:     my %Expired;
                   1916:     #
                   1917:     # Each role can either have not started yet (pending), be active, 
                   1918:     #    or have expired.
                   1919:     #
                   1920:     # If there is an active role, we are done.
                   1921:     #
                   1922:     # If there is more than one role which has not started yet, 
                   1923:     #     choose the one which will start sooner
                   1924:     # If there is one role which has not started yet, return it.
                   1925:     #
                   1926:     # If there is more than one expired role, choose the one which ended last.
                   1927:     # If there is a role which has expired, return it.
                   1928:     #
1.815     albertel 1929:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1930:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1931:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1932:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1933:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1934:         my $section=$1;
                   1935:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1936:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1937:         my $now=time;
1.548     albertel 1938:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1939:             $Expired{$end}=$section;
                   1940:             next;
                   1941:         }
1.548     albertel 1942:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1943:             $Pending{$start}=$section;
                   1944:             next;
                   1945:         }
1.599     albertel 1946:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1947:     }
                   1948:     #
                   1949:     # Presumedly there will be few matching roles from the above
                   1950:     # loop and the sorting time will be negligible.
                   1951:     if (scalar(keys(%Pending))) {
                   1952:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1953:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1954:     } 
                   1955:     if (scalar(keys(%Expired))) {
                   1956:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1957:         my $time = pop(@sorted);
1.599     albertel 1958:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1959:     }
1.599     albertel 1960:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1961: }
1.70      www      1962: 
1.599     albertel 1963: sub save_cache {
                   1964:     &purge_remembered();
1.722     albertel 1965:     #&Apache::loncommon::validate_page();
1.620     albertel 1966:     undef(%env);
1.780     albertel 1967:     undef($env_loaded);
1.599     albertel 1968: }
1.452     albertel 1969: 
1.599     albertel 1970: my $to_remember=-1;
                   1971: my %remembered;
                   1972: my %accessed;
                   1973: my $kicks=0;
                   1974: my $hits=0;
1.849     albertel 1975: sub make_key {
                   1976:     my ($name,$id) = @_;
1.872     albertel 1977:     if (length($id) > 65 
                   1978: 	&& length(&escape($id)) > 200) {
                   1979: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1980:     }
1.849     albertel 1981:     return &escape($name.':'.$id);
                   1982: }
                   1983: 
1.599     albertel 1984: sub devalidate_cache_new {
                   1985:     my ($name,$id,$debug) = @_;
                   1986:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1987:     $id=&make_key($name,$id);
1.599     albertel 1988:     $memcache->delete($id);
                   1989:     delete($remembered{$id});
                   1990:     delete($accessed{$id});
                   1991: }
                   1992: 
                   1993: sub is_cached_new {
                   1994:     my ($name,$id,$debug) = @_;
1.849     albertel 1995:     $id=&make_key($name,$id);
1.599     albertel 1996:     if (exists($remembered{$id})) {
                   1997: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1998: 	$accessed{$id}=[&gettimeofday()];
                   1999: 	$hits++;
                   2000: 	return ($remembered{$id},1);
                   2001:     }
                   2002:     my $value = $memcache->get($id);
                   2003:     if (!(defined($value))) {
                   2004: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2005: 	return (undef,undef);
1.416     albertel 2006:     }
1.599     albertel 2007:     if ($value eq '__undef__') {
                   2008: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2009: 	$value=undef;
                   2010:     }
                   2011:     &make_room($id,$value,$debug);
                   2012:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2013:     return ($value,1);
                   2014: }
                   2015: 
                   2016: sub do_cache_new {
                   2017:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2018:     $id=&make_key($name,$id);
1.599     albertel 2019:     my $setvalue=$value;
                   2020:     if (!defined($setvalue)) {
                   2021: 	$setvalue='__undef__';
                   2022:     }
1.623     albertel 2023:     if (!defined($time) ) {
                   2024: 	$time=600;
                   2025:     }
1.599     albertel 2026:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2027:     my $result = $memcache->set($id,$setvalue,$time);
                   2028:     if (! $result) {
1.872     albertel 2029: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2030: 	$memcache->disconnect_all();
1.872     albertel 2031:     }
1.600     albertel 2032:     # need to make a copy of $value
1.919     albertel 2033:     &make_room($id,$value,$debug);
1.599     albertel 2034:     return $value;
                   2035: }
                   2036: 
                   2037: sub make_room {
                   2038:     my ($id,$value,$debug)=@_;
1.919     albertel 2039: 
                   2040:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2041:                                     : $value;
1.599     albertel 2042:     if ($to_remember<0) { return; }
                   2043:     $accessed{$id}=[&gettimeofday()];
                   2044:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2045:     my $to_kick;
                   2046:     my $max_time=0;
                   2047:     foreach my $other (keys(%accessed)) {
                   2048: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2049: 	    $to_kick=$other;
                   2050: 	    $max_time=&tv_interval($accessed{$other});
                   2051: 	}
                   2052:     }
                   2053:     delete($remembered{$to_kick});
                   2054:     delete($accessed{$to_kick});
                   2055:     $kicks++;
                   2056:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2057:     return;
                   2058: }
                   2059: 
1.599     albertel 2060: sub purge_remembered {
1.604     albertel 2061:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2062:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2063:     undef(%remembered);
                   2064:     undef(%accessed);
1.428     albertel 2065: }
1.70      www      2066: # ------------------------------------- Read an entry from a user's environment
                   2067: 
                   2068: sub userenvironment {
                   2069:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2070:     my $items;
                   2071:     foreach my $item (@what) {
                   2072:         $items.=&escape($item).'&';
                   2073:     }
                   2074:     $items=~s/\&$//;
1.70      www      2075:     my %returnhash=();
1.1009    raeburn  2076:     my $uhome = &homeserver($unam,$udom);
                   2077:     unless ($uhome eq 'no_host') {
                   2078:         my @answer=split(/\&/, 
                   2079:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2080:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2081:             return %returnhash;
                   2082:         }
1.1009    raeburn  2083:         my $i;
                   2084:         for ($i=0;$i<=$#what;$i++) {
                   2085: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2086:         }
1.70      www      2087:     }
                   2088:     return %returnhash;
1.1       albertel 2089: }
                   2090: 
1.617     albertel 2091: # ---------------------------------------------------------- Get a studentphoto
                   2092: sub studentphoto {
                   2093:     my ($udom,$unam,$ext) = @_;
                   2094:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2095:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2096:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2097:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2098:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2099:             } else {
                   2100:                 my ($result,$perm_reqd)=
1.707     albertel 2101: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2102:                 if ($result eq 'ok') {
                   2103:                     if (!($perm_reqd eq 'yes')) {
                   2104:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2105:                     }
                   2106:                 }
                   2107:             }
                   2108:         }
                   2109:     } else {
                   2110:         my ($result,$perm_reqd) = 
1.707     albertel 2111: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2112:         if ($result eq 'ok') {
                   2113:             if (!($perm_reqd eq 'yes')) {
                   2114:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2115:             }
                   2116:         }
                   2117:     }
                   2118:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2119: }
                   2120: 
                   2121: sub retrievestudentphoto {
                   2122:     my ($udom,$unam,$ext,$type) = @_;
                   2123:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2124:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2125:     if ($ret eq 'ok') {
                   2126:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2127:         if ($type eq 'thumbnail') {
                   2128:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2129:         }
                   2130:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2131:         return $tokenurl;
                   2132:     } else {
                   2133:         if ($type eq 'thumbnail') {
                   2134:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2135:         } else { 
                   2136:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2137:         }
1.617     albertel 2138:     }
                   2139: }
                   2140: 
1.263     www      2141: # -------------------------------------------------------------------- New chat
                   2142: 
                   2143: sub chatsend {
1.724     raeburn  2144:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2145:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2146:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2147:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2148:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2149: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2150: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2151: }
                   2152: 
                   2153: # ------------------------------------------ Find current version of a resource
                   2154: 
                   2155: sub getversion {
                   2156:     my $fname=&clutter(shift);
                   2157:     unless ($fname=~/^\/res\//) { return -1; }
                   2158:     return &currentversion(&filelocation('',$fname));
                   2159: }
                   2160: 
                   2161: sub currentversion {
                   2162:     my $fname=shift;
                   2163:     my $author=$fname;
                   2164:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2165:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2166:     my $home=&homeserver($uname,$udom);
1.292     www      2167:     if ($home eq 'no_host') { 
                   2168:         return -1; 
                   2169:     }
1.1112    www      2170:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2171:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2172: 	return -1;
                   2173:     }
1.1112    www      2174:     return $answer;
1.263     www      2175: }
                   2176: 
1.1111    www      2177: #
                   2178: # Return special version number of resource if set by override, empty otherwise
                   2179: #
                   2180: sub usedversion {
                   2181:     my $fname=shift;
                   2182:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2183:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2184:     if ($urlversion) { return $urlversion; }
                   2185:     return '';
                   2186: }
                   2187: 
1.1       albertel 2188: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2189: 
1.1       albertel 2190: sub subscribe {
                   2191:     my $fname=shift;
1.761     raeburn  2192:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2193:     $fname=~s/[\n\r]//g;
1.1       albertel 2194:     my $author=$fname;
                   2195:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2196:     my ($udom,$uname)=split(/\//,$author);
                   2197:     my $home=homeserver($uname,$udom);
1.335     albertel 2198:     if ($home eq 'no_host') {
                   2199:         return 'not_found';
1.1       albertel 2200:     }
                   2201:     my $answer=reply("sub:$fname",$home);
1.64      www      2202:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2203: 	$answer.=' by '.$home;
                   2204:     }
1.1       albertel 2205:     return $answer;
                   2206: }
                   2207:     
1.8       www      2208: # -------------------------------------------------------------- Replicate file
                   2209: 
                   2210: sub repcopy {
                   2211:     my $filename=shift;
1.23      www      2212:     $filename=~s/\/+/\//g;
1.607     raeburn  2213:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2214:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2215:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2216: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2217: 	return &repcopy_userfile($filename);
                   2218:     }
1.532     albertel 2219:     $filename=~s/[\n\r]//g;
1.8       www      2220:     my $transname="$filename.in.transfer";
1.828     www      2221: # FIXME: this should flock
1.607     raeburn  2222:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2223:     my $remoteurl=subscribe($filename);
1.64      www      2224:     if ($remoteurl =~ /^con_lost by/) {
                   2225: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2226:            return 'unavailable';
1.8       www      2227:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2228: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2229: 	   return 'not_found';
1.64      www      2230:     } elsif ($remoteurl =~ /^rejected by/) {
                   2231: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2232:            return 'forbidden';
1.20      www      2233:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2234:            return 'ok';
1.8       www      2235:     } else {
1.290     www      2236:         my $author=$filename;
                   2237:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2238:         my ($udom,$uname)=split(/\//,$author);
                   2239:         my $home=homeserver($uname,$udom);
                   2240:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2241:            my @parts=split(/\//,$filename);
                   2242:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2243:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2244:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2245: 	       return 'bad_request';
1.8       www      2246:            }
                   2247:            my $count;
                   2248:            for ($count=5;$count<$#parts;$count++) {
                   2249:                $path.="/$parts[$count]";
                   2250:                if ((-e $path)!=1) {
                   2251: 		   mkdir($path,0777);
                   2252:                }
                   2253:            }
                   2254:            my $ua=new LWP::UserAgent;
                   2255:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2256:            my $response=$ua->request($request,$transname);
                   2257:            if ($response->is_error()) {
                   2258: 	       unlink($transname);
                   2259:                my $message=$response->status_line;
1.672     albertel 2260:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2261:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2262:                return 'unavailable';
1.8       www      2263:            } else {
1.16      www      2264: 	       if ($remoteurl!~/\.meta$/) {
                   2265:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2266:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2267:                   if ($mresponse->is_error()) {
                   2268: 		      unlink($filename.'.meta');
                   2269:                       &logthis(
1.672     albertel 2270:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2271:                   }
                   2272: 	       }
1.8       www      2273:                rename($transname,$filename);
1.607     raeburn  2274:                return 'ok';
1.8       www      2275:            }
1.290     www      2276:        }
1.8       www      2277:     }
1.330     www      2278: }
                   2279: 
                   2280: # ------------------------------------------------ Get server side include body
                   2281: sub ssi_body {
1.381     albertel 2282:     my ($filelink,%form)=@_;
1.606     matthew  2283:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2284:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2285:     }
1.953     www      2286:     my $output='';
                   2287:     my $response;
1.980     raeburn  2288:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2289:        ($output,$response)=&externalssi($filelink);
1.953     www      2290:     } else {
1.1004    droeschl 2291:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2292:        $filelink .= 'inhibitmenu=yes';
1.953     www      2293:        ($output,$response)=&ssi($filelink,%form);
                   2294:     }
1.778     albertel 2295:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2296:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2297:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2298:     if (wantarray) {
                   2299:         return ($output, $response);
                   2300:     } else {
                   2301:         return $output;
                   2302:     }
1.8       www      2303: }
                   2304: 
1.15      www      2305: # --------------------------------------------------------- Server Side Include
                   2306: 
1.782     albertel 2307: sub absolute_url {
                   2308:     my ($host_name) = @_;
                   2309:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2310:     if ($host_name eq '') {
                   2311: 	$host_name = $ENV{'SERVER_NAME'};
                   2312:     }
                   2313:     return $protocol.$host_name;
                   2314: }
                   2315: 
1.942     foxr     2316: #
                   2317: #   Server side include.
                   2318: # Parameters:
                   2319: #  fn     Possibly encrypted resource name/id.
                   2320: #  form   Hash that describes how the rendering should be done
                   2321: #         and other things.
1.944     foxr     2322: # Returns:
1.950     raeburn  2323: #   Scalar context: The content of the response.
                   2324: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2325: #     
1.15      www      2326: sub ssi {
                   2327: 
1.944     foxr     2328:     my ($fn,%form)=@_;
1.15      www      2329:     my $ua=new LWP::UserAgent;
1.23      www      2330:     my $request;
1.711     albertel 2331: 
                   2332:     $form{'no_update_last_known'}=1;
1.895     albertel 2333:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2334:     if (%form) {
1.782     albertel 2335:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2336:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2337:     } else {
1.782     albertel 2338:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2339:     }
                   2340: 
1.15      www      2341:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2342:     my $response=$ua->request($request);
                   2343: 
1.944     foxr     2344:     if (wantarray) {
                   2345: 	return ($response->content, $response);
                   2346:     } else {
                   2347: 	return $response->content;
1.942     foxr     2348:     }
1.324     www      2349: }
                   2350: 
                   2351: sub externalssi {
                   2352:     my ($url)=@_;
                   2353:     my $ua=new LWP::UserAgent;
                   2354:     my $request=new HTTP::Request('GET',$url);
                   2355:     my $response=$ua->request($request);
1.954     raeburn  2356:     if (wantarray) {
                   2357:         return ($response->content, $response);
                   2358:     } else {
                   2359:         return $response->content;
                   2360:     }
1.15      www      2361: }
1.254     www      2362: 
1.492     albertel 2363: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2364: 
                   2365: sub allowuploaded {
                   2366:     my ($srcurl,$url)=@_;
                   2367:     $url=&clutter(&declutter($url));
                   2368:     my $dir=$url;
                   2369:     $dir=~s/\/[^\/]+$//;
                   2370:     my %httpref=();
                   2371:     my $httpurl=&hreflocation('',$url);
                   2372:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2373:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2374: }
1.477     raeburn  2375: 
1.478     albertel 2376: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2377: # input: action, courseID, current domain, intended
1.637     raeburn  2378: #        path to file, source of file, instruction to parse file for objects,
                   2379: #        ref to hash for embedded objects,
                   2380: #        ref to hash for codebase of java objects.
1.1095    raeburn  2381: #        reference to scalar to accommodate mime type determined
                   2382: #          from File::MMagic if $parser = parse.
1.637     raeburn  2383: #
1.485     raeburn  2384: # output: url to file (if action was uploaddoc), 
                   2385: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2386: #
1.478     albertel 2387: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2388: # course.
1.477     raeburn  2389: #
1.478     albertel 2390: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2391: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2392: #          course's home server.
1.477     raeburn  2393: #
1.478     albertel 2394: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2395: #          be copied from $source (current location) to 
                   2396: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2397: #         and will then be copied to
                   2398: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2399: #         course's home server.
1.485     raeburn  2400: #
1.481     raeburn  2401: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2402: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2403: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2404: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2405: #         in course's home server.
1.637     raeburn  2406: #
1.477     raeburn  2407: 
                   2408: sub process_coursefile {
1.1095    raeburn  2409:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2410:         $mimetype)=@_;
1.477     raeburn  2411:     my $fetchresult;
1.638     albertel 2412:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2413:     if ($action eq 'propagate') {
1.638     albertel 2414:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2415: 			     $home);
1.481     raeburn  2416:     } else {
1.477     raeburn  2417:         my $fpath = '';
                   2418:         my $fname = $file;
1.478     albertel 2419:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2420:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2421:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2422:         if ($action eq 'copy') {
                   2423:             if ($source eq '') {
                   2424:                 $fetchresult = 'no source file';
                   2425:                 return $fetchresult;
                   2426:             } else {
                   2427:                 my $destination = $filepath.'/'.$fname;
                   2428:                 rename($source,$destination);
                   2429:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2430:                                  $home);
1.481     raeburn  2431:             }
                   2432:         } elsif ($action eq 'uploaddoc') {
                   2433:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2434:             print $fh $env{'form.'.$source};
1.481     raeburn  2435:             close($fh);
1.637     raeburn  2436:             if ($parser eq 'parse') {
1.1024    raeburn  2437:                 my $mm = new File::MMagic;
1.1095    raeburn  2438:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2439:                 if ($type eq 'text/html') {
1.1024    raeburn  2440:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2441:                     unless ($parse_result eq 'ok') {
                   2442:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2443:                     }
1.637     raeburn  2444:                 }
1.1095    raeburn  2445:                 if (ref($mimetype)) {
                   2446:                     $$mimetype = $type;
                   2447:                 } 
1.637     raeburn  2448:             }
1.477     raeburn  2449:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2450:                                  $home);
1.481     raeburn  2451:             if ($fetchresult eq 'ok') {
                   2452:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2453:             } else {
                   2454:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2455:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2456:                 return '/adm/notfound.html';
                   2457:             }
1.477     raeburn  2458:         }
                   2459:     }
1.485     raeburn  2460:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2461:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2462:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2463:     }
                   2464:     return $fetchresult;
                   2465: }
                   2466: 
1.637     raeburn  2467: sub build_filepath {
                   2468:     my ($fpath) = @_;
                   2469:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2470:     unless ($fpath eq '') {
                   2471:         my @parts=split('/',$fpath);
                   2472:         foreach my $part (@parts) {
                   2473:             $filepath.= '/'.$part;
                   2474:             if ((-e $filepath)!=1) {
                   2475:                 mkdir($filepath,0777);
                   2476:             }
                   2477:         }
                   2478:     }
                   2479:     return $filepath;
                   2480: }
                   2481: 
                   2482: sub store_edited_file {
1.638     albertel 2483:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2484:     my $file = $primary_url;
                   2485:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2486:     my $fpath = '';
                   2487:     my $fname = $file;
                   2488:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2489:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2490:     my $filepath = &build_filepath($fpath);
                   2491:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2492:     print $fh $content;
                   2493:     close($fh);
1.638     albertel 2494:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2495:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2496: 			  $home);
1.637     raeburn  2497:     if ($$fetchresult eq 'ok') {
                   2498:         return '/uploaded/'.$fpath.'/'.$fname;
                   2499:     } else {
1.638     albertel 2500:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2501: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2502:         return '/adm/notfound.html';
                   2503:     }
                   2504: }
                   2505: 
1.531     albertel 2506: sub clean_filename {
1.831     albertel 2507:     my ($fname,$args)=@_;
1.315     www      2508: # Replace Windows backslashes by forward slashes
1.257     www      2509:     $fname=~s/\\/\//g;
1.831     albertel 2510:     if (!$args->{'keep_path'}) {
                   2511:         # Get rid of everything but the actual filename
                   2512: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2513:     }
1.315     www      2514: # Replace spaces by underscores
                   2515:     $fname=~s/\s+/\_/g;
                   2516: # Replace all other weird characters by nothing
1.831     albertel 2517:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2518: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2519: # numbers
                   2520:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2521:     return $fname;
                   2522: }
1.1051    raeburn  2523: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2524: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2525: # image with the same aspect ratio as the original, but with dimensions which do 
                   2526: # not exceed $resizewidth and $resizeheight.
                   2527:  
1.984     neumanie 2528: sub resizeImage {
1.1051    raeburn  2529:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2530:     my $ima = Image::Magick->new;
                   2531:     my $resized;
                   2532:     if (-e $img_path) {
                   2533:         $ima->Read($img_path);
                   2534:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2535:             my $width = $ima->Get('width');
                   2536:             my $height = $ima->Get('height');
                   2537:             if ($width > $resizewidth) {
                   2538: 	        my $factor = $width/$resizewidth;
                   2539:                 my $newheight = $height/$factor;
                   2540:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2541:                 $resized = 1;
                   2542:             }
                   2543:         }
                   2544:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2545:             my $width = $ima->Get('width');
                   2546:             my $height = $ima->Get('height');
                   2547:             if ($height > $resizeheight) {
                   2548:                 my $factor = $height/$resizeheight;
                   2549:                 my $newwidth = $width/$factor;
                   2550:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2551:                 $resized = 1;
                   2552:             }
                   2553:         }
                   2554:         if ($resized) {
                   2555:             $ima->Write($img_path);
                   2556:         }
                   2557:     }
                   2558:     return;
1.977     amueller 2559: }
                   2560: 
1.608     albertel 2561: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2562: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2563: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2564: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2565: #                                    canceloverwrite, or ''. 
                   2566: #                   if 'coursedoc': upload to the current course
                   2567: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2568: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2569: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2570: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2571: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2572: #        $allfiles - reference to hash for embedded objects
                   2573: #        $codebase - reference to hash for codebase of java objects
                   2574: #        $desuname - username for permanent storage of uploaded file
                   2575: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2576: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2577: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2578: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2579: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2580: #        $mimetype - reference to scalar to accommodate mime type determined
                   2581: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2582: # 
1.686     albertel 2583: # output: url of file in userspace, or error: <message> 
                   2584: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2585: 
1.531     albertel 2586: sub userfileupload {
1.1090    raeburn  2587:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2588:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2589:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2590:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2591:     $fname=&clean_filename($fname);
1.1090    raeburn  2592:     # See if there is anything left
1.257     www      2593:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2594:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2595:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2596:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2597:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2598:         my $now = time;
1.1090    raeburn  2599:         my $filepath;
1.1095    raeburn  2600:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2601:              $filepath = 'tmp/helprequests/'.$now;
                   2602:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2603:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2604:                          '_'.$env{'user.domain'}.'/pending';
                   2605:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2606:             my ($docuname,$docudom);
                   2607:             if ($destudom) {
                   2608:                 $docudom = $destudom;
                   2609:             } else {
                   2610:                 $docudom = $env{'user.domain'};
                   2611:             }
                   2612:             if ($destuname) {
                   2613:                 $docuname = $destuname;
                   2614:             } else {
                   2615:                 $docuname = $env{'user.name'};
                   2616:             }
                   2617:             if (exists($env{'form.group'})) {
                   2618:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2619:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2620:             }
                   2621:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2622:             if ($context eq 'canceloverwrite') {
                   2623:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2624:                 if (-e  $tempfile) {
                   2625:                     my @info = stat($tempfile);
                   2626:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2627:                         unlink($tempfile);
                   2628:                     }
                   2629:                 }
                   2630:                 return;
1.523     raeburn  2631:             }
                   2632:         }
1.1090    raeburn  2633:         # Create the directory if not present
1.741     raeburn  2634:         my @parts=split(/\//,$filepath);
                   2635:         my $fullpath = $perlvar{'lonDaemons'};
                   2636:         for (my $i=0;$i<@parts;$i++) {
                   2637:             $fullpath .= '/'.$parts[$i];
                   2638:             if ((-e $fullpath)!=1) {
                   2639:                 mkdir($fullpath,0777);
                   2640:             }
                   2641:         }
                   2642:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2643:         print $fh $env{'form.'.$formname};
                   2644:         close($fh);
1.1090    raeburn  2645:         if ($context eq 'existingfile') {
                   2646:             my @info = stat($fullpath.'/'.$fname);
                   2647:             return ($fullpath.'/'.$fname,$info[9]);
                   2648:         } else {
                   2649:             return $fullpath.'/'.$fname;
                   2650:         }
1.523     raeburn  2651:     }
1.995     raeburn  2652:     if ($subdir eq 'scantron') {
                   2653:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2654:     } else {
1.995     raeburn  2655:         $fname="$subdir/$fname";
                   2656:     }
1.1090    raeburn  2657:     if ($context eq 'coursedoc') {
1.638     albertel 2658: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2659: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2660:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2661:             return &finishuserfileupload($docuname,$docudom,
                   2662: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2663: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2664:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2665:         } else {
1.620     albertel 2666:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2667:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2668: 				       $fname,$formname,$parser,
1.1095    raeburn  2669: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2670:         }
1.719     banghart 2671:     } elsif (defined($destuname)) {
                   2672:         my $docuname=$destuname;
                   2673:         my $docudom=$destudom;
1.860     raeburn  2674: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2675: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2676:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2677:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2678:     } else {
1.638     albertel 2679:         my $docuname=$env{'user.name'};
                   2680:         my $docudom=$env{'user.domain'};
1.714     raeburn  2681:         if (exists($env{'form.group'})) {
                   2682:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2683:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2684:         }
1.860     raeburn  2685: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2686: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2687:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2688:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2689:     }
1.271     www      2690: }
                   2691: 
                   2692: sub finishuserfileupload {
1.860     raeburn  2693:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2694:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2695:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2696:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2697:   
1.860     raeburn  2698:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2699:     $file=$fname;
                   2700:     if ($fname=~m|/|) {
                   2701:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2702: 	$path.=$fnamepath.'/';
                   2703:     }
1.259     www      2704:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2705:     my $count;
                   2706:     for ($count=4;$count<=$#parts;$count++) {
                   2707:         $filepath.="/$parts[$count]";
                   2708:         if ((-e $filepath)!=1) {
                   2709: 	    mkdir($filepath,0777);
                   2710:         }
                   2711:     }
1.984     neumanie 2712: 
1.258     www      2713: # Save the file
                   2714:     {
1.701     albertel 2715: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2716: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2717: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2718: 	    return '/adm/notfound.html';
                   2719: 	}
1.1090    raeburn  2720:         if ($context eq 'overwrite') {
1.1117    foxr     2721:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2722:             my $target = $filepath.'/'.$file;
                   2723:             if (-e $source) {
                   2724:                 my @info = stat($source);
                   2725:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2726:                     unless (&File::Copy::move($source,$target)) {
                   2727:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2728:                         return "Moving from $source failed";
                   2729:                     }
                   2730:                 } else {
                   2731:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2732:                 }
                   2733:             } else {
                   2734:                 return "Temporary file: $source missing";
                   2735:             }
                   2736:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2737: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2738: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2739: 	    return '/adm/notfound.html';
                   2740: 	}
1.570     albertel 2741: 	close(FH);
1.1051    raeburn  2742:         if ($resizewidth && $resizeheight) {
                   2743:             my $mm = new File::MMagic;
                   2744:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2745:             if ($mime_type =~ m{^image/}) {
                   2746: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2747:             }  
1.977     amueller 2748: 	}
1.258     www      2749:     }
1.637     raeburn  2750:     if ($parser eq 'parse') {
1.1024    raeburn  2751:         my $mm = new File::MMagic;
1.1095    raeburn  2752:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2753:         if ($type eq 'text/html') {
1.1024    raeburn  2754:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2755:                                                        $allfiles,$codebase);
                   2756:             unless ($parse_result eq 'ok') {
                   2757:                 &logthis('Failed to parse '.$filepath.$file.
                   2758: 	   	         ' for embedded media: '.$parse_result); 
                   2759:             }
1.637     raeburn  2760:         }
1.1095    raeburn  2761:         if (ref($mimetype)) {
                   2762:             $$mimetype = $type;
                   2763:         }
1.637     raeburn  2764:     }
1.860     raeburn  2765:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2766:         my $input = $filepath.'/'.$file;
                   2767:         my $output = $filepath.'/'.'tn-'.$file;
                   2768:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2769:         system("convert -sample $thumbsize $input $output");
                   2770:         if (-e $filepath.'/'.'tn-'.$file) {
                   2771:             $fetchthumb  = 1; 
                   2772:         }
                   2773:     }
1.858     raeburn  2774:  
1.259     www      2775: # Notify homeserver to grep it
                   2776: #
1.984     neumanie 2777:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2778:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2779:     if ($fetchresult eq 'ok') {
1.860     raeburn  2780:         if ($fetchthumb) {
                   2781:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2782:             if ($thumbresult ne 'ok') {
                   2783:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2784:                          $docuhome.': '.$thumbresult);
                   2785:             }
                   2786:         }
1.259     www      2787: #
1.258     www      2788: # Return the URL to it
1.494     albertel 2789:         return '/uploaded/'.$path.$file;
1.263     www      2790:     } else {
1.494     albertel 2791:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2792: 		 ': '.$fetchresult);
1.263     www      2793:         return '/adm/notfound.html';
1.858     raeburn  2794:     }
1.493     albertel 2795: }
                   2796: 
1.637     raeburn  2797: sub extract_embedded_items {
1.961     raeburn  2798:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2799:     my @state = ();
                   2800:     my %javafiles = (
                   2801:                       codebase => '',
                   2802:                       code => '',
                   2803:                       archive => ''
                   2804:                     );
                   2805:     my %mediafiles = (
                   2806:                       src => '',
                   2807:                       movie => '',
                   2808:                      );
1.648     raeburn  2809:     my $p;
                   2810:     if ($content) {
                   2811:         $p = HTML::LCParser->new($content);
                   2812:     } else {
1.961     raeburn  2813:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2814:     }
1.641     albertel 2815:     while (my $t=$p->get_token()) {
1.640     albertel 2816: 	if ($t->[0] eq 'S') {
                   2817: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2818: 	    push(@state, $tagname);
1.648     raeburn  2819:             if (lc($tagname) eq 'allow') {
                   2820:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2821:             }
1.640     albertel 2822: 	    if (lc($tagname) eq 'img') {
                   2823: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2824: 	    }
1.886     albertel 2825: 	    if (lc($tagname) eq 'a') {
                   2826: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2827: 	    }
1.645     raeburn  2828:             if (lc($tagname) eq 'script') {
                   2829:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2830:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2831:                 } else {
                   2832:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2833:                 }
                   2834:             }
                   2835:             if (lc($tagname) eq 'link') {
                   2836:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2837:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2838:                 }
                   2839:             }
1.640     albertel 2840: 	    if (lc($tagname) eq 'object' ||
                   2841: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2842: 		foreach my $item (keys(%javafiles)) {
                   2843: 		    $javafiles{$item} = '';
                   2844: 		}
                   2845: 	    }
                   2846: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2847: 		my $name = lc($attr->{'name'});
                   2848: 		foreach my $item (keys(%javafiles)) {
                   2849: 		    if ($name eq $item) {
                   2850: 			$javafiles{$item} = $attr->{'value'};
                   2851: 			last;
                   2852: 		    }
                   2853: 		}
                   2854: 		foreach my $item (keys(%mediafiles)) {
                   2855: 		    if ($name eq $item) {
                   2856: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2857: 			last;
                   2858: 		    }
                   2859: 		}
                   2860: 	    }
                   2861: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2862: 		foreach my $item (keys(%javafiles)) {
                   2863: 		    if ($attr->{$item}) {
                   2864: 			$javafiles{$item} = $attr->{$item};
                   2865: 			last;
                   2866: 		    }
                   2867: 		}
                   2868: 		foreach my $item (keys(%mediafiles)) {
                   2869: 		    if ($attr->{$item}) {
                   2870: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2871: 			last;
                   2872: 		    }
                   2873: 		}
                   2874: 	    }
                   2875: 	} elsif ($t->[0] eq 'E') {
                   2876: 	    my ($tagname) = ($t->[1]);
                   2877: 	    if ($javafiles{'codebase'} ne '') {
                   2878: 		$javafiles{'codebase'} .= '/';
                   2879: 	    }  
                   2880: 	    if (lc($tagname) eq 'applet' ||
                   2881: 		lc($tagname) eq 'object' ||
                   2882: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2883: 		) {
                   2884: 		foreach my $item (keys(%javafiles)) {
                   2885: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2886: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2887: 			&add_filetype($allfiles,$file,$item);
                   2888: 		    }
                   2889: 		}
                   2890: 	    } 
                   2891: 	    pop @state;
                   2892: 	}
                   2893:     }
1.637     raeburn  2894:     return 'ok';
                   2895: }
                   2896: 
1.639     albertel 2897: sub add_filetype {
                   2898:     my ($allfiles,$file,$type)=@_;
                   2899:     if (exists($allfiles->{$file})) {
                   2900: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2901: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2902: 	}
                   2903:     } else {
                   2904: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2905:     }
                   2906: }
                   2907: 
1.493     albertel 2908: sub removeuploadedurl {
1.984     neumanie 2909:     my ($url)=@_;	
                   2910:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2911:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2912: }
                   2913: 
                   2914: sub removeuserfile {
                   2915:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2916:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2917:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2918:     if ($result eq 'ok') {	
1.798     raeburn  2919:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2920:             my $metafile = $fname.'.meta';
                   2921:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2922: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2923:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2924:             my $sqlresult = 
1.823     albertel 2925:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2926:                                         'portfolio_metadata',$group,
                   2927:                                         'delete');
1.798     raeburn  2928:         }
                   2929:     }
                   2930:     return $result;
1.257     www      2931: }
1.15      www      2932: 
1.530     albertel 2933: sub mkdiruserfile {
                   2934:     my ($docuname,$docudom,$dir)=@_;
                   2935:     my $home=&homeserver($docuname,$docudom);
                   2936:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2937: }
                   2938: 
1.531     albertel 2939: sub renameuserfile {
                   2940:     my ($docuname,$docudom,$old,$new)=@_;
                   2941:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2942:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2943:                         &escape("$old").':'.&escape("$new"),$home);
                   2944:     if ($result eq 'ok') {
                   2945:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2946:             my $oldmeta = $old.'.meta';
                   2947:             my $newmeta = $new.'.meta';
                   2948:             my $metaresult = 
                   2949:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2950: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2951:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2952:             my $sqlresult = 
1.823     albertel 2953:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2954:                                         'portfolio_metadata',$group,
                   2955:                                         'delete');
1.798     raeburn  2956:         }
                   2957:     }
                   2958:     return $result;
1.531     albertel 2959: }
                   2960: 
1.14      www      2961: # ------------------------------------------------------------------------- Log
                   2962: 
                   2963: sub log {
                   2964:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2965:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2966: }
                   2967: 
                   2968: # ------------------------------------------------------------------ Course Log
1.352     www      2969: #
                   2970: # This routine flushes several buffers of non-mission-critical nature
                   2971: #
1.157     www      2972: 
                   2973: sub flushcourselogs {
1.352     www      2974:     &logthis('Flushing log buffers');
                   2975: #
                   2976: # course logs
                   2977: # This is a log of all transactions in a course, which can be used
                   2978: # for data mining purposes
                   2979: #
                   2980: # It also collects the courseid database, which lists last transaction
                   2981: # times and course titles for all courseids
                   2982: #
                   2983:     my %courseidbuffer=();
1.921     raeburn  2984:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2985:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2986: 		          &escape($courselogs{$crsid}),
                   2987: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2988: 	    delete $courselogs{$crsid};
                   2989:         } else {
                   2990:             &logthis('Failed to flush log buffer for '.$crsid);
                   2991:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2992:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2993:                         " exceeded maximum size, deleting.</font>");
                   2994:                delete $courselogs{$crsid};
                   2995:             }
1.352     www      2996:         }
1.920     raeburn  2997:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2998:             'description' => $coursedescrbuf{$crsid},
                   2999:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3000:             'type'        => $coursetypebuf{$crsid},
                   3001:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3002:         };
1.191     harris41 3003:     }
1.352     www      3004: #
                   3005: # Write course id database (reverse lookup) to homeserver of courses 
                   3006: # Is used in pickcourse
                   3007: #
1.840     albertel 3008:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3009:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3010:                                     $courseidbuffer{$crs_home},
                   3011:                                     $crs_home,'timeonly');
1.352     www      3012:     }
                   3013: #
                   3014: # File accesses
                   3015: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3016: #
1.449     matthew  3017:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3018:         if ($entry =~ /___count$/) {
                   3019:             my ($dom,$name);
1.807     albertel 3020:             ($dom,$name,undef)=
1.811     albertel 3021: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3022:             if (! defined($dom) || $dom eq '' || 
                   3023:                 ! defined($name) || $name eq '') {
1.620     albertel 3024:                 my $cid = $env{'request.course.id'};
                   3025:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3026:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3027:             }
1.450     matthew  3028:             my $value = $accesshash{$entry};
                   3029:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3030:             my %temphash=($url => $value);
1.449     matthew  3031:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3032:             if ($result eq 'ok') {
                   3033:                 delete $accesshash{$entry};
                   3034:             } elsif ($result eq 'unknown_cmd') {
                   3035:                 # Target server has old code running on it.
1.450     matthew  3036:                 my %temphash=($entry => $value);
1.449     matthew  3037:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3038:                     delete $accesshash{$entry};
                   3039:                 }
                   3040:             }
                   3041:         } else {
1.811     albertel 3042:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3043:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3044:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3045:                 delete $accesshash{$entry};
                   3046:             }
1.185     www      3047:         }
1.191     harris41 3048:     }
1.352     www      3049: #
                   3050: # Roles
                   3051: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3052: #
1.800     albertel 3053:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3054:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3055: 	    split(/\:/,$entry);
                   3056:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3057:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3058:                 $rudom,$runame) eq 'ok') {
                   3059: 	    delete $userrolehash{$entry};
                   3060:         }
                   3061:     }
1.662     raeburn  3062: #
                   3063: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3064: #
                   3065:     my %domrolebuffer = ();
1.1000    raeburn  3066:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3067:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3068:         if ($domrolebuffer{$rudom}) {
                   3069:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3070:                       '='.&escape($domainrolehash{$entry});
                   3071:         } else {
                   3072:             $domrolebuffer{$rudom}.=&escape($entry).
                   3073:                       '='.&escape($domainrolehash{$entry});
                   3074:         }
                   3075:         delete $domainrolehash{$entry};
                   3076:     }
                   3077:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3078: 	my %servers = &get_servers($dom,'library');
                   3079: 	foreach my $tryserver (keys(%servers)) {
                   3080: 	    unless (&reply('domroleput:'.$dom.':'.
                   3081: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3082: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3083: 	    }
1.662     raeburn  3084:         }
                   3085:     }
1.186     www      3086:     $dumpcount++;
1.157     www      3087: }
                   3088: 
                   3089: sub courselog {
                   3090:     my $what=shift;
1.158     www      3091:     $what=time.':'.$what;
1.620     albertel 3092:     unless ($env{'request.course.id'}) { return ''; }
                   3093:     $coursedombuf{$env{'request.course.id'}}=
                   3094:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3095:     $coursenumbuf{$env{'request.course.id'}}=
                   3096:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3097:     $coursehombuf{$env{'request.course.id'}}=
                   3098:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3099:     $coursedescrbuf{$env{'request.course.id'}}=
                   3100:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3101:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3102:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3103:     $courseownerbuf{$env{'request.course.id'}}=
                   3104:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3105:     $coursetypebuf{$env{'request.course.id'}}=
                   3106:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3107:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3108: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3109:     } else {
1.620     albertel 3110: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3111:     }
1.620     albertel 3112:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3113: 	&flushcourselogs();
                   3114:     }
1.158     www      3115: }
                   3116: 
                   3117: sub courseacclog {
                   3118:     my $fnsymb=shift;
1.620     albertel 3119:     unless ($env{'request.course.id'}) { return ''; }
                   3120:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3121:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3122:         $what.=':POST';
1.583     matthew  3123:         # FIXME: Probably ought to escape things....
1.800     albertel 3124: 	foreach my $key (keys(%env)) {
                   3125:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3126:                 my $formitem = $1;
                   3127:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3128:                     $what.=':'.$formitem.'='.$env{$key};
                   3129:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3130:                     $what.=':'.$formitem.'='.$env{$key};
                   3131:                 }
1.158     www      3132:             }
1.191     harris41 3133:         }
1.583     matthew  3134:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3135:         # FIXME: We should not be depending on a form parameter that someone
                   3136:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3137:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3138:             $what.= ':POST';
                   3139:             # FIXME: Probably ought to escape things....
                   3140:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3141:                                  'crsdiscuss') {
1.620     albertel 3142:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3143:             }
                   3144:         }
1.158     www      3145:     }
                   3146:     &courselog($what);
1.149     www      3147: }
                   3148: 
1.185     www      3149: sub countacc {
                   3150:     my $url=&declutter(shift);
1.458     matthew  3151:     return if (! defined($url) || $url eq '');
1.620     albertel 3152:     unless ($env{'request.course.id'}) { return ''; }
                   3153:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3154:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3155:     $accesshash{$key}++;
1.185     www      3156: }
1.349     www      3157: 
1.361     www      3158: sub linklog {
                   3159:     my ($from,$to)=@_;
                   3160:     $from=&declutter($from);
                   3161:     $to=&declutter($to);
                   3162:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3163:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3164: }
                   3165:   
1.349     www      3166: sub userrolelog {
                   3167:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3168:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3169:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3170:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3171:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3172:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3173:        $userrolehash
                   3174:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3175:                     =$tend.':'.$tstart;
1.662     raeburn  3176:     }
1.898     albertel 3177:     if (($env{'request.role'} =~ /dc\./) &&
                   3178: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3179: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3180: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3181:          ($trole=~/^co/))) {
1.898     albertel 3182:        $userrolehash
                   3183:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3184:                     =$tend.':'.$tstart;
                   3185:     }
1.662     raeburn  3186:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3187:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3188:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3189:         ($trole=~/^sc/)) {
                   3190:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3191:        $domainrolehash
                   3192:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3193:                     = $tend.':'.$tstart;
                   3194:     }
1.351     www      3195: }
                   3196: 
1.957     raeburn  3197: sub courserolelog {
                   3198:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3199:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3200:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3201:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3202:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3203:         ($trole eq 'co')) {
1.957     raeburn  3204:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3205:             my $cdom = $1;
                   3206:             my $cnum = $2;
                   3207:             my $sec = $3;
                   3208:             my $namespace = 'rolelog';
                   3209:             my %storehash = (
                   3210:                                role    => $trole,
                   3211:                                start   => $tstart,
                   3212:                                end     => $tend,
                   3213:                                selfenroll => $selfenroll,
                   3214:                                context    => $context,
                   3215:                             );
                   3216:             if ($trole eq 'gr') {
                   3217:                 $namespace = 'groupslog';
                   3218:                 $storehash{'group'} = $sec;
                   3219:             } else {
                   3220:                 $storehash{'section'} = $sec;
                   3221:             }
                   3222:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3223:             if (($trole ne 'st') || ($sec ne '')) {
                   3224:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3225:             }
1.957     raeburn  3226:         }
                   3227:     }
                   3228:     return;
                   3229: }
                   3230: 
1.351     www      3231: sub get_course_adv_roles {
1.948     raeburn  3232:     my ($cid,$codes) = @_;
1.620     albertel 3233:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3234:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3235:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3236:     my %nothide=();
1.800     albertel 3237:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3238:         if ($user !~ /:/) {
                   3239: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3240:         } else {
                   3241:             $nothide{$user}=1;
                   3242:         }
1.470     www      3243:     }
1.351     www      3244:     my %returnhash=();
                   3245:     my %dumphash=
                   3246:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3247:     my $now=time;
1.997     raeburn  3248:     my %privileged;
1.1000    raeburn  3249:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3250: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3251:         if (($tstart) && ($tstart<0)) { next; }
                   3252:         if (($tend) && ($tend<$now)) { next; }
                   3253:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3254:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3255: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3256:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3257:             my %dompersonnel =
1.998     raeburn  3258:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3259:             $privileged{$domain} = {};
                   3260:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3261:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3262:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3263:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3264:                         $privileged{$udom}{$uname} = 1;
                   3265:                     }
                   3266:                 }
                   3267:             }
                   3268:         }
                   3269:         if ((exists($privileged{$domain}{$username})) && 
                   3270:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3271: 	if ($role eq 'cr') { next; }
1.948     raeburn  3272:         if ($codes) {
                   3273:             if ($section) { $role .= ':'.$section; }
                   3274:             if ($returnhash{$role}) {
                   3275:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3276:             } else {
                   3277:                 $returnhash{$role}=$username.':'.$domain;
                   3278:             }
1.351     www      3279:         } else {
1.988     raeburn  3280:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3281:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3282:             if ($returnhash{$key}) {
                   3283: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3284:             } else {
                   3285:                 $returnhash{$key}=$username.':'.$domain;
                   3286:             }
1.351     www      3287:         }
1.948     raeburn  3288:     }
1.400     www      3289:     return %returnhash;
                   3290: }
                   3291: 
                   3292: sub get_my_roles {
1.937     raeburn  3293:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3294:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3295:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3296:     my (%dumphash,%nothide);
1.1086    raeburn  3297:     if ($context eq 'userroles') {
                   3298:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3299:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3300:     } else {
                   3301:         %dumphash=
1.400     www      3302:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3303:         if ($hidepriv) {
                   3304:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3305:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3306:                 if ($user !~ /:/) {
                   3307:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3308:                 } else {
                   3309:                     $nothide{$user} = 1;
                   3310:                 }
                   3311:             }
                   3312:         }
1.858     raeburn  3313:     }
1.400     www      3314:     my %returnhash=();
                   3315:     my $now=time;
1.999     raeburn  3316:     my %privileged;
1.800     albertel 3317:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3318:         my ($role,$tend,$tstart);
                   3319:         if ($context eq 'userroles') {
                   3320: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3321:         } else {
                   3322:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3323:         }
1.400     www      3324:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3325:         my $status = 'active';
1.939     raeburn  3326:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3327:             $status = 'previous';
                   3328:         } 
                   3329:         if (($tstart) && ($now<$tstart)) {
                   3330:             $status = 'future';
                   3331:         }
                   3332:         if (ref($types) eq 'ARRAY') {
                   3333:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3334:                 next;
                   3335:             } 
                   3336:         } else {
                   3337:             if ($status ne 'active') {
                   3338:                 next;
                   3339:             }
                   3340:         }
1.867     raeburn  3341:         my ($rolecode,$username,$domain,$section,$area);
                   3342:         if ($context eq 'userroles') {
                   3343:             ($area,$rolecode) = split(/_/,$entry);
                   3344:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3345:         } else {
                   3346:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3347:         }
1.832     raeburn  3348:         if (ref($roledoms) eq 'ARRAY') {
                   3349:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3350:                 next;
                   3351:             }
                   3352:         }
                   3353:         if (ref($roles) eq 'ARRAY') {
                   3354:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3355:                 if ($role =~ /^cr\//) {
                   3356:                     if (!grep(/^cr$/,@{$roles})) {
                   3357:                         next;
                   3358:                     }
1.1104    raeburn  3359:                 } elsif ($role =~ /^gr\//) {
                   3360:                     if (!grep(/^gr$/,@{$roles})) {
                   3361:                         next;
                   3362:                     }
1.922     raeburn  3363:                 } else {
                   3364:                     next;
                   3365:                 }
1.832     raeburn  3366:             }
1.867     raeburn  3367:         }
1.937     raeburn  3368:         if ($hidepriv) {
1.999     raeburn  3369:             if ($context eq 'userroles') {
                   3370:                 if ((&privileged($username,$domain)) &&
                   3371:                     (!$nothide{$username.':'.$domain})) {
                   3372:                     next;
                   3373:                 }
                   3374:             } else {
                   3375:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3376:                     my %dompersonnel =
                   3377:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3378:                     $privileged{$domain} = {};
                   3379:                     if (keys(%dompersonnel)) {
                   3380:                         foreach my $server (keys(%dompersonnel)) {
                   3381:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3382:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3383:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3384:                                     $privileged{$udom}{$uname} = $trole;
                   3385:                                 }
                   3386:                             }
                   3387:                         }
                   3388:                     }
                   3389:                 }
                   3390:                 if (exists($privileged{$domain}{$username})) {
                   3391:                     if (!$nothide{$username.':'.$domain}) {
                   3392:                         next;
                   3393:                     }
                   3394:                 }
1.937     raeburn  3395:             }
                   3396:         }
1.933     raeburn  3397:         if ($withsec) {
                   3398:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3399:                 $tstart.':'.$tend;
                   3400:         } else {
                   3401:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3402:         }
1.832     raeburn  3403:     }
1.373     www      3404:     return %returnhash;
1.399     www      3405: }
                   3406: 
                   3407: # ----------------------------------------------------- Frontpage Announcements
                   3408: #
                   3409: #
                   3410: 
                   3411: sub postannounce {
                   3412:     my ($server,$text)=@_;
1.844     albertel 3413:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3414:     unless ($text=~/\w/) { $text=''; }
                   3415:     return &reply('setannounce:'.&escape($text),$server);
                   3416: }
                   3417: 
                   3418: sub getannounce {
1.448     albertel 3419: 
                   3420:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3421: 	my $announcement='';
1.800     albertel 3422: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3423: 	close($fh);
1.399     www      3424: 	if ($announcement=~/\w/) { 
                   3425: 	    return 
                   3426:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3427:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3428: 	} else {
                   3429: 	    return '';
                   3430: 	}
                   3431:     } else {
                   3432: 	return '';
                   3433:     }
1.351     www      3434: }
1.353     www      3435: 
                   3436: # ---------------------------------------------------------- Course ID routines
                   3437: # Deal with domain's nohist_courseid.db files
                   3438: #
                   3439: 
                   3440: sub courseidput {
1.921     raeburn  3441:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3442:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3443:     my $outcome;
                   3444:     if ($caller eq 'timeonly') {
                   3445:         my $cids = '';
                   3446:         foreach my $item (keys(%$storehash)) {
                   3447:             $cids.=&escape($item).'&';
                   3448:         }
                   3449:         $cids=~s/\&$//;
                   3450:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3451:                           $coursehome);       
                   3452:     } else {
                   3453:         my $items = '';
                   3454:         foreach my $item (keys(%$storehash)) {
                   3455:             $items.= &escape($item).'='.
                   3456:                      &freeze_escape($$storehash{$item}).'&';
                   3457:         }
                   3458:         $items=~s/\&$//;
                   3459:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3460:                           $coursehome);
1.918     raeburn  3461:     }
                   3462:     if ($outcome eq 'unknown_cmd') {
                   3463:         my $what;
                   3464:         foreach my $cid (keys(%$storehash)) {
                   3465:             $what .= &escape($cid).'=';
1.921     raeburn  3466:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3467:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3468:             }
                   3469:             $what =~ s/\:$/&/;
                   3470:         }
                   3471:         $what =~ s/\&$//;  
                   3472:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3473:     } else {
                   3474:         return $outcome;
                   3475:     }
1.353     www      3476: }
                   3477: 
                   3478: sub courseiddump {
1.921     raeburn  3479:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3480:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3481:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3482:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3483:     my $as_hash = 1;
                   3484:     my %returnhash;
                   3485:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3486:     my %libserv = &all_library();
                   3487:     foreach my $tryserver (keys(%libserv)) {
                   3488:         if ( (  $hostidflag == 1 
                   3489: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3490: 	     || (!defined($hostidflag)) ) {
                   3491: 
1.918     raeburn  3492: 	    if (($domfilter eq '') ||
                   3493: 		(&host_domain($tryserver) eq $domfilter)) {
                   3494:                 my $rep = 
                   3495:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3496:                          $sincefilter.':'.&escape($descfilter).':'.
                   3497:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3498:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3499:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3500:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3501:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3502:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3503:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3504:                          &escape($creationcontext).':'.$domcloner,
                   3505:                          $tryserver);
1.918     raeburn  3506:                 my @pairs=split(/\&/,$rep);
                   3507:                 foreach my $item (@pairs) {
                   3508:                     my ($key,$value)=split(/\=/,$item,2);
                   3509:                     $key = &unescape($key);
                   3510:                     next if ($key =~ /^error: 2 /);
                   3511:                     my $result = &thaw_unescape($value);
                   3512:                     if (ref($result) eq 'HASH') {
                   3513:                         $returnhash{$key}=$result;
                   3514:                     } else {
1.921     raeburn  3515:                         my @responses = split(/:/,$value);
                   3516:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3517:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3518:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3519:                         }
1.1008    raeburn  3520:                     }
1.353     www      3521:                 }
                   3522:             }
                   3523:         }
                   3524:     }
                   3525:     return %returnhash;
                   3526: }
                   3527: 
1.1055    raeburn  3528: sub courselastaccess {
                   3529:     my ($cdom,$cnum,$hostidref) = @_;
                   3530:     my %returnhash;
                   3531:     if ($cdom && $cnum) {
                   3532:         my $chome = &homeserver($cnum,$cdom);
                   3533:         if ($chome ne 'no_host') {
                   3534:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3535:             &extract_lastaccess(\%returnhash,$rep);
                   3536:         }
                   3537:     } else {
                   3538:         if (!$cdom) { $cdom=''; }
                   3539:         my %libserv = &all_library();
                   3540:         foreach my $tryserver (keys(%libserv)) {
                   3541:             if (ref($hostidref) eq 'ARRAY') {
                   3542:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3543:             } 
                   3544:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3545:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3546:                 &extract_lastaccess(\%returnhash,$rep);
                   3547:             }
                   3548:         }
                   3549:     }
                   3550:     return %returnhash;
                   3551: }
                   3552: 
                   3553: sub extract_lastaccess {
                   3554:     my ($returnhash,$rep) = @_;
                   3555:     if (ref($returnhash) eq 'HASH') {
                   3556:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3557:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3558:                  $rep eq '') {
                   3559:             my @pairs=split(/\&/,$rep);
                   3560:             foreach my $item (@pairs) {
                   3561:                 my ($key,$value)=split(/\=/,$item,2);
                   3562:                 $key = &unescape($key);
                   3563:                 next if ($key =~ /^error: 2 /);
                   3564:                 $returnhash->{$key} = &thaw_unescape($value);
                   3565:             }
                   3566:         }
                   3567:     }
                   3568:     return;
                   3569: }
                   3570: 
1.658     raeburn  3571: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3572: 
                   3573: sub dcmailput {
1.685     raeburn  3574:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3575:     my $status = &Apache::lonnet::critical(
1.740     www      3576:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3577:        &escape($message),$server);
1.662     raeburn  3578:     return $status;
                   3579: }
                   3580: 
1.658     raeburn  3581: sub dcmaildump {
                   3582:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3583:     my %returnhash=();
1.846     albertel 3584: 
                   3585:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3586:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3587:                                                          &escape($enddate).':';
                   3588: 	my @esc_senders=map { &escape($_)} @$senders;
                   3589: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3590: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3591:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3592:             if (($key) && ($value)) {
                   3593:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3594:             }
                   3595:         }
                   3596:     }
                   3597:     return %returnhash;
                   3598: }
1.662     raeburn  3599: # ---------------------------------------------------------- Domain roles
                   3600: 
                   3601: sub get_domain_roles {
                   3602:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3603:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3604:         $startdate = '.';
                   3605:     }
1.1018    raeburn  3606:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3607:         $enddate = '.';
                   3608:     }
1.922     raeburn  3609:     my $rolelist;
                   3610:     if (ref($roles) eq 'ARRAY') {
                   3611:         $rolelist = join(':',@{$roles});
                   3612:     }
1.662     raeburn  3613:     my %personnel = ();
1.841     albertel 3614: 
                   3615:     my %servers = &get_servers($dom,'library');
                   3616:     foreach my $tryserver (keys(%servers)) {
                   3617: 	%{$personnel{$tryserver}}=();
                   3618: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3619: 					    &escape($startdate).':'.
                   3620: 					    &escape($enddate).':'.
                   3621: 					    &escape($rolelist), $tryserver))) {
                   3622: 	    my ($key,$value) = split(/\=/,$line,2);
                   3623: 	    if (($key) && ($value)) {
                   3624: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3625: 	    }
                   3626: 	}
1.662     raeburn  3627:     }
                   3628:     return %personnel;
                   3629: }
1.658     raeburn  3630: 
1.1057    www      3631: # ----------------------------------------------------------- Interval timing 
1.149     www      3632: 
1.504     albertel 3633: sub get_first_access {
                   3634:     my ($type,$argsymb)=@_;
1.790     albertel 3635:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3636:     if ($argsymb) { $symb=$argsymb; }
                   3637:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3638:     if ($type eq 'course') {
                   3639: 	$res='course';
                   3640:     } elsif ($type eq 'map') {
1.588     albertel 3641: 	$res=&symbread($map);
                   3642:     } else {
                   3643: 	$res=$symb;
                   3644:     }
                   3645:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3646:     return $times{"$courseid\0$res"};
1.504     albertel 3647: }
                   3648: 
                   3649: sub set_first_access {
                   3650:     my ($type)=@_;
1.790     albertel 3651:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3652:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3653:     if ($type eq 'course') {
                   3654: 	$res='course';
                   3655:     } elsif ($type eq 'map') {
1.588     albertel 3656: 	$res=&symbread($map);
                   3657:     } else {
                   3658: 	$res=$symb;
                   3659:     }
                   3660:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3661:     if (!$firstaccess) {
1.588     albertel 3662: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3663:     }
                   3664:     return 'already_set';
1.504     albertel 3665: }
                   3666: 
1.110     www      3667: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3668: 
                   3669: sub expirespread {
                   3670:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3671:     my $cid=$env{'request.course.id'}; 
1.110     www      3672:     if ($cid) {
                   3673:        my $now=time;
                   3674:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3675:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3676:                             $env{'course.'.$cid.'.num'}.
1.110     www      3677: 	        	    ':nohist_expirationdates:'.
                   3678:                             &escape($key).'='.$now,
1.620     albertel 3679:                             $env{'course.'.$cid.'.home'})
1.110     www      3680:     }
                   3681:     return 'ok';
1.14      www      3682: }
                   3683: 
1.109     www      3684: # ----------------------------------------------------- Devalidate Spreadsheets
                   3685: 
                   3686: sub devalidate {
1.325     www      3687:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3688:     my $cid=$env{'request.course.id'}; 
1.109     www      3689:     if ($cid) {
1.391     matthew  3690:         # delete the stored spreadsheets for
                   3691:         # - the student level sheet of this user in course's homespace
                   3692:         # - the assessment level sheet for this resource 
                   3693:         #   for this user in user's homespace
1.553     albertel 3694: 	# - current conditional state info
1.325     www      3695: 	my $key=$uname.':'.$udom.':';
1.109     www      3696:         my $status=
1.299     matthew  3697: 	    &del('nohist_calculatedsheets',
1.391     matthew  3698: 		 [$key.'studentcalc:'],
1.620     albertel 3699: 		 $env{'course.'.$cid.'.domain'},
                   3700: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3701: 		.' '.
                   3702: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3703: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3704:         unless ($status eq 'ok ok') {
                   3705:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3706:                     $uname.' at '.$udom.' for '.
1.109     www      3707: 		    $symb.': '.$status);
1.133     albertel 3708:         }
1.553     albertel 3709: 	&delenv('user.state.'.$cid);
1.109     www      3710:     }
                   3711: }
                   3712: 
1.265     albertel 3713: sub get_scalar {
                   3714:     my ($string,$end) = @_;
                   3715:     my $value;
                   3716:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3717: 	$value = $1;
                   3718:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3719: 	$value = $1;
                   3720:     }
                   3721:     return &unescape($value);
                   3722: }
                   3723: 
                   3724: sub array2str {
                   3725:   my (@array) = @_;
                   3726:   my $result=&arrayref2str(\@array);
                   3727:   $result=~s/^__ARRAY_REF__//;
                   3728:   $result=~s/__END_ARRAY_REF__$//;
                   3729:   return $result;
                   3730: }
                   3731: 
1.204     albertel 3732: sub arrayref2str {
                   3733:   my ($arrayref) = @_;
1.265     albertel 3734:   my $result='__ARRAY_REF__';
1.204     albertel 3735:   foreach my $elem (@$arrayref) {
1.265     albertel 3736:     if(ref($elem) eq 'ARRAY') {
                   3737:       $result.=&arrayref2str($elem).'&';
                   3738:     } elsif(ref($elem) eq 'HASH') {
                   3739:       $result.=&hashref2str($elem).'&';
                   3740:     } elsif(ref($elem)) {
                   3741:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3742:     } else {
                   3743:       $result.=&escape($elem).'&';
                   3744:     }
                   3745:   }
                   3746:   $result=~s/\&$//;
1.265     albertel 3747:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3748:   return $result;
                   3749: }
                   3750: 
1.168     albertel 3751: sub hash2str {
1.204     albertel 3752:   my (%hash) = @_;
                   3753:   my $result=&hashref2str(\%hash);
1.265     albertel 3754:   $result=~s/^__HASH_REF__//;
                   3755:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3756:   return $result;
                   3757: }
                   3758: 
                   3759: sub hashref2str {
                   3760:   my ($hashref)=@_;
1.265     albertel 3761:   my $result='__HASH_REF__';
1.800     albertel 3762:   foreach my $key (sort(keys(%$hashref))) {
                   3763:     if (ref($key) eq 'ARRAY') {
                   3764:       $result.=&arrayref2str($key).'=';
                   3765:     } elsif (ref($key) eq 'HASH') {
                   3766:       $result.=&hashref2str($key).'=';
                   3767:     } elsif (ref($key)) {
1.265     albertel 3768:       $result.='=';
1.800     albertel 3769:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3770:     } else {
1.800     albertel 3771: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3772:     }
                   3773: 
1.800     albertel 3774:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3775:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3776:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3777:       $result.=&hashref2str($hashref->{$key}).'&';
                   3778:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3779:        $result.='&';
1.800     albertel 3780:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3781:     } else {
1.800     albertel 3782:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3783:     }
                   3784:   }
1.168     albertel 3785:   $result=~s/\&$//;
1.265     albertel 3786:   $result .= '__END_HASH_REF__';
1.168     albertel 3787:   return $result;
                   3788: }
                   3789: 
                   3790: sub str2hash {
1.265     albertel 3791:     my ($string)=@_;
                   3792:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3793:     return %$hash;
                   3794: }
                   3795: 
                   3796: sub str2hashref {
1.168     albertel 3797:   my ($string) = @_;
1.265     albertel 3798: 
                   3799:   my %hash;
                   3800: 
                   3801:   if($string !~ /^__HASH_REF__/) {
                   3802:       if (! ($string eq '' || !defined($string))) {
                   3803: 	  $hash{'error'}='Not hash reference';
                   3804:       }
                   3805:       return (\%hash, $string);
                   3806:   }
                   3807: 
                   3808:   $string =~ s/^__HASH_REF__//;
                   3809: 
                   3810:   while($string !~ /^__END_HASH_REF__/) {
                   3811:       #key
                   3812:       my $key='';
                   3813:       if($string =~ /^__HASH_REF__/) {
                   3814:           ($key, $string)=&str2hashref($string);
                   3815:           if(defined($key->{'error'})) {
                   3816:               $hash{'error'}='Bad data';
                   3817:               return (\%hash, $string);
                   3818:           }
                   3819:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3820:           ($key, $string)=&str2arrayref($string);
                   3821:           if($key->[0] eq 'Array reference error') {
                   3822:               $hash{'error'}='Bad data';
                   3823:               return (\%hash, $string);
                   3824:           }
                   3825:       } else {
                   3826:           $string =~ s/^(.*?)=//;
1.267     albertel 3827: 	  $key=&unescape($1);
1.265     albertel 3828:       }
                   3829:       $string =~ s/^=//;
                   3830: 
                   3831:       #value
                   3832:       my $value='';
                   3833:       if($string =~ /^__HASH_REF__/) {
                   3834:           ($value, $string)=&str2hashref($string);
                   3835:           if(defined($value->{'error'})) {
                   3836:               $hash{'error'}='Bad data';
                   3837:               return (\%hash, $string);
                   3838:           }
                   3839:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3840:           ($value, $string)=&str2arrayref($string);
                   3841:           if($value->[0] eq 'Array reference error') {
                   3842:               $hash{'error'}='Bad data';
                   3843:               return (\%hash, $string);
                   3844:           }
                   3845:       } else {
                   3846: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3847:       }
                   3848:       $string =~ s/^&//;
                   3849: 
                   3850:       $hash{$key}=$value;
1.204     albertel 3851:   }
1.265     albertel 3852: 
                   3853:   $string =~ s/^__END_HASH_REF__//;
                   3854: 
                   3855:   return (\%hash, $string);
1.204     albertel 3856: }
                   3857: 
                   3858: sub str2array {
1.265     albertel 3859:     my ($string)=@_;
                   3860:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3861:     return @$array;
                   3862: }
                   3863: 
                   3864: sub str2arrayref {
1.204     albertel 3865:   my ($string) = @_;
1.265     albertel 3866:   my @array;
                   3867: 
                   3868:   if($string !~ /^__ARRAY_REF__/) {
                   3869:       if (! ($string eq '' || !defined($string))) {
                   3870: 	  $array[0]='Array reference error';
                   3871:       }
                   3872:       return (\@array, $string);
                   3873:   }
                   3874: 
                   3875:   $string =~ s/^__ARRAY_REF__//;
                   3876: 
                   3877:   while($string !~ /^__END_ARRAY_REF__/) {
                   3878:       my $value='';
                   3879:       if($string =~ /^__HASH_REF__/) {
                   3880:           ($value, $string)=&str2hashref($string);
                   3881:           if(defined($value->{'error'})) {
                   3882:               $array[0] ='Array reference error';
                   3883:               return (\@array, $string);
                   3884:           }
                   3885:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3886:           ($value, $string)=&str2arrayref($string);
                   3887:           if($value->[0] eq 'Array reference error') {
                   3888:               $array[0] ='Array reference error';
                   3889:               return (\@array, $string);
                   3890:           }
                   3891:       } else {
                   3892: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3893:       }
                   3894:       $string =~ s/^&//;
                   3895: 
                   3896:       push(@array, $value);
1.191     harris41 3897:   }
1.265     albertel 3898: 
                   3899:   $string =~ s/^__END_ARRAY_REF__//;
                   3900: 
                   3901:   return (\@array, $string);
1.168     albertel 3902: }
                   3903: 
1.167     albertel 3904: # -------------------------------------------------------------------Temp Store
                   3905: 
1.168     albertel 3906: sub tmpreset {
                   3907:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3908:   if (!$symb) {
                   3909:     $symb=&symbread();
1.620     albertel 3910:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3911:   }
                   3912:   $symb=escape($symb);
                   3913: 
1.620     albertel 3914:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3915:   $namespace=~s/\//\_/g;
                   3916:   $namespace=~s/\W//g;
                   3917: 
1.620     albertel 3918:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3919:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3920:   if ($domain eq 'public' && $stuname eq 'public') {
                   3921:       $stuname=$ENV{'REMOTE_ADDR'};
                   3922:   }
1.1117    foxr     3923:   my $path=LONCAPA::tempdir();
1.168     albertel 3924:   my %hash;
                   3925:   if (tie(%hash,'GDBM_File',
                   3926: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3927: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3928:     foreach my $key (keys(%hash)) {
1.180     albertel 3929:       if ($key=~ /:$symb/) {
1.168     albertel 3930: 	delete($hash{$key});
                   3931:       }
                   3932:     }
                   3933:   }
                   3934: }
                   3935: 
1.167     albertel 3936: sub tmpstore {
1.168     albertel 3937:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3938: 
                   3939:   if (!$symb) {
                   3940:     $symb=&symbread();
1.620     albertel 3941:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3942:   }
                   3943:   $symb=escape($symb);
                   3944: 
                   3945:   if (!$namespace) {
                   3946:     # I don't think we would ever want to store this for a course.
                   3947:     # it seems this will only be used if we don't have a course.
1.620     albertel 3948:     #$namespace=$env{'request.course.id'};
1.168     albertel 3949:     #if (!$namespace) {
1.620     albertel 3950:       $namespace=$env{'request.state'};
1.168     albertel 3951:     #}
                   3952:   }
                   3953:   $namespace=~s/\//\_/g;
                   3954:   $namespace=~s/\W//g;
1.620     albertel 3955:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3956:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3957:   if ($domain eq 'public' && $stuname eq 'public') {
                   3958:       $stuname=$ENV{'REMOTE_ADDR'};
                   3959:   }
1.168     albertel 3960:   my $now=time;
                   3961:   my %hash;
1.1117    foxr     3962:   my $path=LONCAPA::tempdir();
1.168     albertel 3963:   if (tie(%hash,'GDBM_File',
                   3964: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3965: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3966:     $hash{"version:$symb"}++;
                   3967:     my $version=$hash{"version:$symb"};
                   3968:     my $allkeys=''; 
                   3969:     foreach my $key (keys(%$storehash)) {
                   3970:       $allkeys.=$key.':';
1.591     albertel 3971:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3972:     }
                   3973:     $hash{"$version:$symb:timestamp"}=$now;
                   3974:     $allkeys.='timestamp';
                   3975:     $hash{"$version:keys:$symb"}=$allkeys;
                   3976:     if (untie(%hash)) {
                   3977:       return 'ok';
                   3978:     } else {
                   3979:       return "error:$!";
                   3980:     }
                   3981:   } else {
                   3982:     return "error:$!";
                   3983:   }
                   3984: }
1.167     albertel 3985: 
1.168     albertel 3986: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3987: 
1.168     albertel 3988: sub tmprestore {
                   3989:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3990: 
1.168     albertel 3991:   if (!$symb) {
                   3992:     $symb=&symbread();
1.620     albertel 3993:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3994:   }
                   3995:   $symb=escape($symb);
                   3996: 
1.620     albertel 3997:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3998: 
1.620     albertel 3999:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4000:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4001:   if ($domain eq 'public' && $stuname eq 'public') {
                   4002:       $stuname=$ENV{'REMOTE_ADDR'};
                   4003:   }
1.168     albertel 4004:   my %returnhash;
                   4005:   $namespace=~s/\//\_/g;
                   4006:   $namespace=~s/\W//g;
                   4007:   my %hash;
1.1117    foxr     4008:   my $path=LONCAPA::tempdir();
1.168     albertel 4009:   if (tie(%hash,'GDBM_File',
                   4010: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4011: 	  &GDBM_READER(),0640)) {
1.168     albertel 4012:     my $version=$hash{"version:$symb"};
                   4013:     $returnhash{'version'}=$version;
                   4014:     my $scope;
                   4015:     for ($scope=1;$scope<=$version;$scope++) {
                   4016:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4017:       my @keys=split(/:/,$vkeys);
                   4018:       my $key;
                   4019:       $returnhash{"$scope:keys"}=$vkeys;
                   4020:       foreach $key (@keys) {
1.591     albertel 4021: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4022: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4023:       }
                   4024:     }
1.168     albertel 4025:     if (!(untie(%hash))) {
                   4026:       return "error:$!";
                   4027:     }
                   4028:   } else {
                   4029:     return "error:$!";
                   4030:   }
                   4031:   return %returnhash;
1.167     albertel 4032: }
                   4033: 
1.9       www      4034: # ----------------------------------------------------------------------- Store
                   4035: 
                   4036: sub store {
1.124     www      4037:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4038:     my $home='';
                   4039: 
1.168     albertel 4040:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4041: 
1.213     www      4042:     $symb=&symbclean($symb);
1.122     albertel 4043:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4044: 
1.620     albertel 4045:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4046:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4047: 
                   4048:     &devalidate($symb,$stuname,$domain);
1.109     www      4049: 
                   4050:     $symb=escape($symb);
1.187     www      4051:     if (!$namespace) { 
1.620     albertel 4052:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4053:           return ''; 
                   4054:        } 
                   4055:     }
1.620     albertel 4056:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4057: 
                   4058:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4059:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4060: 
1.12      www      4061:     my $namevalue='';
1.800     albertel 4062:     foreach my $key (keys(%$storehash)) {
                   4063:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4064:     }
1.12      www      4065:     $namevalue=~s/\&$//;
1.187     www      4066:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4067:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4068: }
                   4069: 
1.47      www      4070: # -------------------------------------------------------------- Critical Store
                   4071: 
                   4072: sub cstore {
1.124     www      4073:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4074:     my $home='';
                   4075: 
1.168     albertel 4076:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4077: 
1.213     www      4078:     $symb=&symbclean($symb);
1.122     albertel 4079:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4080: 
1.620     albertel 4081:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4082:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4083: 
                   4084:     &devalidate($symb,$stuname,$domain);
1.109     www      4085: 
                   4086:     $symb=escape($symb);
1.187     www      4087:     if (!$namespace) { 
1.620     albertel 4088:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4089:           return ''; 
                   4090:        } 
                   4091:     }
1.620     albertel 4092:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4093: 
                   4094:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4095:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4096: 
1.47      www      4097:     my $namevalue='';
1.800     albertel 4098:     foreach my $key (keys(%$storehash)) {
                   4099:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4100:     }
1.47      www      4101:     $namevalue=~s/\&$//;
1.187     www      4102:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4103:     return critical
                   4104:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4105: }
                   4106: 
1.9       www      4107: # --------------------------------------------------------------------- Restore
                   4108: 
                   4109: sub restore {
1.124     www      4110:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4111:     my $home='';
                   4112: 
1.168     albertel 4113:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4114: 
1.122     albertel 4115:     if (!$symb) {
                   4116:       unless ($symb=escape(&symbread())) { return ''; }
                   4117:     } else {
1.213     www      4118:       $symb=&escape(&symbclean($symb));
1.122     albertel 4119:     }
1.188     www      4120:     if (!$namespace) { 
1.620     albertel 4121:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4122:           return ''; 
                   4123:        } 
                   4124:     }
1.620     albertel 4125:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4126:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4127:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4128:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4129: 
1.12      www      4130:     my %returnhash=();
1.800     albertel 4131:     foreach my $line (split(/\&/,$answer)) {
                   4132: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4133:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4134:     }
1.75      www      4135:     my $version;
                   4136:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4137:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4138:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4139:        }
1.75      www      4140:     }
1.13      www      4141:     return %returnhash;
1.34      www      4142: }
                   4143: 
                   4144: # ---------------------------------------------------------- Course Description
1.1118    foxr     4145: #
                   4146: #  
1.34      www      4147: 
                   4148: sub coursedescription {
1.731     albertel 4149:     my ($courseid,$args)=@_;
1.34      www      4150:     $courseid=~s/^\///;
1.49      www      4151:     $courseid=~s/\_/\//g;
1.34      www      4152:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4153:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4154:     my $normalid=$cdomain.'_'.$cnum;
                   4155:     # need to always cache even if we get errors otherwise we keep 
                   4156:     # trying and trying and trying to get the course description.
                   4157:     my %envhash=();
                   4158:     my %returnhash=();
1.731     albertel 4159:     
                   4160:     my $expiretime=600;
                   4161:     if ($env{'request.course.id'} eq $normalid) {
                   4162: 	$expiretime=120;
                   4163:     }
                   4164: 
                   4165:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4166:     if (!$args->{'freshen_cache'}
                   4167: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4168: 	foreach my $key (keys(%env)) {
                   4169: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4170: 	    my ($setting) = $1;
                   4171: 	    $returnhash{$setting} = $env{$key};
                   4172: 	}
                   4173: 	return %returnhash;
                   4174:     }
                   4175: 
1.1118    foxr     4176:     # get the data again
                   4177: 
1.731     albertel 4178:     if (!$args->{'one_time'}) {
                   4179: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4180:     }
1.811     albertel 4181: 
1.34      www      4182:     if ($chome ne 'no_host') {
1.302     albertel 4183:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4184:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4185: 	   my $username = $env{'user.name'}; # Defult username
                   4186: 	   if(defined $args->{'user'}) {
                   4187: 	       $username = $args->{'user'};
                   4188: 	   }
1.129     albertel 4189:            $returnhash{'home'}= $chome;
                   4190: 	   $returnhash{'domain'} = $cdomain;
                   4191: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4192:            if (!defined($returnhash{'type'})) {
                   4193:                $returnhash{'type'} = 'Course';
                   4194:            }
1.130     albertel 4195:            while (my ($name,$value) = each %returnhash) {
1.53      www      4196:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4197:            }
1.270     www      4198:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4199:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4200: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4201:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4202:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4203:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4204:        }
                   4205:     }
1.731     albertel 4206:     if (!$args->{'one_time'}) {
1.949     raeburn  4207: 	&appenv(\%envhash);
1.731     albertel 4208:     }
1.302     albertel 4209:     return %returnhash;
1.461     www      4210: }
                   4211: 
1.1080    raeburn  4212: sub update_released_required {
                   4213:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4214:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4215:         $cid = $env{'request.course.id'};
                   4216:         $cdom = $env{'course.'.$cid.'.domain'};
                   4217:         $cnum = $env{'course.'.$cid.'.num'};
                   4218:         $chome = $env{'course.'.$cid.'.home'};
                   4219:     }
                   4220:     if ($needsrelease) {
                   4221:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4222:         my $needsupdate;
                   4223:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4224:             $needsupdate = 1;
                   4225:         } else {
                   4226:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4227:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4228:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4229:                 $needsupdate = 1;
                   4230:             }
                   4231:         }
                   4232:         if ($needsupdate) {
                   4233:             my %needshash = (
                   4234:                              'internal.releaserequired' => $needsrelease,
                   4235:                             );
                   4236:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4237:             if ($putresult eq 'ok') {
                   4238:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4239:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4240:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4241:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4242:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4243:                 }
                   4244:             }
                   4245:         }
                   4246:     }
                   4247:     return;
                   4248: }
                   4249: 
1.461     www      4250: # -------------------------------------------------See if a user is privileged
                   4251: 
                   4252: sub privileged {
                   4253:     my ($username,$domain)=@_;
                   4254:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4255: 			&homeserver($username,$domain));
1.1033    raeburn  4256:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4257:         ($rolesdump =~ /^error:/)) {
                   4258:         return 0;
                   4259:     }
1.461     www      4260:     my $now=time;
                   4261:     if ($rolesdump ne '') {
1.800     albertel 4262:         foreach my $entry (split(/&/,$rolesdump)) {
                   4263: 	    if ($entry!~/^rolesdef_/) {
                   4264: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4265: 		$area=~s/\_\w\w$//;
                   4266: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4267: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4268: 		    my $active=1;
                   4269: 		    if ($tend) {
                   4270: 			if ($tend<$now) { $active=0; }
                   4271: 		    }
                   4272: 		    if ($tstart) {
                   4273: 			if ($tstart>$now) { $active=0; }
                   4274: 		    }
                   4275: 		    if ($active) { return 1; }
                   4276: 		}
                   4277: 	    }
                   4278: 	}
                   4279:     }
                   4280:     return 0;
1.9       www      4281: }
1.1       albertel 4282: 
1.103     harris41 4283: # -------------------------------------------------------- Get user privileges
1.11      www      4284: 
                   4285: sub rolesinit {
                   4286:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4287:     my $now=time;
                   4288:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4289:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4290:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4291:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4292:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4293:         return \%userroles;
                   4294:     }
1.11      www      4295:     my %allroles=();
1.678     raeburn  4296:     my %allgroups=();   
1.11      www      4297: 
                   4298:     if ($rolesdump ne '') {
1.800     albertel 4299:         foreach my $entry (split(/&/,$rolesdump)) {
                   4300: 	  if ($entry!~/^rolesdef_/) {
                   4301:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4302: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4303:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4304: 	    if ($role=~/^cr/) { 
1.807     albertel 4305: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4306: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4307: 		    ($tend,$tstart)=split('_',$trest);
                   4308: 		} else {
                   4309: 		    $trole=$role;
                   4310: 		}
1.678     raeburn  4311:             } elsif ($role =~ m|^gr/|) {
                   4312:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4313:                 next if ($tstart eq '-1');
1.678     raeburn  4314:                 ($trole,$group_privs) = split(/\//,$trole);
                   4315:                 $group_privs = &unescape($group_privs);
1.587     albertel 4316: 	    } else {
                   4317: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4318: 	    }
1.743     albertel 4319: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4320: 					 $username);
                   4321: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4322:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4323:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4324:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4325: 		my $spec=$trole.'.'.$area;
                   4326: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4327: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4328:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4329:                 } elsif ($trole eq 'gr') {
                   4330:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4331: 		} else {
1.567     raeburn  4332:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4333: 		}
1.12      www      4334:             }
1.662     raeburn  4335:           }
1.191     harris41 4336:         }
1.743     albertel 4337:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4338:         $userroles{'user.adv'}    = $adv;
                   4339: 	$userroles{'user.author'} = $author;
1.620     albertel 4340:         $env{'user.adv'}=$adv;
1.11      www      4341:     }
1.743     albertel 4342:     return \%userroles;  
1.11      www      4343: }
                   4344: 
1.567     raeburn  4345: sub set_arearole {
                   4346:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4347: # log the associated role with the area
                   4348:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4349:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4350: }
                   4351: 
                   4352: sub custom_roleprivs {
                   4353:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4354:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4355:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4356:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4357:         my ($rdummy,$roledef)=
                   4358:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4359:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4360:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4361:             if (defined($syspriv)) {
1.1043    raeburn  4362:                 if ($trest =~ /^$match_community$/) {
                   4363:                     $syspriv =~ s/bre\&S//; 
                   4364:                 }
1.567     raeburn  4365:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4366:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4367:             }
                   4368:             if ($tdomain ne '') {
                   4369:                 if (defined($dompriv)) {
                   4370:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4371:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4372:                 }
                   4373:                 if (($trest ne '') && (defined($coursepriv))) {
                   4374:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4375:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4376:                 }
                   4377:             }
                   4378:         }
                   4379:     }
                   4380: }
                   4381: 
1.678     raeburn  4382: sub group_roleprivs {
                   4383:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4384:     my $access = 1;
                   4385:     my $now = time;
                   4386:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4387:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4388:     if ($access) {
1.811     albertel 4389:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4390:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4391:     }
                   4392: }
1.567     raeburn  4393: 
                   4394: sub standard_roleprivs {
                   4395:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4396:     if (defined($pr{$trole.':s'})) {
                   4397:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4398:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4399:     }
                   4400:     if ($tdomain ne '') {
                   4401:         if (defined($pr{$trole.':d'})) {
                   4402:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4403:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4404:         }
                   4405:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4406:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4407:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4408:         }
                   4409:     }
                   4410: }
                   4411: 
                   4412: sub set_userprivs {
1.1064    raeburn  4413:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4414:     my $author=0;
                   4415:     my $adv=0;
1.678     raeburn  4416:     my %grouproles = ();
                   4417:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4418:         my @groupkeys; 
1.1000    raeburn  4419:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4420:             push(@groupkeys,$role);
                   4421:         }
                   4422:         if (ref($groups_roles) eq 'HASH') {
                   4423:             foreach my $key (keys(%{$groups_roles})) {
                   4424:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4425:                     push(@groupkeys,$key);
                   4426:                 }
                   4427:             }
                   4428:         }
                   4429:         if (@groupkeys > 0) {
                   4430:             foreach my $role (@groupkeys) {
                   4431:                 my ($trole,$area,$sec,$extendedarea);
                   4432:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4433:                     $trole = $1;
                   4434:                     $area = $2;
                   4435:                     $sec = $3;
                   4436:                     $extendedarea = $area.$sec;
                   4437:                     if (exists($$allgroups{$area})) {
                   4438:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4439:                             my $spec = $trole.'.'.$extendedarea;
                   4440:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4441:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4442:                         }
1.678     raeburn  4443:                     }
                   4444:                 }
                   4445:             }
                   4446:         }
                   4447:     }
1.800     albertel 4448:     foreach my $group (keys(%grouproles)) {
                   4449:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4450:     }
1.800     albertel 4451:     foreach my $role (keys(%{$allroles})) {
                   4452:         my %thesepriv;
1.941     raeburn  4453:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4454:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4455:             if ($item ne '') {
                   4456:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4457:                 if ($restrictions eq '') {
                   4458:                     $thesepriv{$privilege}='F';
                   4459:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4460:                     $thesepriv{$privilege}.=$restrictions;
                   4461:                 }
                   4462:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4463:             }
                   4464:         }
                   4465:         my $thesestr='';
1.1104    raeburn  4466:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4467: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4468: 	}
                   4469:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4470:     }
                   4471:     return ($author,$adv);
                   4472: }
                   4473: 
1.994     raeburn  4474: sub role_status {
1.1104    raeburn  4475:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4476:     my @pwhere = ();
                   4477:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4478:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4479:         unless (!defined($$role) || $$role eq '') {
                   4480:             $$where=join('.',@pwhere);
                   4481:             $$trolecode=$$role.'.'.$$where;
                   4482:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4483:             $$tstatus='is';
1.1104    raeburn  4484:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4485:                 $$tstatus='future';
1.1034    raeburn  4486:                 if ($$tstart<$now) {
                   4487:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4488:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4489:                             my (%allroles,%allgroups,$group_privs,
                   4490:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4491:                             my %userroles = (
                   4492:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4493:                             );
1.1064    raeburn  4494:                             @rolecodes = ('cm'); 
1.1002    raeburn  4495:                             my $spec=$$role.'.'.$$where;
                   4496:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4497:                             if ($$role =~ /^cr\//) {
                   4498:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4499:                                 push(@rolecodes,'cr');
1.1002    raeburn  4500:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4501:                                 push(@rolecodes,$$role);
1.1002    raeburn  4502:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4503:                                                     $env{'user.name'});
1.1064    raeburn  4504:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4505:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4506:                                 $group_privs = &unescape($group_privs);
                   4507:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4508:                                 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  4509:                                 &get_groups_roles($tdomain,$trest,
                   4510:                                                   \%course_roles,\@rolecodes,
                   4511:                                                   \%groups_roles);
1.1002    raeburn  4512:                             } else {
1.1064    raeburn  4513:                                 push(@rolecodes,$$role);
1.1002    raeburn  4514:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4515:                             }
1.1064    raeburn  4516:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4517:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4518:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4519:                         }
                   4520:                     }
1.1034    raeburn  4521:                     $$tstatus = 'is';
1.1002    raeburn  4522:                 }
1.994     raeburn  4523:             }
                   4524:             if ($$tend) {
1.1104    raeburn  4525:                 if ($$tend<$update) {
1.994     raeburn  4526:                     $$tstatus='expired';
                   4527:                 } elsif ($$tend<$now) {
                   4528:                     $$tstatus='will_not';
                   4529:                 }
                   4530:             }
                   4531:         }
                   4532:     }
                   4533: }
                   4534: 
1.1104    raeburn  4535: sub get_groups_roles {
                   4536:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4537:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4538:                   (ref($rolecodes) eq 'ARRAY') && 
                   4539:                   (ref($groups_roles) eq 'HASH')); 
                   4540:     if (keys(%{$cdom_courseroles}) > 0) {
                   4541:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4542:         if ($cdom ne '' && $cnum ne '') {
                   4543:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4544:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4545:                     my $crsrole = $1;
                   4546:                     my $crssec = $2;
                   4547:                     if ($crsrole =~ /^cr/) {
                   4548:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4549:                             push(@{$rolecodes},'cr');
                   4550:                         }
                   4551:                     } else {
                   4552:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4553:                             push(@{$rolecodes},$crsrole);
                   4554:                         }
                   4555:                     }
                   4556:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4557:                     if ($crssec ne '') {
                   4558:                         $rolekey .= "/$crssec";
                   4559:                     }
                   4560:                     $rolekey .= './';
                   4561:                     $groups_roles->{$rolekey} = $rolecodes;
                   4562:                 }
                   4563:             }
                   4564:         }
                   4565:     }
                   4566:     return;
                   4567: }
                   4568: 
                   4569: sub delete_env_groupprivs {
                   4570:     my ($where,$courseroles,$possroles) = @_;
                   4571:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4572:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4573:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4574:         %{$courseroles->{$udom}} =
                   4575:             &get_my_roles('','','userroles',['active'],
                   4576:                           $possroles,[$udom],1);
                   4577:     }
                   4578:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4579:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4580:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4581:             my $area = '/'.$cdom.'/'.$cnum;
                   4582:             my $privkey = "user.priv.$crsrole.$area";
                   4583:             if ($crssec ne '') {
                   4584:                 $privkey .= '/'.$crssec;
                   4585:             }
                   4586:             $privkey .= ".$area/$group";
                   4587:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4588:         }
                   4589:     }
                   4590:     return;
                   4591: }
                   4592: 
1.994     raeburn  4593: sub check_adhoc_privs {
1.1104    raeburn  4594:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4595:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4596:     if ($env{$cckey}) {
                   4597:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4598:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4599:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4600:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4601:         }
                   4602:     } else {
1.1088    raeburn  4603:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4604:     }
                   4605: }
                   4606: 
                   4607: sub set_adhoc_privileges {
                   4608: # role can be cc or ca
1.1088    raeburn  4609:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4610:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4611:     my $spec = $role.'.'.$area;
                   4612:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4613:                                   $env{'user.name'});
                   4614:     my %ccrole = ();
                   4615:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4616:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4617:     &appenv(\%userroles,[$role,'cm']);
                   4618:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4619:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4620:         &appenv( {'request.role'        => $spec,
                   4621:                   'request.role.domain' => $dcdom,
                   4622:                   'request.course.sec'  => ''
                   4623:                  }
                   4624:                );
                   4625:         my $tadv=0;
                   4626:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4627:         &appenv({'request.role.adv'    => $tadv});
                   4628:     }
1.994     raeburn  4629: }
                   4630: 
1.12      www      4631: # --------------------------------------------------------------- get interface
                   4632: 
                   4633: sub get {
1.131     albertel 4634:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4635:    my $items='';
1.800     albertel 4636:    foreach my $item (@$storearr) {
                   4637:        $items.=&escape($item).'&';
1.191     harris41 4638:    }
1.12      www      4639:    $items=~s/\&$//;
1.620     albertel 4640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4641:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4642:    my $uhome=&homeserver($uname,$udomain);
                   4643: 
1.133     albertel 4644:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4645:    my @pairs=split(/\&/,$rep);
1.273     albertel 4646:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4647:      return @pairs;
                   4648:    }
1.15      www      4649:    my %returnhash=();
1.42      www      4650:    my $i=0;
1.800     albertel 4651:    foreach my $item (@$storearr) {
                   4652:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4653:       $i++;
1.191     harris41 4654:    }
1.15      www      4655:    return %returnhash;
1.27      www      4656: }
                   4657: 
                   4658: # --------------------------------------------------------------- del interface
                   4659: 
                   4660: sub del {
1.133     albertel 4661:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4662:    my $items='';
1.800     albertel 4663:    foreach my $item (@$storearr) {
                   4664:        $items.=&escape($item).'&';
1.191     harris41 4665:    }
1.984     neumanie 4666: 
1.27      www      4667:    $items=~s/\&$//;
1.620     albertel 4668:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4669:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4670:    my $uhome=&homeserver($uname,$udomain);
                   4671:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4672: }
                   4673: 
                   4674: # -------------------------------------------------------------- dump interface
                   4675: 
                   4676: sub dump {
1.1086    raeburn  4677:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4678:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4679:     if (!$uname) { $uname=$env{'user.name'}; }
                   4680:     my $uhome=&homeserver($uname,$udomain);
                   4681:     if ($regexp) {
                   4682: 	$regexp=&escape($regexp);
                   4683:     } else {
                   4684: 	$regexp='.';
                   4685:     }
1.1086    raeburn  4686:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4687:     my @pairs=split(/\&/,$rep);
                   4688:     my %returnhash=();
1.1098    foxr     4689:     if (!($rep =~ /^error/ )) {
                   4690: 	foreach my $item (@pairs) {
                   4691: 	    my ($key,$value)=split(/=/,$item,2);
                   4692: 	    $key = &unescape($key);
                   4693: 	    next if ($key =~ /^error: 2 /);
                   4694: 	    $returnhash{$key}=&thaw_unescape($value);
                   4695: 	}
1.755     albertel 4696:     }
                   4697:     return %returnhash;
1.407     www      4698: }
                   4699: 
1.1098    foxr     4700: 
1.717     albertel 4701: # --------------------------------------------------------- dumpstore interface
                   4702: 
                   4703: sub dumpstore {
                   4704:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4705:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4706:    if (!$uname) { $uname=$env{'user.name'}; }
                   4707:    my $uhome=&homeserver($uname,$udomain);
                   4708:    if ($regexp) {
                   4709:        $regexp=&escape($regexp);
                   4710:    } else {
                   4711:        $regexp='.';
                   4712:    }
                   4713:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4714:    my @pairs=split(/\&/,$rep);
                   4715:    my %returnhash=();
                   4716:    foreach my $item (@pairs) {
                   4717:        my ($key,$value)=split(/=/,$item,2);
                   4718:        next if ($key =~ /^error: 2 /);
                   4719:        $returnhash{$key}=&thaw_unescape($value);
                   4720:    }
                   4721:    return %returnhash;
1.717     albertel 4722: }
                   4723: 
1.407     www      4724: # -------------------------------------------------------------- keys interface
                   4725: 
                   4726: sub getkeys {
                   4727:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4728:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4729:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4730:    my $uhome=&homeserver($uname,$udomain);
                   4731:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4732:    my @keyarray=();
1.800     albertel 4733:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4734:       next if ($key =~ /^error: 2 /);
1.800     albertel 4735:       push(@keyarray,&unescape($key));
1.407     www      4736:    }
                   4737:    return @keyarray;
1.318     matthew  4738: }
                   4739: 
1.319     matthew  4740: # --------------------------------------------------------------- currentdump
                   4741: sub currentdump {
1.328     matthew  4742:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4743:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4744:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4745:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4746:    my $uhome = &homeserver($sname,$sdom);
                   4747:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4748:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4749:    #
1.318     matthew  4750:    my %returnhash=();
1.319     matthew  4751:    #
                   4752:    if ($rep eq "unknown_cmd") { 
                   4753:        # an old lond will not know currentdump
                   4754:        # Do a dump and make it look like a currentdump
1.822     albertel 4755:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4756:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4757:        my %hash = @tmp;
                   4758:        @tmp=();
1.424     matthew  4759:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4760:    } else {
                   4761:        my @pairs=split(/\&/,$rep);
1.800     albertel 4762:        foreach my $pair (@pairs) {
                   4763:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4764:            my ($symb,$param) = split(/:/,$key);
                   4765:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4766:                                                         &thaw_unescape($value);
1.319     matthew  4767:        }
1.191     harris41 4768:    }
1.12      www      4769:    return %returnhash;
1.424     matthew  4770: }
                   4771: 
                   4772: sub convert_dump_to_currentdump{
                   4773:     my %hash = %{shift()};
                   4774:     my %returnhash;
                   4775:     # Code ripped from lond, essentially.  The only difference
                   4776:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4777:     # we might run in to problems with parameter names =~ /^v\./
                   4778:     while (my ($key,$value) = each(%hash)) {
                   4779:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4780: 	$symb  = &unescape($symb);
                   4781: 	$param = &unescape($param);
1.424     matthew  4782:         next if ($v eq 'version' || $symb eq 'keys');
                   4783:         next if (exists($returnhash{$symb}) &&
                   4784:                  exists($returnhash{$symb}->{$param}) &&
                   4785:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4786:         $returnhash{$symb}->{$param}=$value;
                   4787:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4788:     }
                   4789:     #
                   4790:     # Remove all of the keys in the hashes which keep track of
                   4791:     # the version of the parameter.
                   4792:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4793:         # use a foreach because we are going to delete from the hash.
                   4794:         foreach my $key (keys(%$param_hash)) {
                   4795:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4796:         }
                   4797:     }
                   4798:     return \%returnhash;
1.12      www      4799: }
                   4800: 
1.627     albertel 4801: # ------------------------------------------------------ critical inc interface
                   4802: 
                   4803: sub cinc {
                   4804:     return &inc(@_,'critical');
                   4805: }
                   4806: 
1.449     matthew  4807: # --------------------------------------------------------------- inc interface
                   4808: 
                   4809: sub inc {
1.627     albertel 4810:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4811:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4812:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4813:     my $uhome=&homeserver($uname,$udomain);
                   4814:     my $items='';
                   4815:     if (! ref($store)) {
                   4816:         # got a single value, so use that instead
                   4817:         $items = &escape($store).'=&';
                   4818:     } elsif (ref($store) eq 'SCALAR') {
                   4819:         $items = &escape($$store).'=&';        
                   4820:     } elsif (ref($store) eq 'ARRAY') {
                   4821:         $items = join('=&',map {&escape($_);} @{$store});
                   4822:     } elsif (ref($store) eq 'HASH') {
                   4823:         while (my($key,$value) = each(%{$store})) {
                   4824:             $items.= &escape($key).'='.&escape($value).'&';
                   4825:         }
                   4826:     }
                   4827:     $items=~s/\&$//;
1.627     albertel 4828:     if ($critical) {
                   4829: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4830:     } else {
                   4831: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4832:     }
1.449     matthew  4833: }
                   4834: 
1.12      www      4835: # --------------------------------------------------------------- put interface
                   4836: 
                   4837: sub put {
1.134     albertel 4838:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4839:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4840:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4841:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4842:    my $items='';
1.800     albertel 4843:    foreach my $item (keys(%$storehash)) {
                   4844:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4845:    }
1.12      www      4846:    $items=~s/\&$//;
1.134     albertel 4847:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4848: }
                   4849: 
1.631     albertel 4850: # ------------------------------------------------------------ newput interface
                   4851: 
                   4852: sub newput {
                   4853:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4855:    if (!$uname) { $uname=$env{'user.name'}; }
                   4856:    my $uhome=&homeserver($uname,$udomain);
                   4857:    my $items='';
                   4858:    foreach my $key (keys(%$storehash)) {
                   4859:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4860:    }
                   4861:    $items=~s/\&$//;
                   4862:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4863: }
                   4864: 
                   4865: # ---------------------------------------------------------  putstore interface
                   4866: 
1.524     raeburn  4867: sub putstore {
1.715     albertel 4868:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4869:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4870:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4871:    my $uhome=&homeserver($uname,$udomain);
                   4872:    my $items='';
1.715     albertel 4873:    foreach my $key (keys(%$storehash)) {
                   4874:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4875:    }
1.715     albertel 4876:    $items=~s/\&$//;
1.716     albertel 4877:    my $esc_symb=&escape($symb);
                   4878:    my $esc_v=&escape($version);
1.715     albertel 4879:    my $reply =
1.716     albertel 4880:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4881: 	      $uhome);
                   4882:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4883:        # gfall back to way things use to be done
1.715     albertel 4884:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4885: 			    $uname);
1.524     raeburn  4886:    }
1.715     albertel 4887:    return $reply;
                   4888: }
                   4889: 
                   4890: sub old_putstore {
1.716     albertel 4891:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4892:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4893:     if (!$uname) { $uname=$env{'user.name'}; }
                   4894:     my $uhome=&homeserver($uname,$udomain);
                   4895:     my %newstorehash;
1.800     albertel 4896:     foreach my $item (keys(%$storehash)) {
                   4897: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4898: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4899:     }
                   4900:     my $items='';
                   4901:     my %allitems = ();
1.800     albertel 4902:     foreach my $item (keys(%newstorehash)) {
                   4903: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4904: 	    my $key = $1.':keys:'.$2;
                   4905: 	    $allitems{$key} .= $3.':';
                   4906: 	}
1.800     albertel 4907: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4908:     }
1.800     albertel 4909:     foreach my $item (keys(%allitems)) {
                   4910: 	$allitems{$item} =~ s/\:$//;
                   4911: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4912:     }
                   4913:     $items=~s/\&$//;
                   4914:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4915: }
                   4916: 
1.47      www      4917: # ------------------------------------------------------ critical put interface
                   4918: 
                   4919: sub cput {
1.134     albertel 4920:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4921:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4922:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4923:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4924:    my $items='';
1.800     albertel 4925:    foreach my $item (keys(%$storehash)) {
                   4926:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4927:    }
1.47      www      4928:    $items=~s/\&$//;
1.134     albertel 4929:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4930: }
                   4931: 
                   4932: # -------------------------------------------------------------- eget interface
                   4933: 
                   4934: sub eget {
1.133     albertel 4935:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4936:    my $items='';
1.800     albertel 4937:    foreach my $item (@$storearr) {
                   4938:        $items.=&escape($item).'&';
1.191     harris41 4939:    }
1.12      www      4940:    $items=~s/\&$//;
1.620     albertel 4941:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4942:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4943:    my $uhome=&homeserver($uname,$udomain);
                   4944:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4945:    my @pairs=split(/\&/,$rep);
                   4946:    my %returnhash=();
1.42      www      4947:    my $i=0;
1.800     albertel 4948:    foreach my $item (@$storearr) {
                   4949:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4950:       $i++;
1.191     harris41 4951:    }
1.12      www      4952:    return %returnhash;
                   4953: }
                   4954: 
1.667     albertel 4955: # ------------------------------------------------------------ tmpput interface
                   4956: sub tmpput {
1.802     raeburn  4957:     my ($storehash,$server,$context)=@_;
1.667     albertel 4958:     my $items='';
1.800     albertel 4959:     foreach my $item (keys(%$storehash)) {
                   4960: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4961:     }
                   4962:     $items=~s/\&$//;
1.802     raeburn  4963:     if (defined($context)) {
                   4964:         $items .= ':'.&escape($context);
                   4965:     }
1.667     albertel 4966:     return &reply("tmpput:$items",$server);
                   4967: }
                   4968: 
                   4969: # ------------------------------------------------------------ tmpget interface
                   4970: sub tmpget {
1.688     albertel 4971:     my ($token,$server)=@_;
                   4972:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4973:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4974:     my %returnhash;
                   4975:     foreach my $item (split(/\&/,$rep)) {
                   4976: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4977:         next if ($key =~ /^error: 2 /);
1.667     albertel 4978: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4979:     }
                   4980:     return %returnhash;
                   4981: }
                   4982: 
1.1113    raeburn  4983: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4984: sub tmpdel {
                   4985:     my ($token,$server)=@_;
                   4986:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4987:     return &reply("tmpdel:$token",$server);
                   4988: }
                   4989: 
1.765     albertel 4990: # -------------------------------------------------- portfolio access checking
                   4991: 
                   4992: sub portfolio_access {
1.766     albertel 4993:     my ($requrl) = @_;
1.765     albertel 4994:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4995:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4996:     if ($result) {
                   4997:         my %setters;
                   4998:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4999:             my ($startblock,$endblock) =
                   5000:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5001:             if ($startblock && $endblock) {
                   5002:                 return 'B';
                   5003:             }
                   5004:         } else {
                   5005:             my ($startblock,$endblock) =
                   5006:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5007:             if ($startblock && $endblock) {
                   5008:                 return 'B';
                   5009:             }
                   5010:         }
                   5011:     }
1.765     albertel 5012:     if ($result eq 'ok') {
1.766     albertel 5013:        return 'F';
1.765     albertel 5014:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5015:        return 'A';
1.765     albertel 5016:     }
1.766     albertel 5017:     return '';
1.765     albertel 5018: }
                   5019: 
                   5020: sub get_portfolio_access {
1.767     albertel 5021:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5022: 
                   5023:     if (!ref($access_hash)) {
                   5024: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5025: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5026: 						   $file_name);
                   5027: 	$access_hash = $access_controls{$file_name};
                   5028:     }
                   5029: 
1.765     albertel 5030:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5031:     my $now = time;
                   5032:     if (ref($access_hash) eq 'HASH') {
                   5033:         foreach my $key (keys(%{$access_hash})) {
                   5034:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5035:             if ($start > $now) {
                   5036:                 next;
                   5037:             }
                   5038:             if ($end && $end<$now) {
                   5039:                 next;
                   5040:             }
                   5041:             if ($scope eq 'public') {
                   5042:                 $public = $key;
                   5043:                 last;
                   5044:             } elsif ($scope eq 'guest') {
                   5045:                 $guest = $key;
                   5046:             } elsif ($scope eq 'domains') {
                   5047:                 push(@domains,$key);
                   5048:             } elsif ($scope eq 'users') {
                   5049:                 push(@users,$key);
                   5050:             } elsif ($scope eq 'course') {
                   5051:                 push(@courses,$key);
                   5052:             } elsif ($scope eq 'group') {
                   5053:                 push(@groups,$key);
                   5054:             }
                   5055:         }
                   5056:         if ($public) {
                   5057:             return 'ok';
                   5058:         }
                   5059:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5060:             if ($guest) {
                   5061:                 return $guest;
                   5062:             }
                   5063:         } else {
                   5064:             if (@domains > 0) {
                   5065:                 foreach my $domkey (@domains) {
                   5066:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5067:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5068:                             return 'ok';
                   5069:                         }
                   5070:                     }
                   5071:                 }
                   5072:             }
                   5073:             if (@users > 0) {
                   5074:                 foreach my $userkey (@users) {
1.865     raeburn  5075:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5076:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5077:                             if (ref($item) eq 'HASH') {
                   5078:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5079:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5080:                                     return 'ok';
                   5081:                                 }
                   5082:                             }
                   5083:                         }
                   5084:                     } 
1.765     albertel 5085:                 }
                   5086:             }
                   5087:             my %roleshash;
                   5088:             my @courses_and_groups = @courses;
                   5089:             push(@courses_and_groups,@groups); 
                   5090:             if (@courses_and_groups > 0) {
                   5091:                 my (%allgroups,%allroles); 
                   5092:                 my ($start,$end,$role,$sec,$group);
                   5093:                 foreach my $envkey (%env) {
1.1060    raeburn  5094:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5095:                         my $cid = $2.'_'.$3; 
                   5096:                         if ($1 eq 'gr') {
                   5097:                             $group = $4;
                   5098:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5099:                         } else {
                   5100:                             if ($4 eq '') {
                   5101:                                 $sec = 'none';
                   5102:                             } else {
                   5103:                                 $sec = $4;
                   5104:                             }
                   5105:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5106:                         }
1.811     albertel 5107:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5108:                         my $cid = $2.'_'.$3;
                   5109:                         if ($4 eq '') {
                   5110:                             $sec = 'none';
                   5111:                         } else {
                   5112:                             $sec = $4;
                   5113:                         }
                   5114:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5115:                     }
                   5116:                 }
                   5117:                 if (keys(%allroles) == 0) {
                   5118:                     return;
                   5119:                 }
                   5120:                 foreach my $key (@courses_and_groups) {
                   5121:                     my %content = %{$$access_hash{$key}};
                   5122:                     my $cnum = $content{'number'};
                   5123:                     my $cdom = $content{'domain'};
                   5124:                     my $cid = $cdom.'_'.$cnum;
                   5125:                     if (!exists($allroles{$cid})) {
                   5126:                         next;
                   5127:                     }    
                   5128:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5129:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5130:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5131:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5132:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5133:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5134:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5135:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5136:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5137:                                         if (grep/^all$/,@sections) {
                   5138:                                             return 'ok';
                   5139:                                         } else {
                   5140:                                             if (grep/^$sec$/,@sections) {
                   5141:                                                 return 'ok';
                   5142:                                             }
                   5143:                                         }
                   5144:                                     }
                   5145:                                 }
                   5146:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5147:                                     if (grep/^none$/,@groups) {
                   5148:                                         return 'ok';
                   5149:                                     }
                   5150:                                 } else {
                   5151:                                     if (grep/^all$/,@groups) {
                   5152:                                         return 'ok';
                   5153:                                     } 
                   5154:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5155:                                         if (grep/^$group$/,@groups) {
                   5156:                                             return 'ok';
                   5157:                                         }
                   5158:                                     }
                   5159:                                 } 
                   5160:                             }
                   5161:                         }
                   5162:                     }
                   5163:                 }
                   5164:             }
                   5165:             if ($guest) {
                   5166:                 return $guest;
                   5167:             }
                   5168:         }
                   5169:     }
                   5170:     return;
                   5171: }
                   5172: 
                   5173: sub course_group_datechecker {
                   5174:     my ($dates,$now,$status) = @_;
                   5175:     my ($start,$end) = split(/\./,$dates);
                   5176:     if (!$start && !$end) {
                   5177:         return 'ok';
                   5178:     }
                   5179:     if (grep/^active$/,@{$status}) {
                   5180:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5181:             return 'ok';
                   5182:         }
                   5183:     }
                   5184:     if (grep/^previous$/,@{$status}) {
                   5185:         if ($end > $now ) {
                   5186:             return 'ok';
                   5187:         }
                   5188:     }
                   5189:     if (grep/^future$/,@{$status}) {
                   5190:         if ($start > $now) {
                   5191:             return 'ok';
                   5192:         }
                   5193:     }
                   5194:     return; 
                   5195: }
                   5196: 
                   5197: sub parse_portfolio_url {
                   5198:     my ($url) = @_;
                   5199: 
                   5200:     my ($type,$udom,$unum,$group,$file_name);
                   5201:     
1.823     albertel 5202:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5203: 	$type = 1;
                   5204:         $udom = $1;
                   5205:         $unum = $2;
                   5206:         $file_name = $3;
1.823     albertel 5207:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5208: 	$type = 2;
                   5209:         $udom = $1;
                   5210:         $unum = $2;
                   5211:         $group = $3;
                   5212:         $file_name = $3.'/'.$4;
                   5213:     }
                   5214:     if (wantarray) {
                   5215: 	return ($type,$udom,$unum,$file_name,$group);
                   5216:     }
                   5217:     return $type;
                   5218: }
                   5219: 
                   5220: sub is_portfolio_url {
                   5221:     my ($url) = @_;
                   5222:     return scalar(&parse_portfolio_url($url));
                   5223: }
                   5224: 
1.798     raeburn  5225: sub is_portfolio_file {
                   5226:     my ($file) = @_;
1.820     raeburn  5227:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5228:         return 1;
                   5229:     }
                   5230:     return;
                   5231: }
                   5232: 
1.976     raeburn  5233: sub usertools_access {
1.1084    raeburn  5234:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5235:     my ($access,%tools);
                   5236:     if ($context eq '') {
                   5237:         $context = 'tools';
                   5238:     }
                   5239:     if ($context eq 'requestcourses') {
                   5240:         %tools = (
                   5241:                       official   => 1,
                   5242:                       unofficial => 1,
1.1006    raeburn  5243:                       community  => 1,
1.985     raeburn  5244:                  );
                   5245:     } else {
                   5246:         %tools = (
                   5247:                       aboutme   => 1,
                   5248:                       blog      => 1,
                   5249:                       portfolio => 1,
                   5250:                  );
                   5251:     }
1.976     raeburn  5252:     return if (!defined($tools{$tool}));
                   5253: 
                   5254:     if ((!defined($udom)) || (!defined($uname))) {
                   5255:         $udom = $env{'user.domain'};
                   5256:         $uname = $env{'user.name'};
                   5257:     }
                   5258: 
1.978     raeburn  5259:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5260:         if ($action ne 'reload') {
1.985     raeburn  5261:             if ($context eq 'requestcourses') {
                   5262:                 return $env{'environment.canrequest.'.$tool};
                   5263:             } else {
                   5264:                 return $env{'environment.availabletools.'.$tool};
                   5265:             }
                   5266:         }
1.976     raeburn  5267:     }
                   5268: 
                   5269:     my ($toolstatus,$inststatus);
                   5270: 
1.985     raeburn  5271:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5272:          ($action ne 'reload')) {
                   5273:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5274:         $inststatus = $env{'environment.inststatus'};
                   5275:     } else {
1.1084    raeburn  5276:         if (ref($userenvref) eq 'HASH') {
                   5277:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5278:             $inststatus = $userenvref->{'inststatus'};
                   5279:         } else {
                   5280:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5281:             $toolstatus = $userenv{$context.'.'.$tool};
                   5282:             $inststatus = $userenv{'inststatus'};
                   5283:         }
1.976     raeburn  5284:     }
                   5285: 
                   5286:     if ($toolstatus ne '') {
                   5287:         if ($toolstatus) {
                   5288:             $access = 1;
                   5289:         } else {
                   5290:             $access = 0;
                   5291:         }
                   5292:         return $access;
                   5293:     }
                   5294: 
1.1084    raeburn  5295:     my ($is_adv,%domdef);
                   5296:     if (ref($is_advref) eq 'HASH') {
                   5297:         $is_adv = $is_advref->{'is_adv'};
                   5298:     } else {
                   5299:         $is_adv = &is_advanced_user($udom,$uname);
                   5300:     }
                   5301:     if (ref($domdefref) eq 'HASH') {
                   5302:         %domdef = %{$domdefref};
                   5303:     } else {
                   5304:         %domdef = &get_domain_defaults($udom);
                   5305:     }
1.976     raeburn  5306:     if (ref($domdef{$tool}) eq 'HASH') {
                   5307:         if ($is_adv) {
                   5308:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5309:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5310:                     $access = 1;
                   5311:                 } else {
                   5312:                     $access = 0;
                   5313:                 }
                   5314:                 return $access;
                   5315:             }
                   5316:         }
                   5317:         if ($inststatus ne '') {
                   5318:             my ($hasaccess,$hasnoaccess);
                   5319:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5320:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5321:                     if ($domdef{$tool}{$affiliation}) {
                   5322:                         $hasaccess = 1;
                   5323:                     } else {
                   5324:                         $hasnoaccess = 1;
                   5325:                     }
                   5326:                 }
                   5327:             }
                   5328:             if ($hasaccess || $hasnoaccess) {
                   5329:                 if ($hasaccess) {
                   5330:                     $access = 1;
                   5331:                 } elsif ($hasnoaccess) {
                   5332:                     $access = 0; 
                   5333:                 }
                   5334:                 return $access;
                   5335:             }
                   5336:         } else {
                   5337:             if ($domdef{$tool}{'default'} ne '') {
                   5338:                 if ($domdef{$tool}{'default'}) {
                   5339:                     $access = 1;
                   5340:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5341:                     $access = 0;
                   5342:                 }
                   5343:                 return $access;
                   5344:             }
                   5345:         }
                   5346:     } else {
1.985     raeburn  5347:         if ($context eq 'tools') {
                   5348:             $access = 1;
                   5349:         } else {
                   5350:             $access = 0;
                   5351:         }
1.976     raeburn  5352:         return $access;
                   5353:     }
                   5354: }
                   5355: 
1.1050    raeburn  5356: sub is_course_owner {
                   5357:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5358:     if (($udom eq '') || ($uname eq '')) {
                   5359:         $udom = $env{'user.domain'};
                   5360:         $uname = $env{'user.name'};
                   5361:     }
                   5362:     unless (($udom eq '') || ($uname eq '')) {
                   5363:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5364:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5365:                 return 1;
                   5366:             } else {
                   5367:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5368:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5369:                     return 1;
                   5370:                 }
                   5371:             }
                   5372:         }
                   5373:     }
                   5374:     return;
                   5375: }
                   5376: 
1.976     raeburn  5377: sub is_advanced_user {
                   5378:     my ($udom,$uname) = @_;
1.1085    raeburn  5379:     if ($udom ne '' && $uname ne '') {
                   5380:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5381:             return $env{'user.adv'};  
                   5382:         }
                   5383:     }
1.976     raeburn  5384:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5385:     my %allroles;
                   5386:     my $is_adv;
                   5387:     foreach my $role (keys(%roleshash)) {
                   5388:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5389:         my $area = '/'.$tdomain.'/'.$trest;
                   5390:         if ($sec ne '') {
                   5391:             $area .= '/'.$sec;
                   5392:         }
                   5393:         if (($area ne '') && ($trole ne '')) {
                   5394:             my $spec=$trole.'.'.$area;
                   5395:             if ($trole =~ /^cr\//) {
                   5396:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5397:             } elsif ($trole ne 'gr') {
                   5398:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5399:             }
                   5400:         }
                   5401:     }
                   5402:     foreach my $role (keys(%allroles)) {
                   5403:         last if ($is_adv);
                   5404:         foreach my $item (split(/:/,$allroles{$role})) {
                   5405:             if ($item ne '') {
                   5406:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5407:                 if ($privilege eq 'adv') {
                   5408:                     $is_adv = 1;
                   5409:                     last;
                   5410:                 }
                   5411:             }
                   5412:         }
                   5413:     }
                   5414:     return $is_adv;
                   5415: }
1.798     raeburn  5416: 
1.1035    raeburn  5417: sub check_can_request {
1.1036    raeburn  5418:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5419:     my $canreq = 0;
                   5420:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5421:     my @options = ('approval','validate','autolimit');
                   5422:     my $optregex = join('|',@options);
                   5423:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5424:         foreach my $type (@{$types}) {
                   5425:             if (&usertools_access($env{'user.name'},
                   5426:                                   $env{'user.domain'},
                   5427:                                   $type,undef,'requestcourses')) {
                   5428:                 $canreq ++;
1.1036    raeburn  5429:                 if (ref($request_domains) eq 'HASH') {
                   5430:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5431:                 }
1.1035    raeburn  5432:                 if ($dom eq $env{'user.domain'}) {
                   5433:                     $can_request->{$type} = 1;
                   5434:                 }
                   5435:             }
                   5436:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5437:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5438:                 if (@curr > 0) {
1.1036    raeburn  5439:                     foreach my $item (@curr) {
                   5440:                         if (ref($request_domains) eq 'HASH') {
                   5441:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5442:                             if ($otherdom ne '') {
                   5443:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5444:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5445:                                         push(@{$request_domains->{$type}},$otherdom);
                   5446:                                     }
                   5447:                                 } else {
                   5448:                                     push(@{$request_domains->{$type}},$otherdom);
                   5449:                                 }
                   5450:                             }
                   5451:                         }
                   5452:                     }
                   5453:                     unless($dom eq $env{'user.domain'}) {
                   5454:                         $canreq ++;
1.1035    raeburn  5455:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5456:                             $can_request->{$type} = 1;
                   5457:                         }
                   5458:                     }
                   5459:                 }
                   5460:             }
                   5461:         }
                   5462:     }
                   5463:     return $canreq;
                   5464: }
                   5465: 
1.341     www      5466: # ---------------------------------------------- Custom access rule evaluation
                   5467: 
                   5468: sub customaccess {
                   5469:     my ($priv,$uri)=@_;
1.807     albertel 5470:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5471:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5472:     $udom = &LONCAPA::clean_domain($udom);
                   5473:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5474:     my $access=0;
1.800     albertel 5475:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5476: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5477: 	if ($type eq 'user') {
                   5478: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5479: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5480: 		if ($tdom) {
                   5481: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5482: 		}
1.896     albertel 5483: 		if ($tuname) {
                   5484: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5485: 		}
                   5486: 		$access=($effect eq 'allow');
                   5487: 		last;
                   5488: 	    }
                   5489: 	} else {
                   5490: 	    if ($role) {
                   5491: 		if ($role ne $urole) { next; }
                   5492: 	    }
                   5493: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5494: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5495: 		if ($tdom) {
                   5496: 		    if ($tdom ne $udom) { next; }
                   5497: 		}
                   5498: 		if ($tcrs) {
                   5499: 		    if ($tcrs ne $ucrs) { next; }
                   5500: 		}
                   5501: 		if ($tsec) {
                   5502: 		    if ($tsec ne $usec) { next; }
                   5503: 		}
                   5504: 		$access=($effect eq 'allow');
                   5505: 		last;
                   5506: 	    }
                   5507: 	    if ($realm eq '' && $role eq '') {
                   5508: 		$access=($effect eq 'allow');
                   5509: 	    }
1.402     bowersj2 5510: 	}
1.341     www      5511:     }
                   5512:     return $access;
                   5513: }
                   5514: 
1.103     harris41 5515: # ------------------------------------------------- Check for a user privilege
1.12      www      5516: 
                   5517: sub allowed {
1.810     raeburn  5518:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5519:     my $ver_orguri=$uri;
1.439     www      5520:     $uri=&deversion($uri);
1.152     www      5521:     my $orguri=$uri;
1.52      www      5522:     $uri=&declutter($uri);
1.809     raeburn  5523: 
1.810     raeburn  5524:     if ($priv eq 'evb') {
                   5525: # Evade communication block restrictions for specified role in a course
                   5526:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5527:             return $1;
                   5528:         } else {
                   5529:             return;
                   5530:         }
                   5531:     }
                   5532: 
1.620     albertel 5533:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5534: # Free bre access to adm and meta resources
1.775     albertel 5535:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5536: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5537: 	&& ($priv eq 'bre')) {
1.14      www      5538: 	return 'F';
1.159     www      5539:     }
                   5540: 
1.545     banghart 5541: # Free bre access to user's own portfolio contents
1.714     raeburn  5542:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5543:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5544: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5545:         my %setters;
                   5546:         my ($startblock,$endblock) = 
                   5547:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5548:         if ($startblock && $endblock) {
                   5549:             return 'B';
                   5550:         } else {
                   5551:             return 'F';
                   5552:         }
1.545     banghart 5553:     }
                   5554: 
1.762     raeburn  5555: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5556:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5557:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5558:         if (exists($env{'request.course.id'})) {
                   5559:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5560:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5561:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5562:                 my $courseprivid=$env{'request.course.id'};
                   5563:                 $courseprivid=~s/\_/\//;
                   5564:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5565:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5566:                     return $1; 
1.762     raeburn  5567:                 } else {
                   5568:                     if ($env{'request.course.sec'}) {
                   5569:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5570:                     }
                   5571:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5572:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5573:                         return $2;
                   5574:                     }
1.714     raeburn  5575:                 }
                   5576:             }
                   5577:         }
                   5578:     }
                   5579: 
1.159     www      5580: # Free bre to public access
                   5581: 
                   5582:     if ($priv eq 'bre') {
1.238     www      5583:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5584: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5585:            return 'F'; 
                   5586:         }
1.238     www      5587:         if ($copyright eq 'priv') {
                   5588:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5589: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5590: 		return '';
                   5591:             }
                   5592:         }
                   5593:         if ($copyright eq 'domain') {
                   5594:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5595: 	    unless (($env{'user.domain'} eq $1) ||
                   5596:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5597: 		return '';
                   5598:             }
1.262     matthew  5599:         }
1.620     albertel 5600:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5601:             # Library role, so allow browsing of resources in this domain.
                   5602:             return 'F';
1.238     www      5603:         }
1.341     www      5604:         if ($copyright eq 'custom') {
                   5605: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5606:         }
1.14      www      5607:     }
1.264     matthew  5608:     # Domain coordinator is trying to create a course
1.620     albertel 5609:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5610:         # uri is the requested domain in this case.
                   5611:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5612:         # a role of dc for the domain in question.
1.620     albertel 5613:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5614:     }
1.29      www      5615: 
1.52      www      5616:     my $thisallowed='';
                   5617:     my $statecond=0;
                   5618:     my $courseprivid='';
                   5619: 
1.1039    raeburn  5620:     my $ownaccess;
1.1043    raeburn  5621:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5622:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5623:         if ($uri eq '') {
                   5624:             $ownaccess = 1;
                   5625:         } else {
                   5626:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5627:                 my $udom = $env{'user.domain'};
                   5628:                 my $uname = $env{'user.name'};
                   5629:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5630:                     $ownaccess = 1;
1.1040    raeburn  5631:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5632:                     unless ($uri =~ m{\.\./}) {
                   5633:                         $ownaccess = 1;
                   5634:                     }
                   5635:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5636:                     my $now = time;
                   5637:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5638:                         my $adom = $1;
                   5639:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5640:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5641:                                 my ($start,$end) = split('.',$env{$key});
                   5642:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5643:                                     $ownaccess = 1;
                   5644:                                     last;
                   5645:                                 }
                   5646:                             }
                   5647:                         }
                   5648:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5649:                         my $adom = $1;
                   5650:                         my $aname = $2;
1.1042    raeburn  5651:                         foreach my $role ('ca','aa') { 
                   5652:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5653:                                 my ($start,$end) =
                   5654:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5655:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5656:                                     $ownaccess = 1;
                   5657:                                     last;
                   5658:                                 }
1.1039    raeburn  5659:                             }
                   5660:                         }
                   5661:                     }
                   5662:                 }
                   5663:             }
                   5664:         }
                   5665:     }
                   5666: 
1.52      www      5667: # Course
                   5668: 
1.620     albertel 5669:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5670:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5671:             $thisallowed.=$1;
                   5672:         }
1.52      www      5673:     }
1.29      www      5674: 
1.52      www      5675: # Domain
                   5676: 
1.620     albertel 5677:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5678:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5679:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5680:             $thisallowed.=$1;
                   5681:         }
1.12      www      5682:     }
1.52      www      5683: 
                   5684: # Course: uri itself is a course
1.66      www      5685:     my $courseuri=$uri;
                   5686:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5687:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5688: 
1.620     albertel 5689:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5690:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5691:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5692:             $thisallowed.=$1;
                   5693:         }
1.12      www      5694:     }
1.29      www      5695: 
1.665     albertel 5696: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5697: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5698:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5699: 	$thisallowed='';
1.671     raeburn  5700:         my ($match)=&is_on_map($uri);
                   5701:         if ($match) {
                   5702:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5703:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5704:                 $thisallowed.=$1;
                   5705:             }
                   5706:         } else {
1.705     albertel 5707:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5708:             if ($refuri) {
                   5709:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5710:                     $thisallowed='F';
1.671     raeburn  5711:                 } else {
                   5712:                     $refuri=&declutter($refuri);
                   5713:                     my ($match) = &is_on_map($refuri);
                   5714:                     if ($match) {
                   5715:                         $thisallowed='F';
                   5716:                     }
1.669     raeburn  5717:                 }
1.671     raeburn  5718:             }
                   5719:         }
1.314     www      5720:     }
1.492     albertel 5721: 
1.766     albertel 5722:     if ($priv eq 'bre'
                   5723: 	&& $thisallowed ne 'F' 
                   5724: 	&& $thisallowed ne '2'
                   5725: 	&& &is_portfolio_url($uri)) {
                   5726: 	$thisallowed = &portfolio_access($uri);
                   5727:     }
                   5728:     
1.52      www      5729: # Full access at system, domain or course-wide level? Exit.
1.29      www      5730:     if ($thisallowed=~/F/) {
                   5731: 	return 'F';
                   5732:     }
                   5733: 
1.52      www      5734: # If this is generating or modifying users, exit with special codes
1.29      www      5735: 
1.643     www      5736:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5737: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5738: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5739: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5740: 	    unless ($auname) { return $thisallowed; }
                   5741: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5742: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5743: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5744: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5745: 	}
1.52      www      5746: 	return $thisallowed;
                   5747:     }
                   5748: #
1.103     harris41 5749: # Gathered so far: system, domain and course wide privileges
1.52      www      5750: #
                   5751: # Course: See if uri or referer is an individual resource that is part of 
                   5752: # the course
                   5753: 
1.620     albertel 5754:     if ($env{'request.course.id'}) {
1.232     www      5755: 
1.620     albertel 5756:        $courseprivid=$env{'request.course.id'};
                   5757:        if ($env{'request.course.sec'}) {
                   5758:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5759:        }
                   5760:        $courseprivid=~s/\_/\//;
                   5761:        my $checkreferer=1;
1.232     www      5762:        my ($match,$cond)=&is_on_map($uri);
                   5763:        if ($match) {
                   5764:            $statecond=$cond;
1.620     albertel 5765:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5766:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5767:                $thisallowed.=$1;
                   5768:                $checkreferer=0;
                   5769:            }
1.29      www      5770:        }
1.83      www      5771:        
1.148     www      5772:        if ($checkreferer) {
1.620     albertel 5773: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5774:             unless ($refuri) {
1.800     albertel 5775:                 foreach my $key (keys(%env)) {
                   5776: 		    if ($key=~/^httpref\..*\*/) {
                   5777: 			my $pattern=$key;
1.156     www      5778:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5779:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5780:                         $pattern=~s/\//\\\//g;
1.152     www      5781:                         if ($orguri=~/$pattern/) {
1.800     albertel 5782: 			    $refuri=$env{$key};
1.148     www      5783:                         }
                   5784:                     }
1.191     harris41 5785:                 }
1.148     www      5786:             }
1.232     www      5787: 
1.148     www      5788:          if ($refuri) { 
1.152     www      5789: 	  $refuri=&declutter($refuri);
1.232     www      5790:           my ($match,$cond)=&is_on_map($refuri);
                   5791:             if ($match) {
                   5792:               my $refstatecond=$cond;
1.620     albertel 5793:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5794:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5795:                   $thisallowed.=$1;
1.53      www      5796:                   $uri=$refuri;
                   5797:                   $statecond=$refstatecond;
1.52      www      5798:               }
                   5799:           }
1.148     www      5800:         }
1.29      www      5801:        }
1.52      www      5802:    }
1.29      www      5803: 
1.52      www      5804: #
1.103     harris41 5805: # Gathered now: all privileges that could apply, and condition number
1.52      www      5806: # 
                   5807: #
                   5808: # Full or no access?
                   5809: #
1.29      www      5810: 
1.52      www      5811:     if ($thisallowed=~/F/) {
                   5812: 	return 'F';
                   5813:     }
1.29      www      5814: 
1.52      www      5815:     unless ($thisallowed) {
                   5816:         return '';
                   5817:     }
1.29      www      5818: 
1.52      www      5819: # Restrictions exist, deal with them
                   5820: #
                   5821: #   C:according to course preferences
                   5822: #   R:according to resource settings
                   5823: #   L:unless locked
                   5824: #   X:according to user session state
                   5825: #
                   5826: 
                   5827: # Possibly locked functionality, check all courses
1.54      www      5828: # Locks might take effect only after 10 minutes cache expiration for other
                   5829: # courses, and 2 minutes for current course
1.52      www      5830: 
                   5831:     my $envkey;
                   5832:     if ($thisallowed=~/L/) {
1.1000    raeburn  5833:         foreach $envkey (keys(%env)) {
1.54      www      5834:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5835:                my $courseid=$2;
                   5836:                my $roleid=$1.'.'.$2;
1.92      www      5837:                $courseid=~s/^\///;
1.54      www      5838:                my $expiretime=600;
1.620     albertel 5839:                if ($env{'request.role'} eq $roleid) {
1.54      www      5840: 		  $expiretime=120;
                   5841:                }
                   5842: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5843:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5844:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5845: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5846:                }
1.620     albertel 5847:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5848:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5849: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5850:                        &log($env{'user.domain'},$env{'user.name'},
                   5851:                             $env{'user.home'},
1.57      www      5852:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5853:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5854:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5855: 		       return '';
                   5856:                    }
                   5857:                }
1.620     albertel 5858:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5859:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5860: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5861:                        &log($env{'user.domain'},$env{'user.name'},
                   5862:                             $env{'user.home'},
1.57      www      5863:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5864:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5865:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5866: 		       return '';
                   5867:                    }
                   5868:                }
                   5869: 	   }
1.29      www      5870:        }
1.52      www      5871:     }
                   5872:    
                   5873: #
                   5874: # Rest of the restrictions depend on selected course
                   5875: #
                   5876: 
1.620     albertel 5877:     unless ($env{'request.course.id'}) {
1.766     albertel 5878: 	if ($thisallowed eq 'A') {
                   5879: 	    return 'A';
1.814     raeburn  5880:         } elsif ($thisallowed eq 'B') {
                   5881:             return 'B';
1.766     albertel 5882: 	} else {
                   5883: 	    return '1';
                   5884: 	}
1.52      www      5885:     }
1.29      www      5886: 
1.52      www      5887: #
                   5888: # Now user is definitely in a course
                   5889: #
1.53      www      5890: 
                   5891: 
                   5892: # Course preferences
                   5893: 
                   5894:    if ($thisallowed=~/C/) {
1.620     albertel 5895:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5896:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5897:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5898: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5899: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5900: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5901: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5902: 			$env{'request.course.id'});
                   5903: 	   }
1.237     www      5904:            return '';
                   5905:        }
                   5906: 
1.620     albertel 5907:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5908: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5909: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5910: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5911: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5912: 			$env{'request.course.id'});
                   5913: 	   }
1.54      www      5914:            return '';
                   5915:        }
1.53      www      5916:    }
                   5917: 
                   5918: # Resource preferences
                   5919: 
                   5920:    if ($thisallowed=~/R/) {
1.620     albertel 5921:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5922:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5923: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5924: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5925: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5926: 	   }
                   5927: 	   return '';
1.54      www      5928:        }
1.53      www      5929:    }
1.30      www      5930: 
1.246     www      5931: # Restricted by state or randomout?
1.30      www      5932: 
1.52      www      5933:    if ($thisallowed=~/X/) {
1.620     albertel 5934:       if ($env{'acc.randomout'}) {
1.579     albertel 5935: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5936:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5937:             return ''; 
                   5938:          }
1.247     www      5939:       }
                   5940:       if (&condval($statecond)) {
1.52      www      5941: 	 return '2';
                   5942:       } else {
                   5943:          return '';
                   5944:       }
                   5945:    }
1.30      www      5946: 
1.766     albertel 5947:     if ($thisallowed eq 'A') {
                   5948: 	return 'A';
1.814     raeburn  5949:     } elsif ($thisallowed eq 'B') {
                   5950:         return 'B';
1.766     albertel 5951:     }
1.52      www      5952:    return 'F';
1.232     www      5953: }
                   5954: 
1.710     albertel 5955: sub split_uri_for_cond {
                   5956:     my $uri=&deversion(&declutter(shift));
                   5957:     my @uriparts=split(/\//,$uri);
                   5958:     my $filename=pop(@uriparts);
                   5959:     my $pathname=join('/',@uriparts);
                   5960:     return ($pathname,$filename);
                   5961: }
1.232     www      5962: # --------------------------------------------------- Is a resource on the map?
                   5963: 
                   5964: sub is_on_map {
1.710     albertel 5965:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5966:     #Trying to find the conditional for the file
1.620     albertel 5967:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5968: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5969:     if ($match) {
1.289     bowersj2 5970: 	return (1,$1);
                   5971:     } else {
1.434     www      5972: 	return (0,0);
1.289     bowersj2 5973:     }
1.12      www      5974: }
                   5975: 
1.427     www      5976: # --------------------------------------------------------- Get symb from alias
                   5977: 
                   5978: sub get_symb_from_alias {
                   5979:     my $symb=shift;
                   5980:     my ($map,$resid,$url)=&decode_symb($symb);
                   5981: # Already is a symb
                   5982:     if ($url) { return $symb; }
                   5983: # Must be an alias
                   5984:     my $aliassymb='';
                   5985:     my %bighash;
1.620     albertel 5986:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5987:                             &GDBM_READER(),0640)) {
                   5988:         my $rid=$bighash{'mapalias_'.$symb};
                   5989: 	if ($rid) {
                   5990: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5991: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5992: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5993: 	}
                   5994:         untie %bighash;
                   5995:     }
                   5996:     return $aliassymb;
                   5997: }
                   5998: 
1.12      www      5999: # ----------------------------------------------------------------- Define Role
                   6000: 
                   6001: sub definerole {
                   6002:   if (allowed('mcr','/')) {
                   6003:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6004:     foreach my $role (split(':',$sysrole)) {
                   6005: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6006:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6007:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6008: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6009:                return "refused:s:$crole&$cqual"; 
                   6010:             }
                   6011:         }
1.191     harris41 6012:     }
1.800     albertel 6013:     foreach my $role (split(':',$domrole)) {
                   6014: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6015:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6016:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6017: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6018:                return "refused:d:$crole&$cqual"; 
                   6019:             }
                   6020:         }
1.191     harris41 6021:     }
1.800     albertel 6022:     foreach my $role (split(':',$courole)) {
                   6023: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6024:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6025:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6026: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6027:                return "refused:c:$crole&$cqual"; 
                   6028:             }
                   6029:         }
1.191     harris41 6030:     }
1.620     albertel 6031:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6032:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6033: 	        "rolesdef_$rolename=".
                   6034:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6035:     return reply($command,$env{'user.home'});
1.12      www      6036:   } else {
                   6037:     return 'refused';
                   6038:   }
1.105     harris41 6039: }
                   6040: 
                   6041: # ---------------- Make a metadata query against the network of library servers
                   6042: 
                   6043: sub metadata_query {
1.244     matthew  6044:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6045:     my %rhash;
1.845     albertel 6046:     my %libserv = &all_library();
1.244     matthew  6047:     my @server_list = (defined($server_array) ? @$server_array
                   6048:                                               : keys(%libserv) );
                   6049:     for my $server (@server_list) {
1.118     harris41 6050: 	unless ($custom or $customshow) {
                   6051: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6052: 	    $rhash{$server}=$reply;
                   6053: 	}
                   6054: 	else {
                   6055: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6056: 			     &escape($custom).':'.&escape($customshow),
                   6057: 			     $server);
                   6058: 	    $rhash{$server}=$reply;
                   6059: 	}
1.112     harris41 6060:     }
1.118     harris41 6061:     return \%rhash;
1.240     www      6062: }
                   6063: 
                   6064: # ----------------------------------------- Send log queries and wait for reply
                   6065: 
                   6066: sub log_query {
                   6067:     my ($uname,$udom,$query,%filters)=@_;
                   6068:     my $uhome=&homeserver($uname,$udom);
                   6069:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6070:     my $uhost=&hostname($uhome);
1.800     albertel 6071:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6072:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6073:                        $uhome);
1.479     albertel 6074:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6075:     return get_query_reply($queryid);
                   6076: }
                   6077: 
1.818     raeburn  6078: # -------------------------- Update MySQL table for portfolio file
                   6079: 
                   6080: sub update_portfolio_table {
1.821     raeburn  6081:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6082:     if ($group ne '') {
                   6083:         $file_name =~s /^\Q$group\E//;
                   6084:     }
1.818     raeburn  6085:     my $homeserver = &homeserver($uname,$udom);
                   6086:     my $queryid=
1.821     raeburn  6087:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6088:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6089:     my $reply = &get_query_reply($queryid);
                   6090:     return $reply;
                   6091: }
                   6092: 
1.899     raeburn  6093: # -------------------------- Update MySQL allusers table
                   6094: 
                   6095: sub update_allusers_table {
                   6096:     my ($uname,$udom,$names) = @_;
                   6097:     my $homeserver = &homeserver($uname,$udom);
                   6098:     my $queryid=
                   6099:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6100:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6101:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6102:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6103:                'generation='.&escape($names->{'generation'}).'%%'.
                   6104:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6105:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6106:     return;
1.899     raeburn  6107: }
                   6108: 
1.508     raeburn  6109: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6110: 
                   6111: sub fetch_enrollment_query {
1.511     raeburn  6112:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6113:     my $homeserver;
1.547     raeburn  6114:     my $maxtries = 1;
1.508     raeburn  6115:     if ($context eq 'automated') {
                   6116:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6117:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6118:     } else {
                   6119:         $homeserver = &homeserver($cnum,$dom);
                   6120:     }
1.838     albertel 6121:     my $host=&hostname($homeserver);
1.506     raeburn  6122:     my $cmd = '';
1.1000    raeburn  6123:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6124:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6125:     }
                   6126:     $cmd =~ s/%%$//;
                   6127:     $cmd = &escape($cmd);
                   6128:     my $query = 'fetchenrollment';
1.620     albertel 6129:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6130:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6131:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6132:         return 'error: '.$queryid;
                   6133:     }
1.506     raeburn  6134:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6135:     my $tries = 1;
                   6136:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6137:         $reply = &get_query_reply($queryid);
                   6138:         $tries ++;
                   6139:     }
1.526     raeburn  6140:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6141:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6142:     } else {
1.901     albertel 6143:         my @responses = split(/:/,$reply);
1.515     raeburn  6144:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6145:             foreach my $line (@responses) {
                   6146:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6147:                 $$replyref{$key} = $value;
                   6148:             }
                   6149:         } else {
1.1117    foxr     6150:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6151:             foreach my $line (@responses) {
                   6152:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6153:                 $$replyref{$key} = $value;
                   6154:                 if ($value > 0) {
1.800     albertel 6155:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6156:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6157:                         my $destname = $pathname.'/'.$filename;
                   6158:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6159:                         if ($xml_classlist =~ /^error/) {
                   6160:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6161:                         } else {
1.506     raeburn  6162:                             if ( open(FILE,">$destname") ) {
                   6163:                                 print FILE &unescape($xml_classlist);
                   6164:                                 close(FILE);
1.526     raeburn  6165:                             } else {
                   6166:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6167:                             }
                   6168:                         }
                   6169:                     }
                   6170:                 }
                   6171:             }
                   6172:         }
                   6173:         return 'ok';
                   6174:     }
                   6175:     return 'error';
                   6176: }
                   6177: 
1.242     www      6178: sub get_query_reply {
                   6179:     my $queryid=shift;
1.1117    foxr     6180:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6181:     my $reply='';
                   6182:     for (1..100) {
                   6183: 	sleep 2;
                   6184:         if (-e $replyfile.'.end') {
1.448     albertel 6185: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6186: 		$reply = join('',<$fh>);
                   6187: 		close($fh);
1.240     www      6188: 	   } else { return 'error: reply_file_error'; }
1.242     www      6189:            return &unescape($reply);
                   6190: 	}
1.240     www      6191:     }
1.242     www      6192:     return 'timeout:'.$queryid;
1.240     www      6193: }
                   6194: 
                   6195: sub courselog_query {
1.241     www      6196: #
                   6197: # possible filters:
                   6198: # url: url or symb
                   6199: # username
                   6200: # domain
                   6201: # action: view, submit, grade
                   6202: # start: timestamp
                   6203: # end: timestamp
                   6204: #
1.240     www      6205:     my (%filters)=@_;
1.620     albertel 6206:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6207:     if ($filters{'url'}) {
                   6208: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6209:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6210:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6211:     }
1.620     albertel 6212:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6213:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6214:     return &log_query($cname,$cdom,'courselog',%filters);
                   6215: }
                   6216: 
                   6217: sub userlog_query {
1.858     raeburn  6218: #
                   6219: # possible filters:
                   6220: # action: log check role
                   6221: # start: timestamp
                   6222: # end: timestamp
                   6223: #
1.240     www      6224:     my ($uname,$udom,%filters)=@_;
                   6225:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6226: }
                   6227: 
1.506     raeburn  6228: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6229: 
                   6230: sub auto_run {
1.508     raeburn  6231:     my ($cnum,$cdom) = @_;
1.876     raeburn  6232:     my $response = 0;
                   6233:     my $settings;
                   6234:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6235:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6236:         $settings = $domconfig{'autoenroll'};
                   6237:         if ($settings->{'run'} eq '1') {
                   6238:             $response = 1;
                   6239:         }
                   6240:     } else {
1.934     raeburn  6241:         my $homeserver;
                   6242:         if (&is_course($cdom,$cnum)) {
                   6243:             $homeserver = &homeserver($cnum,$cdom);
                   6244:         } else {
                   6245:             $homeserver = &domain($cdom,'primary');
                   6246:         }
                   6247:         if ($homeserver ne 'no_host') {
                   6248:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6249:         }
1.876     raeburn  6250:     }
1.506     raeburn  6251:     return $response;
                   6252: }
1.776     albertel 6253: 
1.506     raeburn  6254: sub auto_get_sections {
1.508     raeburn  6255:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6256:     my $homeserver;
                   6257:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6258:         $homeserver = &homeserver($cnum,$cdom);
                   6259:     }
                   6260:     if (!defined($homeserver)) { 
                   6261:         if ($cdom =~ /^$match_domain$/) {
                   6262:             $homeserver = &domain($cdom,'primary');
                   6263:         }
                   6264:     }
                   6265:     my @secs;
                   6266:     if (defined($homeserver)) {
                   6267:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6268:         unless ($response eq 'refused') {
                   6269:             @secs = split(/:/,$response);
                   6270:         }
1.506     raeburn  6271:     }
                   6272:     return @secs;
                   6273: }
1.776     albertel 6274: 
1.506     raeburn  6275: sub auto_new_course {
1.1099    raeburn  6276:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6277:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6278:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6279:     return $response;
                   6280: }
1.776     albertel 6281: 
1.506     raeburn  6282: sub auto_validate_courseID {
1.508     raeburn  6283:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6284:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6285:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6286:     return $response;
                   6287: }
1.776     albertel 6288: 
1.1007    raeburn  6289: sub auto_validate_instcode {
1.1020    raeburn  6290:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6291:     my ($homeserver,$response);
                   6292:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6293:         $homeserver = &homeserver($cnum,$cdom);
                   6294:     }
                   6295:     if (!defined($homeserver)) {
                   6296:         if ($cdom =~ /^$match_domain$/) {
                   6297:             $homeserver = &domain($cdom,'primary');
                   6298:         }
                   6299:     }
1.1065    raeburn  6300:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6301:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6302:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6303:     return ($outcome,$description);
1.1007    raeburn  6304: }
                   6305: 
1.506     raeburn  6306: sub auto_create_password {
1.873     raeburn  6307:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6308:     my ($homeserver,$response);
1.506     raeburn  6309:     my $create_passwd = 0;
                   6310:     my $authchk = '';
1.873     raeburn  6311:     if ($udom =~ /^$match_domain$/) {
                   6312:         $homeserver = &domain($udom,'primary');
                   6313:     }
                   6314:     if ($homeserver eq '') {
                   6315:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6316:             $homeserver = &homeserver($cnum,$cdom);
                   6317:         }
                   6318:     }
                   6319:     if ($homeserver eq '') {
                   6320:         $authchk = 'nodomain';
1.506     raeburn  6321:     } else {
1.873     raeburn  6322:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6323:         if ($response eq 'refused') {
                   6324:             $authchk = 'refused';
                   6325:         } else {
1.901     albertel 6326:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6327:         }
1.506     raeburn  6328:     }
                   6329:     return ($authparam,$create_passwd,$authchk);
                   6330: }
                   6331: 
1.706     raeburn  6332: sub auto_photo_permission {
                   6333:     my ($cnum,$cdom,$students) = @_;
                   6334:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6335:     my ($outcome,$perm_reqd,$conditions) = 
                   6336: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6337:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6338: 	return (undef,undef);
                   6339:     }
1.706     raeburn  6340:     return ($outcome,$perm_reqd,$conditions);
                   6341: }
                   6342: 
                   6343: sub auto_checkphotos {
                   6344:     my ($uname,$udom,$pid) = @_;
                   6345:     my $homeserver = &homeserver($uname,$udom);
                   6346:     my ($result,$resulttype);
                   6347:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6348: 				   &escape($uname).':'.&escape($pid),
                   6349: 				   $homeserver));
1.709     albertel 6350:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6351: 	return (undef,undef);
                   6352:     }
1.706     raeburn  6353:     if ($outcome) {
                   6354:         ($result,$resulttype) = split(/:/,$outcome);
                   6355:     } 
                   6356:     return ($result,$resulttype);
                   6357: }
                   6358: 
                   6359: sub auto_photochoice {
                   6360:     my ($cnum,$cdom) = @_;
                   6361:     my $homeserver = &homeserver($cnum,$cdom);
                   6362:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6363: 						       &escape($cdom),
                   6364: 						       $homeserver)));
1.709     albertel 6365:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6366: 	return (undef,undef);
                   6367:     }
1.706     raeburn  6368:     return ($update,$comment);
                   6369: }
                   6370: 
                   6371: sub auto_photoupdate {
                   6372:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6373:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6374:     my $host=&hostname($homeserver);
1.706     raeburn  6375:     my $cmd = '';
                   6376:     my $maxtries = 1;
1.800     albertel 6377:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6378:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6379:     }
                   6380:     $cmd =~ s/%%$//;
                   6381:     $cmd = &escape($cmd);
                   6382:     my $query = 'institutionalphotos';
                   6383:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6384:     unless ($queryid=~/^\Q$host\E\_/) {
                   6385:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6386:         return 'error: '.$queryid;
                   6387:     }
                   6388:     my $reply = &get_query_reply($queryid);
                   6389:     my $tries = 1;
                   6390:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6391:         $reply = &get_query_reply($queryid);
                   6392:         $tries ++;
                   6393:     }
                   6394:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6395:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6396:     } else {
                   6397:         my @responses = split(/:/,$reply);
                   6398:         my $outcome = shift(@responses); 
                   6399:         foreach my $item (@responses) {
                   6400:             my ($key,$value) = split(/=/,$item);
                   6401:             $$photo{$key} = $value;
                   6402:         }
                   6403:         return $outcome;
                   6404:     }
                   6405:     return 'error';
                   6406: }
                   6407: 
1.521     raeburn  6408: sub auto_instcode_format {
1.793     albertel 6409:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6410: 	$cat_order) = @_;
1.521     raeburn  6411:     my $courses = '';
1.772     raeburn  6412:     my @homeservers;
1.521     raeburn  6413:     if ($caller eq 'global') {
1.841     albertel 6414: 	my %servers = &get_servers($codedom,'library');
                   6415: 	foreach my $tryserver (keys(%servers)) {
                   6416: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6417: 		push(@homeservers,$tryserver);
                   6418: 	    }
1.584     raeburn  6419:         }
1.1022    raeburn  6420:     } elsif ($caller eq 'requests') {
                   6421:         if ($codedom =~ /^$match_domain$/) {
                   6422:             my $chome = &domain($codedom,'primary');
                   6423:             unless ($chome eq 'no_host') {
                   6424:                 push(@homeservers,$chome);
                   6425:             }
                   6426:         }
1.521     raeburn  6427:     } else {
1.772     raeburn  6428:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6429:     }
1.793     albertel 6430:     foreach my $code (keys(%{$instcodes})) {
                   6431:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6432:     }
                   6433:     chop($courses);
1.772     raeburn  6434:     my $ok_response = 0;
                   6435:     my $response;
                   6436:     while (@homeservers > 0 && $ok_response == 0) {
                   6437:         my $server = shift(@homeservers); 
                   6438:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6439:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6440:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6441: 		split(/:/,$response);
1.772     raeburn  6442:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6443:             push(@{$codetitles},&str2array($codetitles_str));
                   6444:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6445:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6446:             $ok_response = 1;
                   6447:         }
                   6448:     }
                   6449:     if ($ok_response) {
1.521     raeburn  6450:         return 'ok';
1.772     raeburn  6451:     } else {
                   6452:         return $response;
1.521     raeburn  6453:     }
                   6454: }
                   6455: 
1.792     raeburn  6456: sub auto_instcode_defaults {
                   6457:     my ($domain,$returnhash,$code_order) = @_;
                   6458:     my @homeservers;
1.841     albertel 6459: 
                   6460:     my %servers = &get_servers($domain,'library');
                   6461:     foreach my $tryserver (keys(%servers)) {
                   6462: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6463: 	    push(@homeservers,$tryserver);
                   6464: 	}
1.792     raeburn  6465:     }
1.841     albertel 6466: 
1.792     raeburn  6467:     my $response;
1.841     albertel 6468:     foreach my $server (@homeservers) {
1.792     raeburn  6469:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6470:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6471: 	
                   6472: 	foreach my $pair (split(/\&/,$response)) {
                   6473: 	    my ($name,$value)=split(/\=/,$pair);
                   6474: 	    if ($name eq 'code_order') {
                   6475: 		@{$code_order} = split(/\&/,&unescape($value));
                   6476: 	    } else {
                   6477: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6478: 	    }
                   6479: 	}
                   6480: 	return 'ok';
1.792     raeburn  6481:     }
1.841     albertel 6482: 
                   6483:     return $response;
1.1003    raeburn  6484: }
                   6485: 
                   6486: sub auto_possible_instcodes {
1.1007    raeburn  6487:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6488:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6489:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6490:         return;
                   6491:     }
1.1003    raeburn  6492:     my (@homeservers,$uhome);
                   6493:     if (defined(&domain($domain,'primary'))) {
                   6494:         $uhome=&domain($domain,'primary');
                   6495:         push(@homeservers,&domain($domain,'primary'));
                   6496:     } else {
                   6497:         my %servers = &get_servers($domain,'library');
                   6498:         foreach my $tryserver (keys(%servers)) {
                   6499:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6500:                 push(@homeservers,$tryserver);
                   6501:             }
                   6502:         }
                   6503:     }
                   6504:     my $response;
                   6505:     foreach my $server (@homeservers) {
                   6506:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6507:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6508:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6509:             split(':',$response);
                   6510:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6511:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6512:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6513:             my ($name,$value)=split('=',$item);
                   6514:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6515:         }
                   6516:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6517:             my ($name,$value)=split('=',$item);
                   6518:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6519:         }
                   6520:         return 'ok';
                   6521:     }
                   6522:     return $response;
                   6523: }
1.792     raeburn  6524: 
1.1010    raeburn  6525: sub auto_courserequest_checks {
                   6526:     my ($dom) = @_;
1.1020    raeburn  6527:     my ($homeserver,%validations);
                   6528:     if ($dom =~ /^$match_domain$/) {
                   6529:         $homeserver = &domain($dom,'primary');
                   6530:     }
                   6531:     unless ($homeserver eq 'no_host') {
                   6532:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6533:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6534:             my @items = split(/&/,$response);
                   6535:             foreach my $item (@items) {
                   6536:                 my ($key,$value) = split('=',$item);
                   6537:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6538:             }
                   6539:         }
                   6540:     }
1.1010    raeburn  6541:     return %validations; 
                   6542: }
                   6543: 
1.1020    raeburn  6544: sub auto_courserequest_validation {
                   6545:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6546:     my ($homeserver,$response);
                   6547:     if ($dom =~ /^$match_domain$/) {
                   6548:         $homeserver = &domain($dom,'primary');
                   6549:     }
                   6550:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6551:           
1.1020    raeburn  6552:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6553:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6554:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6555:                                     $homeserver));
                   6556:     }
                   6557:     return $response;
                   6558: }
                   6559: 
1.777     albertel 6560: sub auto_validate_class_sec {
1.918     raeburn  6561:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6562:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6563:     my $ownerlist;
                   6564:     if (ref($owners) eq 'ARRAY') {
                   6565:         $ownerlist = join(',',@{$owners});
                   6566:     } else {
                   6567:         $ownerlist = $owners;
                   6568:     }
1.773     raeburn  6569:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6570:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6571:     return $response;
                   6572: }
                   6573: 
1.679     raeburn  6574: # ------------------------------------------------------- Course Group routines
                   6575: 
                   6576: sub get_coursegroups {
1.809     raeburn  6577:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6578:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6579: }
                   6580: 
1.679     raeburn  6581: sub modify_coursegroup {
                   6582:     my ($cdom,$cnum,$groupsettings) = @_;
                   6583:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6584: }
                   6585: 
1.809     raeburn  6586: sub toggle_coursegroup_status {
                   6587:     my ($cdom,$cnum,$group,$action) = @_;
                   6588:     my ($from_namespace,$to_namespace);
                   6589:     if ($action eq 'delete') {
                   6590:         $from_namespace = 'coursegroups';
                   6591:         $to_namespace = 'deleted_groups';
                   6592:     } else {
                   6593:         $from_namespace = 'deleted_groups';
                   6594:         $to_namespace = 'coursegroups';
                   6595:     }
                   6596:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6597:     if (my $tmp = &error(%curr_group)) {
                   6598:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6599:         return ('read error',$tmp);
                   6600:     } else {
                   6601:         my %savedsettings = %curr_group; 
1.809     raeburn  6602:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6603:         my $deloutcome;
                   6604:         if ($result eq 'ok') {
1.809     raeburn  6605:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6606:         } else {
                   6607:             return ('write error',$result);
                   6608:         }
                   6609:         if ($deloutcome eq 'ok') {
                   6610:             return 'ok';
                   6611:         } else {
                   6612:             return ('delete error',$deloutcome);
                   6613:         }
                   6614:     }
                   6615: }
                   6616: 
1.679     raeburn  6617: sub modify_group_roles {
1.957     raeburn  6618:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6619:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6620:     my $role = 'gr/'.&escape($userprivs);
                   6621:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6622:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6623:     if ($result eq 'ok') {
                   6624:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6625:     }
1.679     raeburn  6626:     return $result;
                   6627: }
                   6628: 
                   6629: sub modify_coursegroup_membership {
                   6630:     my ($cdom,$cnum,$membership) = @_;
                   6631:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6632:     return $result;
                   6633: }
                   6634: 
1.682     raeburn  6635: sub get_active_groups {
                   6636:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6637:     my $now = time;
                   6638:     my %groups = ();
                   6639:     foreach my $key (keys(%env)) {
1.811     albertel 6640:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6641:             my ($start,$end) = split(/\./,$env{$key});
                   6642:             if (($end!=0) && ($end<$now)) { next; }
                   6643:             if (($start!=0) && ($start>$now)) { next; }
                   6644:             if ($1 eq $cdom && $2 eq $cnum) {
                   6645:                 $groups{$3} = $env{$key} ;
                   6646:             }
                   6647:         }
                   6648:     }
                   6649:     return %groups;
                   6650: }
                   6651: 
1.683     raeburn  6652: sub get_group_membership {
                   6653:     my ($cdom,$cnum,$group) = @_;
                   6654:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6655: }
                   6656: 
                   6657: sub get_users_groups {
                   6658:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6659:     my @usersgroups;
1.683     raeburn  6660:     my $cachetime=1800;
                   6661: 
                   6662:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6663:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6664:     if (defined($cached)) {
1.734     albertel 6665:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6666:     } else {  
                   6667:         $grouplist = '';
1.816     raeburn  6668:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6669:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6670:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6671:         my $access_end = $env{'course.'.$courseid.
                   6672:                               '.default_enrollment_end_date'};
                   6673:         my $now = time;
                   6674:         foreach my $key (keys(%roleshash)) {
                   6675:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6676:                 my $group = $1;
                   6677:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6678:                     my $start = $2;
                   6679:                     my $end = $1;
                   6680:                     if ($start == -1) { next; } # deleted from group
                   6681:                     if (($start!=0) && ($start>$now)) { next; }
                   6682:                     if (($end!=0) && ($end<$now)) {
                   6683:                         if ($access_end && $access_end < $now) {
                   6684:                             if ($access_end - $end < 86400) {
                   6685:                                 push(@usersgroups,$group);
1.733     raeburn  6686:                             }
                   6687:                         }
1.817     raeburn  6688:                         next;
1.733     raeburn  6689:                     }
1.817     raeburn  6690:                     push(@usersgroups,$group);
1.683     raeburn  6691:                 }
                   6692:             }
                   6693:         }
1.817     raeburn  6694:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6695:         $grouplist = join(':',@usersgroups);
                   6696:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6697:     }
1.733     raeburn  6698:     return @usersgroups;
1.683     raeburn  6699: }
                   6700: 
                   6701: sub devalidate_getgroups_cache {
                   6702:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6703:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6704: 
1.683     raeburn  6705:     my $hashid="$udom:$uname:$courseid";
                   6706:     &devalidate_cache_new('getgroups',$hashid);
                   6707: }
                   6708: 
1.12      www      6709: # ------------------------------------------------------------------ Plain Text
                   6710: 
                   6711: sub plaintext {
1.988     raeburn  6712:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6713:     if ($short =~ m{^cr/}) {
1.758     albertel 6714: 	return (split('/',$short))[-1];
                   6715:     }
1.742     raeburn  6716:     if (!defined($cid)) {
                   6717:         $cid = $env{'request.course.id'};
                   6718:     }
                   6719:     my %rolenames = (
1.1008    raeburn  6720:                       Course    => 'std',
                   6721:                       Community => 'alt1',
1.742     raeburn  6722:                     );
1.1037    raeburn  6723:     if ($cid ne '') {
                   6724:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6725:             unless ($forcedefault) {
                   6726:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6727:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6728:                 return &Apache::lonlocal::mt($roletext);
                   6729:             }
                   6730:         }
                   6731:     }
                   6732:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6733:         (defined($rolenames{$type})) && 
                   6734:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6735:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6736:     } elsif ($cid ne '') {
                   6737:         my $crstype = $env{'course.'.$cid.'.type'};
                   6738:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6739:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6740:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6741:         }
1.742     raeburn  6742:     }
1.1037    raeburn  6743:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6744: }
                   6745: 
                   6746: # ----------------------------------------------------------------- Assign Role
                   6747: 
                   6748: sub assignrole {
1.957     raeburn  6749:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6750:         $context)=@_;
1.21      www      6751:     my $mrole;
                   6752:     if ($role =~ /^cr\//) {
1.393     www      6753:         my $cwosec=$url;
1.811     albertel 6754:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6755: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6756:            my $refused = 1;
                   6757:            if ($context eq 'requestcourses') {
                   6758:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6759:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6760:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6761:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6762:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6763:                            if ($crsenv{'internal.courseowner'} eq
                   6764:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6765:                                $refused = '';
                   6766:                            }
                   6767:                        }
                   6768:                    }
                   6769:                }
                   6770:            }
                   6771:            if ($refused) {
                   6772:                &logthis('Refused custom assignrole: '.
                   6773:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6774:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6775:                return 'refused';
                   6776:            }
1.104     www      6777:         }
1.21      www      6778:         $mrole='cr';
1.678     raeburn  6779:     } elsif ($role =~ /^gr\//) {
                   6780:         my $cwogrp=$url;
1.811     albertel 6781:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6782:         unless (&allowed('mdg',$cwogrp)) {
                   6783:             &logthis('Refused group assignrole: '.
                   6784:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6785:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6786:             return 'refused';
                   6787:         }
                   6788:         $mrole='gr';
1.21      www      6789:     } else {
1.82      www      6790:         my $cwosec=$url;
1.811     albertel 6791:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6792:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6793:             my $refused;
                   6794:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6795:                 if (!(&allowed('c'.$role,$url))) {
                   6796:                     $refused = 1;
                   6797:                 }
                   6798:             } else {
                   6799:                 $refused = 1;
                   6800:             }
1.947     raeburn  6801:             if ($refused) {
1.1045    raeburn  6802:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6803:                 if (!$selfenroll && $context eq 'course') {
                   6804:                     my %crsenv;
                   6805:                     if ($role eq 'cc' || $role eq 'co') {
                   6806:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6807:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6808:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6809:                                 if ($crsenv{'internal.courseowner'} eq 
                   6810:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6811:                                     $refused = '';
                   6812:                                 }
                   6813:                             }
                   6814:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6815:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6816:                                 if ($crsenv{'internal.courseowner'} eq 
                   6817:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6818:                                     $refused = '';
                   6819:                                 }
                   6820:                             }
                   6821:                         }
                   6822:                     }
                   6823:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6824:                     $refused = '';
1.1017    raeburn  6825:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6826:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6827:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6828:                         my $wrongcc;
                   6829:                         if ($cnum =~ /^$match_community$/) {
                   6830:                             $wrongcc = 1 if ($role eq 'cc');
                   6831:                         } else {
                   6832:                             $wrongcc = 1 if ($role eq 'co');
                   6833:                         }
                   6834:                         unless ($wrongcc) {
                   6835:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6836:                             if ($crsenv{'internal.courseowner'} eq 
                   6837:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6838:                                 $refused = '';
                   6839:                             }
1.1017    raeburn  6840:                         }
                   6841:                     }
                   6842:                 }
                   6843:                 if ($refused) {
1.947     raeburn  6844:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6845:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6846: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6847:                     return 'refused';
                   6848:                 }
1.932     raeburn  6849:             }
1.104     www      6850:         }
1.21      www      6851:         $mrole=$role;
                   6852:     }
1.620     albertel 6853:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6854:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6855:     if ($end) { $command.='_'.$end; }
1.21      www      6856:     if ($start) {
                   6857: 	if ($end) { 
1.81      www      6858:            $command.='_'.$start; 
1.21      www      6859:         } else {
1.81      www      6860:            $command.='_0_'.$start;
1.21      www      6861:         }
                   6862:     }
1.739     raeburn  6863:     my $origstart = $start;
                   6864:     my $origend = $end;
1.957     raeburn  6865:     my $delflag;
1.357     www      6866: # actually delete
                   6867:     if ($deleteflag) {
1.373     www      6868: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6869: # modify command to delete the role
1.620     albertel 6870:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6871:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6872: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6873: # set start and finish to negative values for userrolelog
                   6874:            $start=-1;
                   6875:            $end=-1;
1.957     raeburn  6876:            $delflag = 1;
1.357     www      6877:         }
                   6878:     }
                   6879: # send command
1.349     www      6880:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6881: # log new user role if status is ok
1.349     www      6882:     if ($answer eq 'ok') {
1.663     raeburn  6883: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6884: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6885:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6886:         unless ($role =~ /^gr/) {
                   6887:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6888:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6889:         }
1.1053    raeburn  6890:         if ($role eq 'cc') {
                   6891:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6892:         }
1.349     www      6893:     }
                   6894:     return $answer;
1.169     harris41 6895: }
                   6896: 
1.1053    raeburn  6897: sub autoupdate_coowners {
                   6898:     my ($url,$end,$start,$uname,$udom) = @_;
                   6899:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6900:     if (($cdom ne '') && ($cnum ne '')) {
                   6901:         my $now = time;
                   6902:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6903:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6904:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6905:             my $instcode = $coursehash{'internal.coursecode'};
                   6906:             if ($instcode ne '') {
1.1056    raeburn  6907:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6908:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6909:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6910:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6911:                         if ($result eq 'valid') {
                   6912:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6913:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6914:                                     push(@newcoowners,$coowner);
                   6915:                                 }
                   6916:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6917:                                     push(@newcoowners,$uname.':'.$udom);
                   6918:                                 }
                   6919:                                 @newcoowners = sort(@newcoowners);
                   6920:                             } else {
                   6921:                                 push(@newcoowners,$uname.':'.$udom);
                   6922:                             }
                   6923:                         } else {
                   6924:                             if ($coursehash{'internal.co-owners'}) {
                   6925:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6926:                                     unless ($coowner eq $uname.':'.$udom) {
                   6927:                                         push(@newcoowners,$coowner);
                   6928:                                     }
                   6929:                                 }
                   6930:                                 unless (@newcoowners > 0) {
                   6931:                                     $delcoowners = 1;
                   6932:                                     $coowners = '';
                   6933:                                 }
                   6934:                             }
                   6935:                         }
                   6936:                         if (@newcoowners || $delcoowners) {
                   6937:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6938:                                             $delcoowners,@newcoowners);
                   6939:                         }
                   6940:                     }
                   6941:                 }
                   6942:             }
                   6943:         }
                   6944:     }
                   6945: }
                   6946: 
                   6947: sub store_coowners {
                   6948:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6949:     my $cid = $cdom.'_'.$cnum;
                   6950:     my ($coowners,$delresult,$putresult);
                   6951:     if (@newcoowners) {
                   6952:         $coowners = join(',',@newcoowners);
                   6953:         my %coownershash = (
                   6954:                             'internal.co-owners' => $coowners,
                   6955:                            );
                   6956:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6957:         if ($putresult eq 'ok') {
                   6958:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6959:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6960:             }
                   6961:         }
                   6962:     }
                   6963:     if ($delcoowners) {
                   6964:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6965:         if ($delresult eq 'ok') {
                   6966:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6967:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6968:             }
                   6969:         }
                   6970:     }
                   6971:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6972:         my %crsinfo =
                   6973:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6974:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6975:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6976:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6977:         }
                   6978:     }
                   6979: }
                   6980: 
1.169     harris41 6981: # -------------------------------------------------- Modify user authentication
1.197     www      6982: # Overrides without validation
                   6983: 
1.169     harris41 6984: sub modifyuserauth {
                   6985:     my ($udom,$uname,$umode,$upass)=@_;
                   6986:     my $uhome=&homeserver($uname,$udom);
1.197     www      6987:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6988:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6989:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6990:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6991:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6992: 		     &escape($upass),$uhome);
1.620     albertel 6993:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6994:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6995:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6996:     &log($udom,,$uname,$uhome,
1.620     albertel 6997:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6998:                                      $env{'user.name'}.', '.$umode.
1.197     www      6999:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7000:     unless ($reply eq 'ok') {
1.197     www      7001:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7002: 	return 'error: '.$reply;
                   7003:     }   
1.170     harris41 7004:     return 'ok';
1.80      www      7005: }
                   7006: 
1.81      www      7007: # --------------------------------------------------------------- Modify a user
1.80      www      7008: 
1.81      www      7009: sub modifyuser {
1.206     matthew  7010:     my ($udom,    $uname, $uid,
                   7011:         $umode,   $upass, $first,
                   7012:         $middle,  $last,  $gene,
1.1058    raeburn  7013:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7014:     $udom= &LONCAPA::clean_domain($udom);
                   7015:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7016:     my $showcandelete = 'none';
                   7017:     if (ref($candelete) eq 'ARRAY') {
                   7018:         if (@{$candelete} > 0) {
                   7019:             $showcandelete = join(', ',@{$candelete});
                   7020:         }
                   7021:     }
1.81      www      7022:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7023:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7024: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7025:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7026:                                      ' desiredhome not specified'). 
1.620     albertel 7027:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7028:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7029:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7030:     my $newuser;
                   7031:     if ($uhome eq 'no_host') {
                   7032:         $newuser = 1;
                   7033:     }
1.80      www      7034: # ----------------------------------------------------------------- Create User
1.406     albertel 7035:     if (($uhome eq 'no_host') && 
                   7036: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7037:         my $unhome='';
1.844     albertel 7038:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7039:             $unhome = $desiredhome;
1.620     albertel 7040: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7041: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7042:         } else { # load balancing routine for determining $unhome
1.81      www      7043:             my $loadm=10000000;
1.841     albertel 7044: 	    my %servers = &get_servers($udom,'library');
                   7045: 	    foreach my $tryserver (keys(%servers)) {
                   7046: 		my $answer=reply('load',$tryserver);
                   7047: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7048: 		    $loadm=$answer;
                   7049: 		    $unhome=$tryserver;
                   7050: 		}
1.80      www      7051: 	    }
                   7052:         }
                   7053:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7054: 	    return 'error: unable to find a home server for '.$uname.
                   7055:                    ' in domain '.$udom;
1.80      www      7056:         }
                   7057:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7058:                          &escape($upass),$unhome);
                   7059: 	unless ($reply eq 'ok') {
                   7060:             return 'error: '.$reply;
                   7061:         }   
1.230     stredwic 7062:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7063:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7064: 	    return 'error: unable verify users home machine.';
1.80      www      7065:         }
1.209     matthew  7066:     }   # End of creation of new user
1.80      www      7067: # ---------------------------------------------------------------------- Add ID
                   7068:     if ($uid) {
                   7069:        $uid=~tr/A-Z/a-z/;
                   7070:        my %uidhash=&idrget($udom,$uname);
1.196     www      7071:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7072:          && (!$forceid)) {
1.80      www      7073: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7074: 	      return 'error: user id "'.$uid.'" does not match '.
                   7075:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7076:           }
                   7077:        } else {
                   7078: 	  &idput($udom,($uname => $uid));
                   7079:        }
                   7080:     }
                   7081: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7082:     my @tmp=&get('environment',
1.899     raeburn  7083: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7084:                     'permanentemail','inststatus'],
1.134     albertel 7085: 		   $udom,$uname);
1.1075    raeburn  7086:     my (%names,%oldnames);
1.313     matthew  7087:     if ($tmp[0] =~ m/^error:.*/) { 
                   7088:         %names=(); 
                   7089:     } else {
                   7090:         %names = @tmp;
1.1075    raeburn  7091:         %oldnames = %names;
1.313     matthew  7092:     }
1.388     www      7093: #
1.1058    raeburn  7094: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7095: # of users did not contain them), do not overwrite existing values
                   7096: # unless field is in $candelete array ref.  
                   7097: #
                   7098: 
                   7099:     my @fields = ('firstname','middlename','lastname','generation',
                   7100:                   'permanentemail','id');
                   7101:     my %newvalues;
                   7102:     if (ref($candelete) eq 'ARRAY') {
                   7103:         foreach my $field (@fields) {
                   7104:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7105:                 if ($field eq 'firstname') {
                   7106:                     $names{$field} = $first;
                   7107:                 } elsif ($field eq 'middlename') {
                   7108:                     $names{$field} = $middle;
                   7109:                 } elsif ($field eq 'lastname') {
                   7110:                     $names{$field} = $last;
                   7111:                 } elsif ($field eq 'generation') { 
                   7112:                     $names{$field} = $gene;
                   7113:                 } elsif ($field eq 'permanentemail') {
                   7114:                     $names{$field} = $email;
                   7115:                 } elsif ($field eq 'id') {
                   7116:                     $names{$field}  = $uid;
                   7117:                 }
                   7118:             }
                   7119:         }
                   7120:     }
1.388     www      7121:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7122:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7123:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7124:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7125:     if ($email) {
                   7126:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7127:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7128:     }
1.899     raeburn  7129:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7130:     if (defined($inststatus)) {
                   7131:         $names{'inststatus'} = '';
                   7132:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7133:         if (ref($usertypes) eq 'HASH') {
                   7134:             my @okstatuses; 
                   7135:             foreach my $item (split(/:/,$inststatus)) {
                   7136:                 if (defined($usertypes->{$item})) {
                   7137:                     push(@okstatuses,$item);  
                   7138:                 }
                   7139:             }
                   7140:             if (@okstatuses) {
                   7141:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7142:             }
                   7143:         }
                   7144:     }
1.1075    raeburn  7145:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7146:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7147:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7148:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7149:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7150:     } else {
                   7151:         $logmsg .= ' during self creation';
                   7152:     }
1.1075    raeburn  7153:     my $changed;
                   7154:     if ($newuser) {
                   7155:         $changed = 1;
                   7156:     } else {
                   7157:         foreach my $field (@fields) {
                   7158:             if ($names{$field} ne $oldnames{$field}) {
                   7159:                 $changed = 1;
                   7160:                 last;
                   7161:             }
                   7162:         }
                   7163:     }
                   7164:     unless ($changed) {
                   7165:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7166:         &logthis($logmsg);
                   7167:         return 'ok';
                   7168:     }
                   7169:     my $reply = &put('environment', \%names, $udom,$uname);
                   7170:     if ($reply ne 'ok') { 
                   7171:         return 'error: '.$reply;
                   7172:     }
1.1087    raeburn  7173:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7174:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7175:     }
1.1075    raeburn  7176:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7177:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7178:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7179:     &logthis($logmsg);
1.134     albertel 7180:     return 'ok';
1.80      www      7181: }
                   7182: 
1.81      www      7183: # -------------------------------------------------------------- Modify student
1.80      www      7184: 
1.81      www      7185: sub modifystudent {
                   7186:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7187:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7188:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7189:     if (!$cid) {
1.620     albertel 7190: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7191: 	    return 'not_in_class';
                   7192: 	}
1.80      www      7193:     }
                   7194: # --------------------------------------------------------------- Make the user
1.81      www      7195:     my $reply=&modifyuser
1.209     matthew  7196: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7197:          $desiredhome,$email,$inststatus);
1.80      www      7198:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7199:     # This will cause &modify_student_enrollment to get the uid from the
                   7200:     # students environment
                   7201:     $uid = undef if (!$forceid);
1.455     albertel 7202:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7203: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7204:     return $reply;
                   7205: }
                   7206: 
                   7207: sub modify_student_enrollment {
1.957     raeburn  7208:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7209:     my ($cdom,$cnum,$chome);
                   7210:     if (!$cid) {
1.620     albertel 7211: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7212: 	    return 'not_in_class';
                   7213: 	}
1.620     albertel 7214: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7215: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7216:     } else {
                   7217: 	($cdom,$cnum)=split(/_/,$cid);
                   7218:     }
1.620     albertel 7219:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7220:     if (!$chome) {
1.457     raeburn  7221: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7222:     }
1.455     albertel 7223:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7224:     # Make sure the user exists
1.81      www      7225:     my $uhome=&homeserver($uname,$udom);
                   7226:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7227: 	return 'error: no such user';
                   7228:     }
1.297     matthew  7229:     # Get student data if we were not given enough information
                   7230:     if (!defined($first)  || $first  eq '' || 
                   7231:         !defined($last)   || $last   eq '' || 
                   7232:         !defined($uid)    || $uid    eq '' || 
                   7233:         !defined($middle) || $middle eq '' || 
                   7234:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7235:         # They did not supply us with enough data to enroll the student, so
                   7236:         # we need to pick up more information.
1.297     matthew  7237:         my %tmp = &get('environment',
1.294     matthew  7238:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7239:                        ,$udom,$uname);
                   7240: 
1.800     albertel 7241:         #foreach my $key (keys(%tmp)) {
                   7242:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7243:         #}
1.294     matthew  7244:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7245:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7246:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7247:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7248:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7249:     }
1.556     albertel 7250:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7251:     my $reply=cput('classlist',
                   7252: 		   {"$uname:$udom" => 
1.515     raeburn  7253: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7254: 		   $cdom,$cnum);
1.81      www      7255:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7256: 	return 'error: '.$reply;
1.652     albertel 7257:     } else {
                   7258: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7259:     }
1.297     matthew  7260:     # Add student role to user
1.83      www      7261:     my $uurl='/'.$cid;
1.81      www      7262:     $uurl=~s/\_/\//g;
                   7263:     if ($usec) {
                   7264: 	$uurl.='/'.$usec;
                   7265:     }
1.957     raeburn  7266:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7267: }
                   7268: 
1.556     albertel 7269: sub format_name {
                   7270:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7271:     my $name;
                   7272:     if ($first ne 'lastname') {
                   7273: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7274:     } else {
                   7275: 	if ($lastname=~/\S/) {
                   7276: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7277: 	    $name=~s/\s+,/,/;
                   7278: 	} else {
                   7279: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7280: 	}
                   7281:     }
                   7282:     $name=~s/^\s+//;
                   7283:     $name=~s/\s+$//;
                   7284:     $name=~s/\s+/ /g;
                   7285:     return $name;
                   7286: }
                   7287: 
1.84      www      7288: # ------------------------------------------------- Write to course preferences
                   7289: 
                   7290: sub writecoursepref {
                   7291:     my ($courseid,%prefs)=@_;
                   7292:     $courseid=~s/^\///;
                   7293:     $courseid=~s/\_/\//g;
                   7294:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7295:     my $chome=homeserver($cnum,$cdomain);
                   7296:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7297: 	return 'error: no such course';
                   7298:     }
                   7299:     my $cstring='';
1.800     albertel 7300:     foreach my $pref (keys(%prefs)) {
                   7301: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7302:     }
1.84      www      7303:     $cstring=~s/\&$//;
                   7304:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7305: }
                   7306: 
                   7307: # ---------------------------------------------------------- Make/modify course
                   7308: 
                   7309: sub createcourse {
1.741     raeburn  7310:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7311:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7312:     $url=&declutter($url);
                   7313:     my $cid='';
1.1028    raeburn  7314:     if ($context eq 'requestcourses') {
                   7315:         my $can_create = 0;
                   7316:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7317:         if ($udom eq $ownerdom) {
                   7318:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7319:                                   $context)) {
                   7320:                 $can_create = 1;
                   7321:             }
                   7322:         } else {
                   7323:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7324:                                            $category);
                   7325:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7326:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7327:                 if (@curr > 0) {
                   7328:                     my @options = qw(approval validate autolimit);
                   7329:                     my $optregex = join('|',@options);
                   7330:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7331:                         $can_create = 1;
                   7332:                     }
                   7333:                 }
                   7334:             }
                   7335:         }
                   7336:         if ($can_create) {
                   7337:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7338:                 unless (&allowed('ccc',$udom)) {
                   7339:                     return 'refused'; 
                   7340:                 }
1.1017    raeburn  7341:             }
                   7342:         } else {
                   7343:             return 'refused';
                   7344:         }
1.1028    raeburn  7345:     } elsif (!&allowed('ccc',$udom)) {
                   7346:         return 'refused';
1.84      www      7347:     }
1.1011    raeburn  7348: # --------------------------------------------------------------- Get Unique ID
                   7349:     my $uname;
                   7350:     if ($cnum =~ /^$match_courseid$/) {
                   7351:         my $chome=&homeserver($cnum,$udom,'true');
                   7352:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7353:             $uname = $cnum;
                   7354:         } else {
1.1038    raeburn  7355:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7356:         }
                   7357:     } else {
1.1038    raeburn  7358:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7359:     }
                   7360:     return $uname if ($uname =~ /^error/);
                   7361: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7362:     if (!defined($course_server)) {
                   7363:         if (defined(&domain($udom,'primary'))) {
                   7364:             $course_server = &domain($udom,'primary');
                   7365:         } else {
                   7366:             $course_server = $env{'user.home'}; 
                   7367:         }
                   7368:     }
                   7369:     my %host_servers =
                   7370:         &Apache::lonnet::get_servers($udom,'library');
                   7371:     unless ($host_servers{$course_server}) {
                   7372:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7373:     }
1.84      www      7374: # ------------------------------------------------------------- Make the course
                   7375:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7376:                       $course_server);
1.84      www      7377:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7378:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7379:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7380: 	return 'error: no such course';
                   7381:     }
1.271     www      7382: # ----------------------------------------------------------------- Course made
1.516     raeburn  7383: # log existence
1.1029    raeburn  7384:     my $now = time;
1.918     raeburn  7385:     my $newcourse = {
                   7386:                     $udom.'_'.$uname => {
1.921     raeburn  7387:                                      description => $description,
                   7388:                                      inst_code   => $inst_code,
                   7389:                                      owner       => $course_owner,
                   7390:                                      type        => $crstype,
1.1029    raeburn  7391:                                      creator     => $env{'user.name'}.':'.
                   7392:                                                     $env{'user.domain'},
                   7393:                                      created     => $now,
                   7394:                                      context     => $context,
1.918     raeburn  7395:                                                 },
                   7396:                     };
1.921     raeburn  7397:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7398: # set toplevel url
1.271     www      7399:     my $topurl=$url;
                   7400:     unless ($nonstandard) {
                   7401: # ------------------------------------------ For standard courses, make top url
                   7402:         my $mapurl=&clutter($url);
1.278     www      7403:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7404:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7405: <map>
                   7406: <resource id="1" type="start"></resource>
                   7407: <resource id="2" src="$mapurl"></resource>
                   7408: <resource id="3" type="finish"></resource>
                   7409: <link index="1" from="1" to="2"></link>
                   7410: <link index="2" from="2" to="3"></link>
                   7411: </map>
                   7412: ENDINITMAP
                   7413:         $topurl=&declutter(
1.638     albertel 7414:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7415:                           );
                   7416:     }
                   7417: # ----------------------------------------------------------- Write preferences
1.84      www      7418:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7419:                      ('description'              => $description,
                   7420:                       'url'                      => $topurl,
                   7421:                       'internal.creator'         => $env{'user.name'}.':'.
                   7422:                                                     $env{'user.domain'},
                   7423:                       'internal.created'         => $now,
                   7424:                       'internal.creationcontext' => $context)
                   7425:                     );
1.84      www      7426:     return '/'.$udom.'/'.$uname;
                   7427: }
                   7428: 
1.1011    raeburn  7429: # ------------------------------------------------------------------- Create ID
                   7430: sub generate_coursenum {
1.1038    raeburn  7431:     my ($udom,$crstype) = @_;
1.1011    raeburn  7432:     my $domdesc = &domain($udom);
                   7433:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7434:     my $first;
                   7435:     if ($crstype eq 'Community') {
                   7436:         $first = '0';
                   7437:     } else {
                   7438:         $first = int(1+rand(9)); 
                   7439:     } 
                   7440:     my $uname=$first.
1.1011    raeburn  7441:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7442:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7443:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7444: # ----------------------------------------------- Make sure that does not exist
                   7445:     my $uhome=&homeserver($uname,$udom,'true');
                   7446:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7447:         if ($crstype eq 'Community') {
                   7448:             $first = '0';
                   7449:         } else {
                   7450:             $first = int(1+rand(9));
                   7451:         }
                   7452:         $uname=$first.
1.1011    raeburn  7453:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7454:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7455:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7456:         $uhome=&homeserver($uname,$udom,'true');
                   7457:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7458:             return 'error: unable to generate unique course-ID';
                   7459:         }
                   7460:     }
                   7461:     return $uname;
                   7462: }
                   7463: 
1.813     albertel 7464: sub is_course {
                   7465:     my ($cdom,$cnum) = @_;
                   7466:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7467: 				undef,'.');
1.813     albertel 7468:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7469:         return 1;
                   7470:     }
                   7471:     return 0;
                   7472: }
                   7473: 
1.1015    raeburn  7474: sub store_userdata {
                   7475:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7476:     my $result;
1.1016    raeburn  7477:     if ($datakey ne '') {
1.1013    raeburn  7478:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7479:             if ($udom eq '' || $uname eq '') {
                   7480:                 $udom = $env{'user.domain'};
                   7481:                 $uname = $env{'user.name'};
                   7482:             }
                   7483:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7484:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7485:                 $result = 'error: no_host';
                   7486:             } else {
                   7487:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7488:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7489: 
                   7490:                 my $namevalue='';
                   7491:                 foreach my $key (keys(%{$storehash})) {
                   7492:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7493:                 }
                   7494:                 $namevalue=~s/\&$//;
1.1105    raeburn  7495:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7496:                                   $namevalue,$uhome);
1.1013    raeburn  7497:             }
                   7498:         } else {
                   7499:             $result = 'error: data to store was not a hash reference'; 
                   7500:         }
                   7501:     } else {
                   7502:         $result= 'error: invalid requestkey'; 
                   7503:     }
                   7504:     return $result;
                   7505: }
                   7506: 
1.21      www      7507: # ---------------------------------------------------------- Assign Custom Role
                   7508: 
                   7509: sub assigncustomrole {
1.957     raeburn  7510:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7511:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7512:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7513: }
                   7514: 
                   7515: # ----------------------------------------------------------------- Revoke Role
                   7516: 
                   7517: sub revokerole {
1.957     raeburn  7518:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7519:     my $now=time;
1.965     raeburn  7520:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7521: }
                   7522: 
                   7523: # ---------------------------------------------------------- Revoke Custom Role
                   7524: 
                   7525: sub revokecustomrole {
1.957     raeburn  7526:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7527:     my $now=time;
1.357     www      7528:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7529:            $deleteflag,$selfenroll,$context);
1.17      www      7530: }
                   7531: 
1.533     banghart 7532: # ------------------------------------------------------------ Disk usage
1.535     albertel 7533: sub diskusage {
1.955     raeburn  7534:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7535:     $directorypath =~ s/\/$//;
                   7536:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7537:                        .&escape($getpropath).':'.&escape($uname).':'
                   7538:                        .&escape($udom),homeserver($uname,$udom));
                   7539:     if ($listing eq 'unknown_cmd') {
                   7540:         if ($getpropath) {
                   7541:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7542:         }
                   7543:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7544:     }
1.514     albertel 7545:     return $listing;
1.512     banghart 7546: }
                   7547: 
1.566     banghart 7548: sub is_locked {
1.1096    raeburn  7549:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7550:     my @check;
                   7551:     my $is_locked;
1.1093    raeburn  7552:     push (@check,$file_name);
1.613     albertel 7553:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7554: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7555:     my ($tmp)=keys(%locked);
                   7556:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7557:     
1.566     banghart 7558:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7559:         $is_locked = 'false';
                   7560:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7561:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7562:                $is_locked = 'true';
1.1096    raeburn  7563:                if (ref($which) eq 'ARRAY') {
                   7564:                    push(@{$which},$entry);
                   7565:                } else {
                   7566:                    last;
                   7567:                }
1.745     raeburn  7568:            }
                   7569:        }
1.566     banghart 7570:     } else {
                   7571:         $is_locked = 'false';
                   7572:     }
1.1093    raeburn  7573:     return $is_locked;
1.566     banghart 7574: }
                   7575: 
1.759     albertel 7576: sub declutter_portfile {
                   7577:     my ($file) = @_;
1.833     albertel 7578:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7579:     return $file;
                   7580: }
                   7581: 
1.559     banghart 7582: # ------------------------------------------------------------- Mark as Read Only
                   7583: 
                   7584: sub mark_as_readonly {
                   7585:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7586:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7587:     my ($tmp)=keys(%current_permissions);
                   7588:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7589:     foreach my $file (@{$files}) {
1.759     albertel 7590: 	$file = &declutter_portfile($file);
1.561     banghart 7591:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7592:     }
1.613     albertel 7593:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7594:     return;
                   7595: }
                   7596: 
1.572     banghart 7597: # ------------------------------------------------------------Save Selected Files
                   7598: 
                   7599: sub save_selected_files {
                   7600:     my ($user, $path, @files) = @_;
                   7601:     my $filename = $user."savedfiles";
1.573     banghart 7602:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7603:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7604:     foreach my $file (@files) {
1.620     albertel 7605:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7606:     }
                   7607:     foreach my $file (@other_files) {
1.574     banghart 7608:         print (OUT $file."\n");
1.572     banghart 7609:     }
1.574     banghart 7610:     close (OUT);
1.572     banghart 7611:     return 'ok';
                   7612: }
                   7613: 
1.574     banghart 7614: sub clear_selected_files {
                   7615:     my ($user) = @_;
                   7616:     my $filename = $user."savedfiles";
1.1117    foxr     7617:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7618:     print (OUT undef);
                   7619:     close (OUT);
                   7620:     return ("ok");    
                   7621: }
                   7622: 
1.572     banghart 7623: sub files_in_path {
                   7624:     my ($user, $path) = @_;
                   7625:     my $filename = $user."savedfiles";
                   7626:     my %return_files;
1.1117    foxr     7627:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7628:     while (my $line_in = <IN>) {
1.574     banghart 7629:         chomp ($line_in);
                   7630:         my @paths_and_file = split (m!/!, $line_in);
                   7631:         my $file_part = pop (@paths_and_file);
                   7632:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7633:         $path_part.='/';
                   7634:         my $path_and_file = $path_part.$file_part;
                   7635:         if ($path_part eq $path) {
                   7636:             $return_files{$file_part}= 'selected';
                   7637:         }
                   7638:     }
1.574     banghart 7639:     close (IN);
                   7640:     return (\%return_files);
1.572     banghart 7641: }
                   7642: 
                   7643: # called in portfolio select mode, to show files selected NOT in current directory
                   7644: sub files_not_in_path {
                   7645:     my ($user, $path) = @_;
                   7646:     my $filename = $user."savedfiles";
                   7647:     my @return_files;
                   7648:     my $path_part;
1.1117    foxr     7649:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7650:     while (my $line = <IN>) {
1.572     banghart 7651:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7652:         my @paths_and_file = split(m|/|, $line);
                   7653:         my $file_part = pop(@paths_and_file);
                   7654:         chomp($file_part);
                   7655:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7656:         $path_part .= '/';
                   7657:         my $path_and_file = $path_part.$file_part;
                   7658:         if ($path_part ne $path) {
1.800     albertel 7659:             push(@return_files, ($path_and_file));
1.572     banghart 7660:         }
                   7661:     }
1.800     albertel 7662:     close(OUT);
1.574     banghart 7663:     return (@return_files);
1.572     banghart 7664: }
                   7665: 
1.745     raeburn  7666: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7667: 
1.745     raeburn  7668: sub get_portfile_permissions {
                   7669:     my ($domain,$user) = @_;
1.613     albertel 7670:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7671:     my ($tmp)=keys(%current_permissions);
                   7672:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7673:     return \%current_permissions;
                   7674: }
                   7675: 
                   7676: #---------------------------------------------Get portfolio file access controls
                   7677: 
1.749     raeburn  7678: sub get_access_controls {
1.745     raeburn  7679:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7680:     my %access;
                   7681:     my $real_file = $file;
                   7682:     $file =~ s/\.meta$//;
1.745     raeburn  7683:     if (defined($file)) {
1.749     raeburn  7684:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7685:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7686:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7687:             }
                   7688:         }
1.745     raeburn  7689:     } else {
1.749     raeburn  7690:         foreach my $key (keys(%{$current_permissions})) {
                   7691:             if ($key =~ /\0accesscontrol$/) {
                   7692:                 if (defined($group)) {
                   7693:                     if ($key !~ m-^\Q$group\E/-) {
                   7694:                         next;
                   7695:                     }
                   7696:                 }
                   7697:                 my ($fullpath) = split(/\0/,$key);
                   7698:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7699:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7700:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7701:                     }
                   7702:                 }
                   7703:             }
                   7704:         }
                   7705:     }
                   7706:     return %access;
                   7707: }
                   7708: 
                   7709: sub modify_access_controls {
                   7710:     my ($file_name,$changes,$domain,$user)=@_;
                   7711:     my ($outcome,$deloutcome);
                   7712:     my %store_permissions;
                   7713:     my %new_values;
                   7714:     my %new_control;
                   7715:     my %translation;
                   7716:     my @deletions = ();
                   7717:     my $now = time;
                   7718:     if (exists($$changes{'activate'})) {
                   7719:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7720:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7721:             my $numnew = scalar(@newitems);
                   7722:             for (my $i=0; $i<$numnew; $i++) {
                   7723:                 my $newkey = $newitems[$i];
                   7724:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7725:                 if ($newkey =~ /^\d+:/) { 
                   7726:                     $newkey =~ s/^(\d+)/$newid/;
                   7727:                     $translation{$1} = $newid;
                   7728:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7729:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7730:                     $translation{$1} = $newid;
                   7731:                 }
1.749     raeburn  7732:                 $new_values{$file_name."\0".$newkey} = 
                   7733:                                           $$changes{'activate'}{$newitems[$i]};
                   7734:                 $new_control{$newkey} = $now;
                   7735:             }
                   7736:         }
                   7737:     }
                   7738:     my %todelete;
                   7739:     my %changed_items;
                   7740:     foreach my $action ('delete','update') {
                   7741:         if (exists($$changes{$action})) {
                   7742:             if (ref($$changes{$action}) eq 'HASH') {
                   7743:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7744:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7745:                     if ($action eq 'delete') { 
                   7746:                         $todelete{$itemnum} = 1;
                   7747:                     } else {
                   7748:                         $changed_items{$itemnum} = $key;
                   7749:                     }
                   7750:                 }
1.745     raeburn  7751:             }
                   7752:         }
1.749     raeburn  7753:     }
                   7754:     # get lock on access controls for file.
                   7755:     my $lockhash = {
                   7756:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7757:                                                        ':'.$env{'user.domain'},
                   7758:                    }; 
                   7759:     my $tries = 0;
                   7760:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7761:    
                   7762:     while (($gotlock ne 'ok') && $tries <3) {
                   7763:         $tries ++;
                   7764:         sleep 1;
                   7765:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7766:     }
                   7767:     if ($gotlock eq 'ok') {
                   7768:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7769:         my ($tmp)=keys(%curr_permissions);
                   7770:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7771:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7772:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7773:             if (ref($curr_controls) eq 'HASH') {
                   7774:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7775:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7776:                     if (defined($todelete{$itemnum})) {
                   7777:                         push(@deletions,$file_name."\0".$control_item);
                   7778:                     } else {
                   7779:                         if (defined($changed_items{$itemnum})) {
                   7780:                             $new_control{$changed_items{$itemnum}} = $now;
                   7781:                             push(@deletions,$file_name."\0".$control_item);
                   7782:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7783:                         } else {
                   7784:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7785:                         }
                   7786:                     }
1.745     raeburn  7787:                 }
                   7788:             }
                   7789:         }
1.970     raeburn  7790:         my ($group);
                   7791:         if (&is_course($domain,$user)) {
                   7792:             ($group,my $file) = split(/\//,$file_name,2);
                   7793:         }
1.749     raeburn  7794:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7795:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7796:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7797:         #  remove lock
                   7798:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7799:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7800:         my $sqlresult =
1.970     raeburn  7801:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7802:                                     $group);
1.749     raeburn  7803:     } else {
                   7804:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7805:     }
1.749     raeburn  7806:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7807: }
                   7808: 
1.827     raeburn  7809: sub make_public_indefinitely {
                   7810:     my ($requrl) = @_;
                   7811:     my $now = time;
                   7812:     my $action = 'activate';
                   7813:     my $aclnum = 0;
                   7814:     if (&is_portfolio_url($requrl)) {
                   7815:         my (undef,$udom,$unum,$file_name,$group) =
                   7816:             &parse_portfolio_url($requrl);
                   7817:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7818:         my %access_controls = &get_access_controls($current_perms,
                   7819:                                                    $group,$file_name);
                   7820:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7821:             my ($num,$scope,$end,$start) = 
                   7822:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7823:             if ($scope eq 'public') {
                   7824:                 if ($start <= $now && $end == 0) {
                   7825:                     $action = 'none';
                   7826:                 } else {
                   7827:                     $action = 'update';
                   7828:                     $aclnum = $num;
                   7829:                 }
                   7830:                 last;
                   7831:             }
                   7832:         }
                   7833:         if ($action eq 'none') {
                   7834:              return 'ok';
                   7835:         } else {
                   7836:             my %changes;
                   7837:             my $newend = 0;
                   7838:             my $newstart = $now;
                   7839:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7840:             $changes{$action}{$newkey} = {
                   7841:                 type => 'public',
                   7842:                 time => {
                   7843:                     start => $newstart,
                   7844:                     end   => $newend,
                   7845:                 },
                   7846:             };
                   7847:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7848:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7849:             return $outcome;
                   7850:         }
                   7851:     } else {
                   7852:         return 'invalid';
                   7853:     }
                   7854: }
                   7855: 
1.745     raeburn  7856: #------------------------------------------------------Get Marked as Read Only
                   7857: 
                   7858: sub get_marked_as_readonly {
                   7859:     my ($domain,$user,$what,$group) = @_;
                   7860:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7861:     my @readonly_files;
1.629     banghart 7862:     my $cmp1=$what;
                   7863:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7864:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7865:         if (defined($group)) {
                   7866:             if ($file_name !~ m-^\Q$group\E/-) {
                   7867:                 next;
                   7868:             }
                   7869:         }
1.561     banghart 7870:         if (ref($value) eq "ARRAY"){
                   7871:             foreach my $stored_what (@{$value}) {
1.629     banghart 7872:                 my $cmp2=$stored_what;
1.759     albertel 7873:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7874:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7875:                 }
1.629     banghart 7876:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7877:                     push(@readonly_files, $file_name);
1.745     raeburn  7878:                     last;
1.563     banghart 7879:                 } elsif (!defined($what)) {
                   7880:                     push(@readonly_files, $file_name);
1.745     raeburn  7881:                     last;
1.561     banghart 7882:                 }
                   7883:             }
1.745     raeburn  7884:         }
1.561     banghart 7885:     }
                   7886:     return @readonly_files;
                   7887: }
1.577     banghart 7888: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7889: 
1.577     banghart 7890: sub get_marked_as_readonly_hash {
1.745     raeburn  7891:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7892:     my %readonly_files;
1.745     raeburn  7893:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7894:         if (defined($group)) {
                   7895:             if ($file_name !~ m-^\Q$group\E/-) {
                   7896:                 next;
                   7897:             }
                   7898:         }
1.577     banghart 7899:         if (ref($value) eq "ARRAY"){
                   7900:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7901:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7902:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7903:                         if ($lock_descriptor eq 'graded') {
                   7904:                             $readonly_files{$file_name} = 'graded';
                   7905:                         } elsif ($lock_descriptor eq 'handback') {
                   7906:                             $readonly_files{$file_name} = 'handback';
                   7907:                         } else {
                   7908:                             if (!exists($readonly_files{$file_name})) {
                   7909:                                 $readonly_files{$file_name} = 'locked';
                   7910:                             }
                   7911:                         }
1.745     raeburn  7912:                     }
1.750     banghart 7913:                 } 
1.577     banghart 7914:             }
                   7915:         } 
                   7916:     }
                   7917:     return %readonly_files;
                   7918: }
1.559     banghart 7919: # ------------------------------------------------------------ Unmark as Read Only
                   7920: 
                   7921: sub unmark_as_readonly {
1.629     banghart 7922:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7923:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7924:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7925:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7926:     my $symb_crs = $what;
                   7927:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7928:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7929:     my ($tmp)=keys(%current_permissions);
                   7930:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7931:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7932:     foreach my $file (@readonly_files) {
1.759     albertel 7933: 	my $clean_file = &declutter_portfile($file);
                   7934: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7935: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7936:         my @new_locks;
                   7937:         my @del_keys;
                   7938:         if (ref($current_locks) eq "ARRAY"){
                   7939:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7940:                 my $compare=$locker;
1.749     raeburn  7941:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7942:                     $compare=join('',@{$locker});
1.746     raeburn  7943:                     if ($compare ne $symb_crs) {
                   7944:                         push(@new_locks, $locker);
                   7945:                     }
1.563     banghart 7946:                 }
                   7947:             }
1.650     albertel 7948:             if (scalar(@new_locks) > 0) {
1.563     banghart 7949:                 $current_permissions{$file} = \@new_locks;
                   7950:             } else {
                   7951:                 push(@del_keys, $file);
1.613     albertel 7952:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7953:                 delete($current_permissions{$file});
1.563     banghart 7954:             }
                   7955:         }
1.561     banghart 7956:     }
1.613     albertel 7957:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7958:     return;
                   7959: }
1.512     banghart 7960: 
1.17      www      7961: # ------------------------------------------------------------ Directory lister
                   7962: 
                   7963: sub dirlist {
1.955     raeburn  7964:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7965:     $uri=~s/^\///;
                   7966:     $uri=~s/\/$//;
1.253     stredwic 7967:     my ($udom, $uname);
1.955     raeburn  7968:     if ($getuserdir) {
1.253     stredwic 7969:         $udom = $userdomain;
                   7970:         $uname = $username;
1.955     raeburn  7971:     } else {
                   7972:         (undef,$udom,$uname)=split(/\//,$uri);
                   7973:         if(defined($userdomain)) {
                   7974:             $udom = $userdomain;
                   7975:         }
                   7976:         if(defined($username)) {
                   7977:             $uname = $username;
                   7978:         }
1.253     stredwic 7979:     }
1.955     raeburn  7980:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7981: 
1.955     raeburn  7982:     $dirRoot = $perlvar{'lonDocRoot'};
                   7983:     if (defined($getpropath)) {
                   7984:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7985:         $dirRoot =~ s/\/$//;
1.955     raeburn  7986:     } elsif (defined($getuserdir)) {
                   7987:         my $subdir=$uname.'__';
                   7988:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7989:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7990:                    ."/$udom/$subdir/$uname";
                   7991:     } elsif (defined($alternateRoot)) {
                   7992:         $dirRoot = $alternateRoot;
1.751     banghart 7993:     }
1.253     stredwic 7994: 
                   7995:     if($udom) {
                   7996:         if($uname) {
1.955     raeburn  7997:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7998:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7999:                               .':'.&escape($uname).':'.&escape($udom),
                   8000:                               &homeserver($uname,$udom));
                   8001:             if ($listing eq 'unknown_cmd') {
                   8002:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   8003:                                   &homeserver($uname,$udom));
                   8004:             } else {
                   8005:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8006:             }
1.605     matthew  8007:             if ($listing eq 'unknown_cmd') {
1.800     albertel 8008:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   8009: 				  &homeserver($uname,$udom));
1.605     matthew  8010:                 @listing_results = split(/:/,$listing);
                   8011:             } else {
                   8012:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8013:             }
                   8014:             return @listing_results;
1.955     raeburn  8015:         } elsif(!$alternateRoot) {
1.800     albertel 8016:             my %allusers;
1.841     albertel 8017: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8018:  	    foreach my $tryserver (keys(%servers)) {
                   8019:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8020:                                   &escape($udom),$tryserver);
                   8021:                 if ($listing eq 'unknown_cmd') {
                   8022: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8023: 				      $udom, $tryserver);
                   8024:                 } else {
                   8025:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8026:                 }
1.841     albertel 8027: 		if ($listing eq 'unknown_cmd') {
                   8028: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8029: 				      $udom, $tryserver);
                   8030: 		    @listing_results = split(/:/,$listing);
                   8031: 		} else {
                   8032: 		    @listing_results =
                   8033: 			map { &unescape($_); } split(/:/,$listing);
                   8034: 		}
                   8035: 		if ($listing_results[0] ne 'no_such_dir' && 
                   8036: 		    $listing_results[0] ne 'empty'       &&
                   8037: 		    $listing_results[0] ne 'con_lost') {
                   8038: 		    foreach my $line (@listing_results) {
                   8039: 			my ($entry) = split(/&/,$line,2);
                   8040: 			$allusers{$entry} = 1;
                   8041: 		    }
                   8042: 		}
1.253     stredwic 8043:             }
                   8044:             my $alluserstr='';
1.800     albertel 8045:             foreach my $user (sort(keys(%allusers))) {
                   8046:                 $alluserstr.=$user.'&user:';
1.253     stredwic 8047:             }
                   8048:             $alluserstr=~s/:$//;
                   8049:             return split(/:/,$alluserstr);
                   8050:         } else {
1.800     albertel 8051:             return ('missing user name');
1.253     stredwic 8052:         }
1.955     raeburn  8053:     } elsif(!defined($getpropath)) {
1.841     albertel 8054:         my @all_domains = sort(&all_domains());
1.955     raeburn  8055:         foreach my $domain (@all_domains) {
                   8056:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   8057:         }
                   8058:         return @all_domains;
                   8059:     } else {
1.800     albertel 8060:         return ('missing domain');
1.275     stredwic 8061:     }
                   8062: }
                   8063: 
                   8064: # --------------------------------------------- GetFileTimestamp
                   8065: # This function utilizes dirlist and returns the date stamp for
                   8066: # when it was last modified.  It will also return an error of -1
                   8067: # if an error occurs
                   8068: 
                   8069: sub GetFileTimestamp {
1.955     raeburn  8070:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8071:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8072:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  8073:     my ($fileStat) = 
                   8074:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   8075:                                  undef,$getuserdir);
1.275     stredwic 8076:     my @stats = split('&', $fileStat);
                   8077:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  8078:         # @stats contains first the filename, then the stat output
                   8079:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8080:     } else {
                   8081:         return -1;
1.253     stredwic 8082:     }
1.26      www      8083: }
                   8084: 
1.712     albertel 8085: sub stat_file {
                   8086:     my ($uri) = @_;
1.787     albertel 8087:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8088: 
1.955     raeburn  8089:     my ($udom,$uname,$file);
1.712     albertel 8090:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8091: 	($udom,$uname,$file) =
1.811     albertel 8092: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8093: 	$file = 'userfiles/'.$file;
                   8094:     }
                   8095:     if ($uri =~ m-^/res/-) {
                   8096: 	($udom,$uname) = 
1.807     albertel 8097: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8098: 	$file = $uri;
                   8099:     }
                   8100: 
                   8101:     if (!$udom || !$uname || !$file) {
                   8102: 	# unable to handle the uri
                   8103: 	return ();
                   8104:     }
1.956     raeburn  8105:     my $getpropath;
                   8106:     if ($file =~ /^userfiles\//) {
                   8107:         $getpropath = 1;
                   8108:     }
1.955     raeburn  8109:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8110:     my @stats = split('&', $result);
1.721     banghart 8111:     
1.712     albertel 8112:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8113: 	shift(@stats); #filename is first
                   8114: 	return @stats;
                   8115:     }
                   8116:     return ();
                   8117: }
                   8118: 
1.26      www      8119: # -------------------------------------------------------- Value of a Condition
                   8120: 
1.713     albertel 8121: # gets the value of a specific preevaluated condition
                   8122: #    stored in the string  $env{user.state.<cid>}
                   8123: # or looks up a condition reference in the bighash and if if hasn't
                   8124: # already been evaluated recurses into docondval to get the value of
                   8125: # the condition, then memoizing it to 
                   8126: #   $env{user.state.<cid>.<condition>}
1.40      www      8127: sub directcondval {
                   8128:     my $number=shift;
1.620     albertel 8129:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8130: 	&Apache::lonuserstate::evalstate();
                   8131:     }
1.713     albertel 8132:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8133: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8134:     } elsif ($number =~ /^_/) {
                   8135: 	my $sub_condition;
                   8136: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8137: 		&GDBM_READER(),0640)) {
                   8138: 	    $sub_condition=$bighash{'conditions'.$number};
                   8139: 	    untie(%bighash);
                   8140: 	}
                   8141: 	my $value = &docondval($sub_condition);
1.949     raeburn  8142: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8143: 	return $value;
                   8144:     }
1.620     albertel 8145:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8146:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8147:     } else {
                   8148:        return 2;
                   8149:     }
                   8150: }
                   8151: 
1.713     albertel 8152: # get the collection of conditions for this resource
1.26      www      8153: sub condval {
                   8154:     my $condidx=shift;
1.54      www      8155:     my $allpathcond='';
1.713     albertel 8156:     foreach my $cond (split(/\|/,$condidx)) {
                   8157: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8158: 	    $allpathcond.=
                   8159: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8160: 	}
1.191     harris41 8161:     }
1.54      www      8162:     $allpathcond=~s/\|$//;
1.713     albertel 8163:     return &docondval($allpathcond);
                   8164: }
                   8165: 
                   8166: #evaluates an expression of conditions
                   8167: sub docondval {
                   8168:     my ($allpathcond) = @_;
                   8169:     my $result=0;
                   8170:     if ($env{'request.course.id'}
                   8171: 	&& defined($allpathcond)) {
                   8172: 	my $operand='|';
                   8173: 	my @stack;
                   8174: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8175: 	    if ($chunk eq '(') {
                   8176: 		push @stack,($operand,$result);
                   8177: 	    } elsif ($chunk eq ')') {
                   8178: 		my $before=pop @stack;
                   8179: 		if (pop @stack eq '&') {
                   8180: 		    $result=$result>$before?$before:$result;
                   8181: 		} else {
                   8182: 		    $result=$result>$before?$result:$before;
                   8183: 		}
                   8184: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8185: 		$operand=$chunk;
                   8186: 	    } else {
                   8187: 		my $new=directcondval($chunk);
                   8188: 		if ($operand eq '&') {
                   8189: 		    $result=$result>$new?$new:$result;
                   8190: 		} else {
                   8191: 		    $result=$result>$new?$result:$new;
                   8192: 		}
                   8193: 	    }
                   8194: 	}
1.26      www      8195:     }
                   8196:     return $result;
1.421     albertel 8197: }
                   8198: 
                   8199: # ---------------------------------------------------- Devalidate courseresdata
                   8200: 
                   8201: sub devalidatecourseresdata {
                   8202:     my ($coursenum,$coursedomain)=@_;
                   8203:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8204:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8205: }
                   8206: 
1.763     www      8207: 
1.200     www      8208: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8209: #
                   8210: #  Parameters:
                   8211: #      $coursenum    - Number of the course.
                   8212: #      $coursedomain - Domain at which the course was created.
                   8213: #  Returns:
                   8214: #     A hash of the course parameters along (I think) with timestamps
                   8215: #     and version info.
1.877     foxr     8216: 
1.624     albertel 8217: sub get_courseresdata {
                   8218:     my ($coursenum,$coursedomain)=@_;
1.200     www      8219:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8220:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8221:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8222:     my %dumpreply;
1.417     albertel 8223:     unless (defined($cached)) {
1.624     albertel 8224: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8225: 	$result=\%dumpreply;
1.251     albertel 8226: 	my ($tmp) = keys(%dumpreply);
                   8227: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8228: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8229: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8230: 	    return $tmp;
1.416     albertel 8231: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8232: 	    $result=undef;
1.599     albertel 8233: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8234: 	}
                   8235:     }
1.624     albertel 8236:     return $result;
                   8237: }
                   8238: 
1.633     albertel 8239: sub devalidateuserresdata {
                   8240:     my ($uname,$udom)=@_;
                   8241:     my $hashid="$udom:$uname";
                   8242:     &devalidate_cache_new('userres',$hashid);
                   8243: }
                   8244: 
1.624     albertel 8245: sub get_userresdata {
                   8246:     my ($uname,$udom)=@_;
                   8247:     #most student don\'t have any data set, check if there is some data
                   8248:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8249: 
                   8250:     my $hashid="$udom:$uname";
                   8251:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8252:     if (!defined($cached)) {
                   8253: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8254: 	$result=\%resourcedata;
                   8255: 	&do_cache_new('userres',$hashid,$result,600);
                   8256:     }
                   8257:     my ($tmp)=keys(%$result);
                   8258:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8259: 	return $result;
                   8260:     }
                   8261:     #error 2 occurs when the .db doesn't exist
                   8262:     if ($tmp!~/error: 2 /) {
1.672     albertel 8263: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8264: 		 " Trying to get resource data for ".
                   8265: 		 $uname." at ".$udom.": ".
                   8266: 		 $tmp."</font>");
                   8267:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8268: 	#&EXT_cache_set($udom,$uname);
                   8269: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8270: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8271:     }
                   8272:     return $tmp;
                   8273: }
1.879     foxr     8274: #----------------------------------------------- resdata - return resource data
                   8275: #  Purpose:
                   8276: #    Return resource data for either users or for a course.
                   8277: #  Parameters:
                   8278: #     $name      - Course/user name.
                   8279: #     $domain    - Name of the domain the user/course is registered on.
                   8280: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8281: #     @which     - Array of names of resources desired.
                   8282: #  Returns:
                   8283: #     The value of the first reasource in @which that is found in the
                   8284: #     resource hash.
                   8285: #  Exceptional Conditions:
                   8286: #     If the $type passed in is not valid (not the string 'course' or 
                   8287: #     'user', an undefined  reference is returned.
                   8288: #     If none of the resources are found, an undef is returned
1.624     albertel 8289: sub resdata {
                   8290:     my ($name,$domain,$type,@which)=@_;
                   8291:     my $result;
                   8292:     if ($type eq 'course') {
                   8293: 	$result=&get_courseresdata($name,$domain);
                   8294:     } elsif ($type eq 'user') {
                   8295: 	$result=&get_userresdata($name,$domain);
                   8296:     }
                   8297:     if (!ref($result)) { return $result; }    
1.251     albertel 8298:     foreach my $item (@which) {
1.927     albertel 8299: 	if (defined($result->{$item->[0]})) {
                   8300: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8301: 	}
1.250     albertel 8302:     }
1.291     albertel 8303:     return undef;
1.200     www      8304: }
                   8305: 
1.379     matthew  8306: #
                   8307: # EXT resource caching routines
                   8308: #
                   8309: 
                   8310: sub clear_EXT_cache_status {
1.383     albertel 8311:     &delenv('cache.EXT.');
1.379     matthew  8312: }
                   8313: 
                   8314: sub EXT_cache_status {
                   8315:     my ($target_domain,$target_user) = @_;
1.383     albertel 8316:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8317:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8318:         # We know already the user has no data
                   8319:         return 1;
                   8320:     } else {
                   8321:         return 0;
                   8322:     }
                   8323: }
                   8324: 
                   8325: sub EXT_cache_set {
                   8326:     my ($target_domain,$target_user) = @_;
1.383     albertel 8327:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8328:     #&appenv({$cachename => time});
1.379     matthew  8329: }
                   8330: 
1.28      www      8331: # --------------------------------------------------------- Value of a Variable
1.58      www      8332: sub EXT {
1.715     albertel 8333: 
1.395     albertel 8334:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8335:     unless ($varname) { return ''; }
1.218     albertel 8336:     #get real user name/domain, courseid and symb
                   8337:     my $courseid;
1.359     albertel 8338:     my $publicuser;
1.427     www      8339:     if ($symbparm) {
                   8340: 	$symbparm=&get_symb_from_alias($symbparm);
                   8341:     }
1.218     albertel 8342:     if (!($uname && $udom)) {
1.790     albertel 8343:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8344:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8345:     } else {
1.620     albertel 8346: 	$courseid=$env{'request.course.id'};
1.218     albertel 8347:     }
1.48      www      8348:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8349:     my $rest;
1.320     albertel 8350:     if (defined($therest[0])) {
1.48      www      8351:        $rest=join('.',@therest);
                   8352:     } else {
                   8353:        $rest='';
                   8354:     }
1.320     albertel 8355: 
1.57      www      8356:     my $qualifierrest=$qualifier;
                   8357:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8358:     my $spacequalifierrest=$space;
                   8359:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8360:     if ($realm eq 'user') {
1.48      www      8361: # --------------------------------------------------------------- user.resource
                   8362: 	if ($space eq 'resource') {
1.651     albertel 8363: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8364: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8365: 		 &&
1.744     albertel 8366: 		 ($symbparm eq &symbread()) ) {	
                   8367: 		# if we are in the middle of processing the resource the
                   8368: 		# get the value we are planning on committing
                   8369:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8370:                     return $Apache::lonhomework::results{$qualifierrest};
                   8371:                 } else {
                   8372:                     return $Apache::lonhomework::history{$qualifierrest};
                   8373:                 }
1.335     albertel 8374: 	    } else {
1.359     albertel 8375: 		my %restored;
1.620     albertel 8376: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8377: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8378: 		} else {
                   8379: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8380: 		}
1.335     albertel 8381: 		return $restored{$qualifierrest};
                   8382: 	    }
1.48      www      8383: # ----------------------------------------------------------------- user.access
                   8384:         } elsif ($space eq 'access') {
1.218     albertel 8385: 	    # FIXME - not supporting calls for a specific user
1.48      www      8386:             return &allowed($qualifier,$rest);
                   8387: # ------------------------------------------ user.preferences, user.environment
                   8388:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8389: 	    if (($uname eq $env{'user.name'}) &&
                   8390: 		($udom eq $env{'user.domain'})) {
                   8391: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8392: 	    } else {
1.359     albertel 8393: 		my %returnhash;
                   8394: 		if (!$publicuser) {
                   8395: 		    %returnhash=&userenvironment($udom,$uname,
                   8396: 						 $qualifierrest);
                   8397: 		}
1.218     albertel 8398: 		return $returnhash{$qualifierrest};
                   8399: 	    }
1.48      www      8400: # ----------------------------------------------------------------- user.course
                   8401:         } elsif ($space eq 'course') {
1.218     albertel 8402: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8403:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8404: # ------------------------------------------------------------------- user.role
                   8405:         } elsif ($space eq 'role') {
1.218     albertel 8406: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8407:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8408:             if ($qualifier eq 'value') {
                   8409: 		return $role;
                   8410:             } elsif ($qualifier eq 'extent') {
                   8411:                 return $where;
                   8412:             }
                   8413: # ----------------------------------------------------------------- user.domain
                   8414:         } elsif ($space eq 'domain') {
1.218     albertel 8415:             return $udom;
1.48      www      8416: # ------------------------------------------------------------------- user.name
                   8417:         } elsif ($space eq 'name') {
1.218     albertel 8418:             return $uname;
1.48      www      8419: # ---------------------------------------------------- Any other user namespace
1.29      www      8420:         } else {
1.359     albertel 8421: 	    my %reply;
                   8422: 	    if (!$publicuser) {
                   8423: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8424: 	    }
                   8425: 	    return $reply{$qualifierrest};
1.48      www      8426:         }
1.236     www      8427:     } elsif ($realm eq 'query') {
                   8428: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8429:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8430: 						[$spacequalifierrest]);
1.620     albertel 8431: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8432:    } elsif ($realm eq 'request') {
1.48      www      8433: # ------------------------------------------------------------- request.browser
                   8434:         if ($space eq 'browser') {
1.430     www      8435: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8436: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8437: 		    return 1;
                   8438: 		} else {
                   8439: 		    return 0;
                   8440: 		}
                   8441: 	    } else {
1.620     albertel 8442: 		return $env{'browser.'.$qualifier};
1.430     www      8443: 	    }
1.57      www      8444: # ------------------------------------------------------------ request.filename
                   8445:         } else {
1.620     albertel 8446:             return $env{'request.'.$spacequalifierrest};
1.29      www      8447:         }
1.28      www      8448:     } elsif ($realm eq 'course') {
1.48      www      8449: # ---------------------------------------------------------- course.description
1.620     albertel 8450:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8451:     } elsif ($realm eq 'resource') {
1.165     www      8452: 
1.620     albertel 8453: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8454: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8455: 	}
1.693     albertel 8456: 
                   8457: 	if ($space eq 'title') {
                   8458: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8459: 	    return &gettitle($symbparm);
                   8460: 	}
                   8461: 	
                   8462: 	if ($space eq 'map') {
                   8463: 	    my ($map) = &decode_symb($symbparm);
                   8464: 	    return &symbread($map);
                   8465: 	}
1.905     albertel 8466: 	if ($space eq 'filename') {
                   8467: 	    if ($symbparm) {
                   8468: 		return &clutter((&decode_symb($symbparm))[2]);
                   8469: 	    }
                   8470: 	    return &hreflocation('',$env{'request.filename'});
                   8471: 	}
1.693     albertel 8472: 
                   8473: 	my ($section, $group, @groups);
1.593     albertel 8474: 	my ($courselevelm,$courselevel);
1.539     albertel 8475: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8476: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8477: 
1.218     albertel 8478: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8479: 
1.60      www      8480: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8481: 	    my $symbp=$symbparm;
1.735     albertel 8482: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8483: 
                   8484: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8485: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8486: 
1.620     albertel 8487: 	    if (($env{'user.name'} eq $uname) &&
                   8488: 		($env{'user.domain'} eq $udom)) {
                   8489: 		$section=$env{'request.course.sec'};
1.733     raeburn  8490:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8491:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8492: 	    } else {
1.539     albertel 8493: 		if (! defined($usection)) {
1.551     albertel 8494: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8495: 		} else {
                   8496: 		    $section = $usection;
                   8497: 		}
1.733     raeburn  8498:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8499: 	    }
                   8500: 
                   8501: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8502: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8503: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8504: 
1.593     albertel 8505: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8506: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8507: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8508: 
1.60      www      8509: # ----------------------------------------------------------- first, check user
1.624     albertel 8510: 
                   8511: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8512: 				       ([$courselevelr,'resource'],
                   8513: 					[$courselevelm,'map'     ],
                   8514: 					[$courselevel, 'course'  ]));
1.931     albertel 8515: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8516: 
1.594     albertel 8517: # ------------------------------------------------ second, check some of course
1.684     raeburn  8518:             my $coursereply;
1.691     raeburn  8519:             if (@groups > 0) {
                   8520:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8521:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8522:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8523:             }
1.96      www      8524: 
1.684     raeburn  8525: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8526: 				  $env{'course.'.$courseid.'.domain'},
                   8527: 				  'course',
                   8528: 				  ([$seclevelr,   'resource'],
                   8529: 				   [$seclevelm,   'map'     ],
                   8530: 				   [$seclevel,    'course'  ],
                   8531: 				   [$courselevelr,'resource']));
                   8532: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8533: 
1.60      www      8534: # ------------------------------------------------------ third, check map parms
1.218     albertel 8535: 	    my %parmhash=();
                   8536: 	    my $thisparm='';
                   8537: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8538: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8539: 		    &GDBM_READER(),0640)) {
1.218     albertel 8540: 		$thisparm=$parmhash{$symbparm};
                   8541: 		untie(%parmhash);
                   8542: 	    }
1.927     albertel 8543: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8544: 	}
1.594     albertel 8545: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8546: 
1.218     albertel 8547: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8548: 	my $filename;
                   8549: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8550: 	if ($symbparm) {
1.409     www      8551: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8552: 	} else {
1.620     albertel 8553: 	    $filename=$env{'request.filename'};
1.282     albertel 8554: 	}
                   8555: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8556: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8557: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8558: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8559: 
1.927     albertel 8560: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8561: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8562: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8563: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8564: 				     $env{'course.'.$courseid.'.domain'},
                   8565: 				     'course',
1.927     albertel 8566: 				     ([$courselevelm,'map'   ],
                   8567: 				      [$courselevel, 'course']));
                   8568: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8569: 	}
1.145     www      8570: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8571: 	unless ($space eq '0') {
1.336     albertel 8572: 	    my @parts=split(/_/,$space);
                   8573: 	    my $id=pop(@parts);
                   8574: 	    my $part=join('_',@parts);
                   8575: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8576: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8577: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8578: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8579: 	}
1.395     albertel 8580: 	if ($recurse) { return undef; }
                   8581: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8582: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8583: # ---------------------------------------------------- Any other user namespace
                   8584:     } elsif ($realm eq 'environment') {
                   8585: # ----------------------------------------------------------------- environment
1.620     albertel 8586: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8587: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8588: 	} else {
1.770     albertel 8589: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8590: 		return '';
                   8591: 	    }
1.219     albertel 8592: 	    my %returnhash=&userenvironment($udom,$uname,
                   8593: 					    $spacequalifierrest);
                   8594: 	    return $returnhash{$spacequalifierrest};
                   8595: 	}
1.28      www      8596:     } elsif ($realm eq 'system') {
1.48      www      8597: # ----------------------------------------------------------------- system.time
                   8598: 	if ($space eq 'time') {
                   8599: 	    return time;
                   8600:         }
1.696     albertel 8601:     } elsif ($realm eq 'server') {
                   8602: # ----------------------------------------------------------------- system.time
                   8603: 	if ($space eq 'name') {
                   8604: 	    return $ENV{'SERVER_NAME'};
                   8605:         }
1.28      www      8606:     }
1.48      www      8607:     return '';
1.61      www      8608: }
                   8609: 
1.927     albertel 8610: sub get_reply {
                   8611:     my ($reply_value) = @_;
1.940     raeburn  8612:     if (ref($reply_value) eq 'ARRAY') {
                   8613:         if (wantarray) {
                   8614: 	    return @$reply_value;
                   8615:         }
                   8616:         return $reply_value->[0];
                   8617:     } else {
                   8618:         return $reply_value;
1.927     albertel 8619:     }
                   8620: }
                   8621: 
1.691     raeburn  8622: sub check_group_parms {
                   8623:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8624:     my @groupitems = ();
                   8625:     my $resultitem;
1.927     albertel 8626:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8627:     foreach my $group (@{$groups}) {
                   8628:         foreach my $level (@levels) {
1.927     albertel 8629:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8630:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8631:         }
                   8632:     }
                   8633:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8634:                             $env{'course.'.$courseid.'.domain'},
                   8635:                                      'course',@groupitems);
                   8636:     return $coursereply;
                   8637: }
                   8638: 
                   8639: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8640:     my ($courseid,@groups) = @_;
                   8641:     @groups = sort(@groups);
1.691     raeburn  8642:     return @groups;
                   8643: }
                   8644: 
1.395     albertel 8645: sub packages_tab_default {
                   8646:     my ($uri,$varname)=@_;
                   8647:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8648: 
                   8649:     my (@extension,@specifics,$do_default);
                   8650:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8651: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8652: 	if ($pack_type eq 'default') {
                   8653: 	    $do_default=1;
                   8654: 	} elsif ($pack_type eq 'extension') {
                   8655: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8656: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8657: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8658: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8659: 	}
                   8660:     }
                   8661:     # first look for a package that matches the requested part id
                   8662:     foreach my $package (@specifics) {
                   8663: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8664: 	next if ($pack_part ne $part);
                   8665: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8666: 	    return $packagetab{"$pack_type&$name&default"};
                   8667: 	}
                   8668:     }
                   8669:     # look for any possible matching non extension_ package
                   8670:     foreach my $package (@specifics) {
                   8671: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8672: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8673: 	    return $packagetab{"$pack_type&$name&default"};
                   8674: 	}
1.585     albertel 8675: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8676: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8677: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8678: 	}
                   8679:     }
1.738     albertel 8680:     # look for any posible extension_ match
                   8681:     foreach my $package (@extension) {
                   8682: 	my ($package,$pack_type)=@{$package};
                   8683: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8684: 	    return $packagetab{"$pack_type&$name&default"};
                   8685: 	}
                   8686: 	if (defined($packagetab{$package."&$name&default"})) {
                   8687: 	    return $packagetab{$package."&$name&default"};
                   8688: 	}
                   8689:     }
                   8690:     # look for a global default setting
                   8691:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8692: 	return $packagetab{"default&$name&default"};
                   8693:     }
1.395     albertel 8694:     return undef;
                   8695: }
                   8696: 
1.334     albertel 8697: sub add_prefix_and_part {
                   8698:     my ($prefix,$part)=@_;
                   8699:     my $keyroot;
                   8700:     if (defined($prefix) && $prefix !~ /^__/) {
                   8701: 	# prefix that has a part already
                   8702: 	$keyroot=$prefix;
                   8703:     } elsif (defined($prefix)) {
                   8704: 	# prefix that is missing a part
                   8705: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8706:     } else {
                   8707: 	# no prefix at all
                   8708: 	if (defined($part)) { $keyroot='_'.$part; }
                   8709:     }
                   8710:     return $keyroot;
                   8711: }
                   8712: 
1.71      www      8713: # ---------------------------------------------------------------- Get metadata
                   8714: 
1.599     albertel 8715: my %metaentry;
1.1070    www      8716: my %importedpartids;
1.71      www      8717: sub metadata {
1.176     www      8718:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8719:     $uri=&declutter($uri);
1.288     albertel 8720:     # if it is a non metadata possible uri return quickly
1.529     albertel 8721:     if (($uri eq '') || 
                   8722: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8723: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8724:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8725: 	return undef;
                   8726:     }
                   8727:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8728: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8729: 	return undef;
1.288     albertel 8730:     }
1.73      www      8731:     my $filename=$uri;
                   8732:     $uri=~s/\.meta$//;
1.172     www      8733: #
                   8734: # Is the metadata already cached?
1.177     www      8735: # Look at timestamp of caching
1.172     www      8736: # Everything is cached by the main uri, libraries are never directly cached
                   8737: #
1.428     albertel 8738:     if (!defined($liburi)) {
1.599     albertel 8739: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8740: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8741:     }
                   8742:     {
1.1069    www      8743: # Imported parts would go here
1.1070    www      8744:         my %importedids=();
                   8745:         my @origfileimportpartids=();
1.1069    www      8746:         my $importedparts=0;
1.172     www      8747: #
                   8748: # Is this a recursive call for a library?
                   8749: #
1.599     albertel 8750: #	if (! exists($metacache{$uri})) {
                   8751: #	    $metacache{$uri}={};
                   8752: #	}
1.924     albertel 8753: 	my $cachetime = 60*60;
1.171     www      8754:         if ($liburi) {
                   8755: 	    $liburi=&declutter($liburi);
                   8756:             $filename=$liburi;
1.401     bowersj2 8757:         } else {
1.599     albertel 8758: 	    &devalidate_cache_new('meta',$uri);
                   8759: 	    undef(%metaentry);
1.401     bowersj2 8760: 	}
1.140     www      8761:         my %metathesekeys=();
1.73      www      8762:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8763: 	my $metastring;
1.924     albertel 8764: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8765: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8766: 	    $metastring = 
1.929     albertel 8767: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8768: 					  ('grade_target' => 'meta'));
                   8769: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8770: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8771:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8772: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8773: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8774: 	    $metastring=&getfile($file);
1.489     albertel 8775: 	}
1.208     albertel 8776:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8777:         my $token;
1.140     www      8778:         undef %metathesekeys;
1.71      www      8779:         while ($token=$parser->get_token) {
1.339     albertel 8780: 	    if ($token->[0] eq 'S') {
                   8781: 		if (defined($token->[2]->{'package'})) {
1.172     www      8782: #
                   8783: # This is a package - get package info
                   8784: #
1.339     albertel 8785: 		    my $package=$token->[2]->{'package'};
                   8786: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8787: 		    if (defined($token->[2]->{'id'})) { 
                   8788: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8789: 		    }
1.599     albertel 8790: 		    if ($metaentry{':packages'}) {
                   8791: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8792: 		    } else {
1.599     albertel 8793: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8794: 		    }
1.736     albertel 8795: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8796: 			my $part=$keyroot;
                   8797: 			$part=~s/^\_//;
1.736     albertel 8798: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8799: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8800: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8801: 			    # ignore package.tab specified default values
                   8802:                             # here &package_tab_default() will fetch those
                   8803: 			    if ($subp eq 'default') { next; }
1.736     albertel 8804: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8805: 			    my $unikey;
                   8806: 			    if ($pack =~ /_0$/) {
                   8807: 				$unikey='parameter_0_'.$name;
                   8808: 				$part=0;
                   8809: 			    } else {
                   8810: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8811: 			    }
1.339     albertel 8812: 			    if ($subp eq 'display') {
                   8813: 				$value.=' [Part: '.$part.']';
                   8814: 			    }
1.599     albertel 8815: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8816: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8817: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8818: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8819: 			    }
1.599     albertel 8820: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8821: 				$metaentry{':'.$unikey}=
                   8822: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8823: 			    }
1.339     albertel 8824: 			}
                   8825: 		    }
                   8826: 		} else {
1.172     www      8827: #
                   8828: # This is not a package - some other kind of start tag
1.339     albertel 8829: #
                   8830: 		    my $entry=$token->[1];
1.1068    www      8831: 		    my $unikey='';
1.175     www      8832: 
1.339     albertel 8833: 		    if ($entry eq 'import') {
1.175     www      8834: #
                   8835: # Importing a library here
1.339     albertel 8836: #
1.1067    www      8837:                         my $location=$parser->get_text('/import');
                   8838:                         my $dir=$filename;
                   8839:                         $dir=~s|[^/]*$||;
                   8840:                         $location=&filelocation($dir,$location);
1.1069    www      8841:                        
1.1068    www      8842:                         my $importmode=$token->[2]->{'importmode'};
                   8843:                         if ($importmode eq 'problem') {
1.1069    www      8844: # Import as problem/response
1.1068    www      8845:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8846:                         } elsif ($importmode eq 'part') {
                   8847: # Import as part(s)
1.1069    www      8848:                            $importedparts=1;
                   8849: # We need to get the original file and the imported file to get the part order correct
                   8850: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8851: # Load and inspect original file
1.1070    www      8852:                            if ($#origfileimportpartids<0) {
                   8853:                               undef(%importedpartids);
                   8854:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8855:                               my $origfile=&getfile($origfilelocation);
                   8856:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8857:                            }
                   8858: 
1.1069    www      8859: # Load and inspect imported file
                   8860:                            my $impfile=&getfile($location);
                   8861:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8862:                            if ($#impfilepartids>=0) {
                   8863: # This problem had parts
1.1070    www      8864:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8865:                            } else {
                   8866: # Importing by turning a single problem into a problem part
                   8867: # It gets the import-tags ID as part-ID
                   8868:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8869:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8870:                            }
1.1068    www      8871:                         } else {
                   8872: # Normal import
                   8873:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8874:                            if (defined($token->[2]->{'id'})) {
                   8875:                               $unikey.='_'.$token->[2]->{'id'};
                   8876:                            }
1.1067    www      8877:                         }
                   8878: 
1.339     albertel 8879: 			if ($depthcount<20) {
1.736     albertel 8880: 			    my $metadata = 
                   8881: 				&metadata($uri,'keys', $location,$unikey,
                   8882: 					  $depthcount+1);
                   8883: 			    foreach my $meta (split(',',$metadata)) {
                   8884: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8885: 				$metathesekeys{$meta}=1;
1.339     albertel 8886: 			    }
1.1068    www      8887: 			
                   8888:                         }
1.1067    www      8889: 		    } else {
                   8890: #
                   8891: # Not importing, some other kind of non-package, non-library start tag
                   8892: # 
                   8893:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8894:                         if (defined($token->[2]->{'id'})) {
                   8895:                             $unikey.='_'.$token->[2]->{'id'};
                   8896:                         }
1.339     albertel 8897: 			if (defined($token->[2]->{'name'})) { 
                   8898: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8899: 			}
                   8900: 			$metathesekeys{$unikey}=1;
1.736     albertel 8901: 			foreach my $param (@{$token->[3]}) {
                   8902: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8903: 				$token->[2]->{$param};
1.339     albertel 8904: 			}
                   8905: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8906: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8907: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8908: 		 # only ws inside the tag, and not in default, so use default
                   8909: 		 # as value
1.599     albertel 8910: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8911: 			} elsif ( $internaltext =~ /\S/ ) {
                   8912: 		  # something interesting inside the tag
                   8913: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8914: 			} else {
1.908     albertel 8915: 		  # no interesting values, don't set a default
1.339     albertel 8916: 			}
1.172     www      8917: # end of not-a-package not-a-library import
1.339     albertel 8918: 		    }
1.172     www      8919: # end of not-a-package start tag
1.339     albertel 8920: 		}
1.172     www      8921: # the next is the end of "start tag"
1.339     albertel 8922: 	    }
                   8923: 	}
1.483     albertel 8924: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8925: 	$extension = lc($extension);
                   8926: 	if ($extension eq 'htm') { $extension='html'; }
                   8927: 
1.737     albertel 8928: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8929: 	    #no specific packages #how's our extension
                   8930: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8931: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8932: 					 \%metathesekeys);
                   8933: 	}
1.883     albertel 8934: 
                   8935: 	if (!exists($metaentry{':packages'})
                   8936: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8937: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8938: 		#no specific packages well let's get default then
                   8939: 		if ($key!~/^default&/) { next; }
1.488     albertel 8940: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8941: 					     \%metathesekeys);
                   8942: 	    }
                   8943: 	}
1.338     www      8944: # are there custom rights to evaluate
1.599     albertel 8945: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8946: 
1.338     www      8947:     #
                   8948:     # Importing a rights file here
1.339     albertel 8949:     #
                   8950: 	    unless ($depthcount) {
1.599     albertel 8951: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8952: 		my $dir=$filename;
                   8953: 		$dir=~s|[^/]*$||;
                   8954: 		$location=&filelocation($dir,$location);
1.736     albertel 8955: 		my $rights_metadata =
                   8956: 		    &metadata($uri,'keys',$location,'_rights',
                   8957: 			      $depthcount+1);
                   8958: 		foreach my $rights (split(',',$rights_metadata)) {
                   8959: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8960: 		    $metathesekeys{$rights}=1;
1.339     albertel 8961: 		}
                   8962: 	    }
                   8963: 	}
1.737     albertel 8964: 	# uniqifiy package listing
                   8965: 	my %seen;
                   8966: 	my @uniq_packages =
                   8967: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8968: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8969: 
1.1070    www      8970:         if ($importedparts) {
                   8971: # We had imported parts and need to rebuild partorder
                   8972:            $metaentry{':partorder'}='';
                   8973:            $metathesekeys{'partorder'}=1;
                   8974:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8975:                if ($origfileimportpartids[$index] eq 'part') {
                   8976: # original part, part of the problem
                   8977:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8978:                } else {
                   8979: # we have imported parts at this position
                   8980:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8981:                }
                   8982:            }
                   8983:            $metaentry{':partorder'}=~s/^\,//;
                   8984:         }
                   8985: 
1.737     albertel 8986: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8987: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8988: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8989: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8990: # this is the end of "was not already recently cached
1.71      www      8991:     }
1.599     albertel 8992:     return $metaentry{':'.$what};
1.261     albertel 8993: }
                   8994: 
1.488     albertel 8995: sub metadata_create_package_def {
1.483     albertel 8996:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8997:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8998:     if ($subp eq 'default') { next; }
                   8999:     
1.599     albertel 9000:     if (defined($metaentry{':packages'})) {
                   9001: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9002:     } else {
1.599     albertel 9003: 	$metaentry{':packages'}=$package;
1.483     albertel 9004:     }
                   9005:     my $value=$packagetab{$key};
                   9006:     my $unikey;
                   9007:     $unikey='parameter_0_'.$name;
1.599     albertel 9008:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9009:     $$metathesekeys{$unikey}=1;
1.599     albertel 9010:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9011: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9012:     }
1.599     albertel 9013:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9014: 	$metaentry{':'.$unikey}=
                   9015: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9016:     }
                   9017: }
                   9018: 
1.261     albertel 9019: sub metadata_generate_part0 {
                   9020:     my ($metadata,$metacache,$uri) = @_;
                   9021:     my %allnames;
1.737     albertel 9022:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9023: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9024: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9025: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9026: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9027: 	    $allnames{$name}=$part;
                   9028: 	  }
                   9029: 	}
                   9030:     }
                   9031:     foreach my $name (keys(%allnames)) {
                   9032:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9033:       my $key=":parameter_0_$name";
1.261     albertel 9034:       $$metacache{"$key.part"}='0';
                   9035:       $$metacache{"$key.name"}=$name;
1.428     albertel 9036:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9037: 					   $allnames{$name}.'_'.$name.
                   9038: 					   '.type'};
1.428     albertel 9039:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9040: 			     '.display'};
1.644     www      9041:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9042:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9043:       $$metacache{"$key.display"}=$olddis;
                   9044:     }
1.71      www      9045: }
                   9046: 
1.764     albertel 9047: # ------------------------------------------------------ Devalidate title cache
                   9048: 
                   9049: sub devalidate_title_cache {
                   9050:     my ($url)=@_;
                   9051:     if (!$env{'request.course.id'}) { return; }
                   9052:     my $symb=&symbread($url);
                   9053:     if (!$symb) { return; }
                   9054:     my $key=$env{'request.course.id'}."\0".$symb;
                   9055:     &devalidate_cache_new('title',$key);
                   9056: }
                   9057: 
1.1014    droeschl 9058: # ------------------------------------------------- Get the title of a course
                   9059: 
                   9060: sub current_course_title {
                   9061:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9062: }
1.301     www      9063: # ------------------------------------------------- Get the title of a resource
                   9064: 
                   9065: sub gettitle {
                   9066:     my $urlsymb=shift;
                   9067:     my $symb=&symbread($urlsymb);
1.534     albertel 9068:     if ($symb) {
1.620     albertel 9069: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9070: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9071: 	if (defined($cached)) { 
                   9072: 	    return $result;
                   9073: 	}
1.534     albertel 9074: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9075: 	my $title='';
1.907     albertel 9076: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9077: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9078: 	} else {
                   9079: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9080: 		    &GDBM_READER(),0640)) {
                   9081: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9082: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9083: 		untie(%bighash);
                   9084: 	    }
1.534     albertel 9085: 	}
                   9086: 	$title=~s/\&colon\;/\:/gs;
                   9087: 	if ($title) {
1.599     albertel 9088: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9089: 	}
                   9090: 	$urlsymb=$url;
                   9091:     }
                   9092:     my $title=&metadata($urlsymb,'title');
                   9093:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9094:     return $title;
1.301     www      9095: }
1.613     albertel 9096: 
1.614     albertel 9097: sub get_slot {
                   9098:     my ($which,$cnum,$cdom)=@_;
                   9099:     if (!$cnum || !$cdom) {
1.790     albertel 9100: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9101: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9102: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9103:     }
1.703     albertel 9104:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9105:     my %slotinfo;
                   9106:     if (exists($remembered{$key})) {
                   9107: 	$slotinfo{$which} = $remembered{$key};
                   9108:     } else {
                   9109: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9110: 	&Apache::lonhomework::showhash(%slotinfo);
                   9111: 	my ($tmp)=keys(%slotinfo);
                   9112: 	if ($tmp=~/^error:/) { return (); }
                   9113: 	$remembered{$key} = $slotinfo{$which};
                   9114:     }
1.616     albertel 9115:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9116: 	return %{$slotinfo{$which}};
                   9117:     }
                   9118:     return $slotinfo{$which};
1.614     albertel 9119: }
1.31      www      9120: # ------------------------------------------------- Update symbolic store links
                   9121: 
                   9122: sub symblist {
                   9123:     my ($mapname,%newhash)=@_;
1.438     www      9124:     $mapname=&deversion(&declutter($mapname));
1.31      www      9125:     my %hash;
1.620     albertel 9126:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9127:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9128:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9129: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9130: 		next if ($url eq 'last_known'
                   9131: 			 && $env{'form.no_update_last_known'});
                   9132: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9133: 						    $newhash{$url}->[1],
                   9134: 						    $newhash{$url}->[0]);
1.191     harris41 9135:             }
1.31      www      9136:             if (untie(%hash)) {
                   9137: 		return 'ok';
                   9138:             }
                   9139:         }
                   9140:     }
                   9141:     return 'error';
1.212     www      9142: }
                   9143: 
                   9144: # --------------------------------------------------------------- Verify a symb
                   9145: 
                   9146: sub symbverify {
1.510     www      9147:     my ($symb,$thisurl)=@_;
                   9148:     my $thisfn=$thisurl;
1.439     www      9149:     $thisfn=&declutter($thisfn);
1.215     www      9150: # direct jump to resource in page or to a sequence - will construct own symbs
                   9151:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9152: # check URL part
1.409     www      9153:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9154: 
1.431     www      9155:     unless ($url eq $thisfn) { return 0; }
1.213     www      9156: 
1.216     www      9157:     $symb=&symbclean($symb);
1.510     www      9158:     $thisurl=&deversion($thisurl);
1.439     www      9159:     $thisfn=&deversion($thisfn);
1.213     www      9160: 
                   9161:     my %bighash;
                   9162:     my $okay=0;
1.431     www      9163: 
1.620     albertel 9164:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9165:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9166:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9167:             $thisurl =~ s/\?.+$//;
                   9168:         }
1.510     www      9169:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9170:         unless ($ids) {
                   9171:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9172:             $ids=$bighash{$idkey};
1.216     www      9173:         }
                   9174:         if ($ids) {
                   9175: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9176: 	    foreach my $id (split(/\,/,$ids)) {
                   9177: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9178:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9179:                    $symb =~ s/\?.+$//;
                   9180:                }
1.216     www      9181:                if (
                   9182:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9183:    eq $symb) { 
1.620     albertel 9184: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9185: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9186:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9187: 		       $okay=1; 
                   9188: 		   }
                   9189: 	       }
1.216     www      9190: 	   }
                   9191:         }
1.213     www      9192: 	untie(%bighash);
                   9193:     }
                   9194:     return $okay;
1.31      www      9195: }
                   9196: 
1.210     www      9197: # --------------------------------------------------------------- Clean-up symb
                   9198: 
                   9199: sub symbclean {
                   9200:     my $symb=shift;
1.568     albertel 9201:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9202: # remove version from map
                   9203:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9204: 
1.210     www      9205: # remove version from URL
                   9206:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9207: 
1.507     www      9208: # remove wrapper
                   9209: 
1.510     www      9210:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9211:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9212:     return $symb;
1.409     www      9213: }
                   9214: 
                   9215: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9216: 
                   9217: sub encode_symb {
                   9218:     my ($map,$resid,$url)=@_;
                   9219:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9220: }
1.409     www      9221: 
                   9222: sub decode_symb {
1.568     albertel 9223:     my $symb=shift;
                   9224:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9225:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9226:     return (&fixversion($map),$resid,&fixversion($url));
                   9227: }
                   9228: 
                   9229: sub fixversion {
                   9230:     my $fn=shift;
1.609     banghart 9231:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9232:     my %bighash;
                   9233:     my $uri=&clutter($fn);
1.620     albertel 9234:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9235: # is this cached?
1.599     albertel 9236:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9237:     if (defined($cached)) { return $result; }
                   9238: # unfortunately not cached, or expired
1.620     albertel 9239:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9240: 	    &GDBM_READER(),0640)) {
                   9241:  	if ($bighash{'version_'.$uri}) {
                   9242:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9243:  	    unless (($version eq 'mostrecent') || 
                   9244: 		    ($version==&getversion($uri))) {
1.440     www      9245:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9246:  	    }
                   9247:  	}
                   9248:  	untie %bighash;
1.413     www      9249:     }
1.599     albertel 9250:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9251: }
                   9252: 
                   9253: sub deversion {
                   9254:     my $url=shift;
                   9255:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9256:     return $url;
1.210     www      9257: }
                   9258: 
1.31      www      9259: # ------------------------------------------------------ Return symb list entry
                   9260: 
                   9261: sub symbread {
1.249     www      9262:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9263:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9264:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9265: # no filename provided? try from environment
1.44      www      9266:     unless ($thisfn) {
1.620     albertel 9267:         if ($env{'request.symb'}) {
                   9268: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9269: 	}
1.620     albertel 9270: 	$thisfn=$env{'request.filename'};
1.44      www      9271:     }
1.569     albertel 9272:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9273: # is that filename actually a symb? Verify, clean, and return
                   9274:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9275: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9276: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9277: 	}
1.242     www      9278:     }
1.44      www      9279:     $thisfn=declutter($thisfn);
1.31      www      9280:     my %hash;
1.37      www      9281:     my %bighash;
                   9282:     my $syval='';
1.620     albertel 9283:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9284:         my $targetfn = $thisfn;
1.609     banghart 9285:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9286:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9287:         }
1.687     albertel 9288: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9289: 	    $targetfn=$1;
                   9290: 	}
1.620     albertel 9291:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9292:                       &GDBM_READER(),0640)) {
1.481     raeburn  9293: 	    $syval=$hash{$targetfn};
1.37      www      9294:             untie(%hash);
                   9295:         }
                   9296: # ---------------------------------------------------------- There was an entry
                   9297:         if ($syval) {
1.601     albertel 9298: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9299: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9300: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9301: 		    #return $env{$cache_str}='';
1.601     albertel 9302: 		#}    
                   9303: 		#$syval.=$1;
                   9304: 	    #}
1.37      www      9305:         } else {
                   9306: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9307:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9308:                             &GDBM_READER(),0640)) {
1.37      www      9309: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9310:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9311:               unless ($ids) { 
                   9312:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9313:               }
                   9314:               unless ($ids) {
                   9315: # alias?
                   9316: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9317:               }
1.37      www      9318:               if ($ids) {
                   9319: # ------------------------------------------------------------------- Has ID(s)
                   9320:                  my @possibilities=split(/\,/,$ids);
1.39      www      9321:                  if ($#possibilities==0) {
                   9322: # ----------------------------------------------- There is only one possibility
1.37      www      9323: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9324: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9325: 						    $resid,$thisfn);
1.249     www      9326:                  } elsif (!$donotrecurse) {
1.39      www      9327: # ------------------------------------------ There is more than one possibility
                   9328:                      my $realpossible=0;
1.800     albertel 9329:                      foreach my $id (@possibilities) {
                   9330: 			 my $file=$bighash{'src_'.$id};
1.39      www      9331:                          if (&allowed('bre',$file)) {
1.800     albertel 9332:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9333:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9334: 				$realpossible++;
1.626     albertel 9335:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9336: 						    $resid,$thisfn);
1.39      www      9337:                             }
                   9338: 			 }
1.191     harris41 9339:                      }
1.39      www      9340: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9341:                  } else {
                   9342:                      $syval='';
1.37      www      9343:                  }
                   9344: 	      }
                   9345:               untie(%bighash)
1.481     raeburn  9346:            }
1.31      www      9347:         }
1.62      www      9348:         if ($syval) {
1.620     albertel 9349: 	    return $env{$cache_str}=$syval;
1.62      www      9350:         }
1.31      www      9351:     }
1.949     raeburn  9352:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9353:     return $env{$cache_str}='';
1.31      www      9354: }
                   9355: 
                   9356: # ---------------------------------------------------------- Return random seed
                   9357: 
1.32      www      9358: sub numval {
                   9359:     my $txt=shift;
                   9360:     $txt=~tr/A-J/0-9/;
                   9361:     $txt=~tr/a-j/0-9/;
                   9362:     $txt=~tr/K-T/0-9/;
                   9363:     $txt=~tr/k-t/0-9/;
                   9364:     $txt=~tr/U-Z/0-5/;
                   9365:     $txt=~tr/u-z/0-5/;
                   9366:     $txt=~s/\D//g;
1.564     albertel 9367:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9368:     return int($txt);
1.368     albertel 9369: }
                   9370: 
1.484     albertel 9371: sub numval2 {
                   9372:     my $txt=shift;
                   9373:     $txt=~tr/A-J/0-9/;
                   9374:     $txt=~tr/a-j/0-9/;
                   9375:     $txt=~tr/K-T/0-9/;
                   9376:     $txt=~tr/k-t/0-9/;
                   9377:     $txt=~tr/U-Z/0-5/;
                   9378:     $txt=~tr/u-z/0-5/;
                   9379:     $txt=~s/\D//g;
                   9380:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9381:     my $total;
                   9382:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9383:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9384:     return int($total);
                   9385: }
                   9386: 
1.575     albertel 9387: sub numval3 {
                   9388:     use integer;
                   9389:     my $txt=shift;
                   9390:     $txt=~tr/A-J/0-9/;
                   9391:     $txt=~tr/a-j/0-9/;
                   9392:     $txt=~tr/K-T/0-9/;
                   9393:     $txt=~tr/k-t/0-9/;
                   9394:     $txt=~tr/U-Z/0-5/;
                   9395:     $txt=~tr/u-z/0-5/;
                   9396:     $txt=~s/\D//g;
                   9397:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9398:     my $total;
                   9399:     foreach my $val (@txts) { $total+=$val; }
                   9400:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9401:     return $total;
                   9402: }
                   9403: 
1.675     albertel 9404: sub digest {
                   9405:     my ($data)=@_;
                   9406:     my $digest=&Digest::MD5::md5($data);
                   9407:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9408:     my ($e,$f);
                   9409:     {
                   9410:         use integer;
                   9411:         $e=($a+$b);
                   9412:         $f=($c+$d);
                   9413:         if ($_64bit) {
                   9414:             $e=(($e<<32)>>32);
                   9415:             $f=(($f<<32)>>32);
                   9416:         }
                   9417:     }
                   9418:     if (wantarray) {
                   9419: 	return ($e,$f);
                   9420:     } else {
                   9421: 	my $g;
                   9422: 	{
                   9423: 	    use integer;
                   9424: 	    $g=($e+$f);
                   9425: 	    if ($_64bit) {
                   9426: 		$g=(($g<<32)>>32);
                   9427: 	    }
                   9428: 	}
                   9429: 	return $g;
                   9430:     }
                   9431: }
                   9432: 
1.368     albertel 9433: sub latest_rnd_algorithm_id {
1.675     albertel 9434:     return '64bit5';
1.366     albertel 9435: }
1.32      www      9436: 
1.503     albertel 9437: sub get_rand_alg {
                   9438:     my ($courseid)=@_;
1.790     albertel 9439:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9440:     if ($courseid) {
1.620     albertel 9441: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9442:     }
                   9443:     return &latest_rnd_algorithm_id();
                   9444: }
                   9445: 
1.562     albertel 9446: sub validCODE {
                   9447:     my ($CODE)=@_;
                   9448:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9449:     return 0;
                   9450: }
                   9451: 
1.491     albertel 9452: sub getCODE {
1.620     albertel 9453:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9454:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9455: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9456: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9457: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9458:     }
                   9459:     return undef;
                   9460: }
                   9461: 
1.31      www      9462: sub rndseed {
1.155     albertel 9463:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9464:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9465:     if (!defined($symb)) {
1.366     albertel 9466: 	unless ($symb=$wsymb) { return time; }
                   9467:     }
                   9468:     if (!$courseid) { $courseid=$wcourseid; }
                   9469:     if (!$domain) { $domain=$wdomain; }
                   9470:     if (!$username) { $username=$wusername }
1.503     albertel 9471:     my $which=&get_rand_alg();
1.1110    www      9472: 
1.491     albertel 9473:     if (defined(&getCODE())) {
1.675     albertel 9474: 	if ($which eq '64bit5') {
                   9475: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9476: 	} elsif ($which eq '64bit4') {
1.575     albertel 9477: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9478: 	} else {
                   9479: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9480: 	}
1.675     albertel 9481:     } elsif ($which eq '64bit5') {
                   9482: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9483:     } elsif ($which eq '64bit4') {
                   9484: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9485:     } elsif ($which eq '64bit3') {
                   9486: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9487:     } elsif ($which eq '64bit2') {
                   9488: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9489:     } elsif ($which eq '64bit') {
                   9490: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9491:     }
                   9492:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9493: }
                   9494: 
                   9495: sub rndseed_32bit {
                   9496:     my ($symb,$courseid,$domain,$username)=@_;
                   9497:     {
                   9498: 	use integer;
                   9499: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9500: 	my $symbseed=numval($symb) << 22;
                   9501: 	my $namechck=unpack("%32C*",$username) << 17;
                   9502: 	my $nameseed=numval($username) << 12;
                   9503: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9504: 	my $courseseed=unpack("%32C*",$courseid);
                   9505: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9506: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9507: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9508: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9509: 	return $num;
                   9510:     }
                   9511: }
                   9512: 
                   9513: sub rndseed_64bit {
                   9514:     my ($symb,$courseid,$domain,$username)=@_;
                   9515:     {
                   9516: 	use integer;
                   9517: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9518: 	my $symbseed=numval($symb) << 10;
                   9519: 	my $namechck=unpack("%32S*",$username);
                   9520: 	
                   9521: 	my $nameseed=numval($username) << 21;
                   9522: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9523: 	my $courseseed=unpack("%32S*",$courseid);
                   9524: 	
                   9525: 	my $num1=$symbchck+$symbseed+$namechck;
                   9526: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9527: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9528: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9529: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9530: 	return "$num1,$num2";
1.155     albertel 9531:     }
1.366     albertel 9532: }
                   9533: 
1.443     albertel 9534: sub rndseed_64bit2 {
                   9535:     my ($symb,$courseid,$domain,$username)=@_;
                   9536:     {
                   9537: 	use integer;
                   9538: 	# strings need to be an even # of cahracters long, it it is odd the
                   9539:         # last characters gets thrown away
                   9540: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9541: 	my $symbseed=numval($symb) << 10;
                   9542: 	my $namechck=unpack("%32S*",$username.' ');
                   9543: 	
                   9544: 	my $nameseed=numval($username) << 21;
1.501     albertel 9545: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9546: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9547: 	
                   9548: 	my $num1=$symbchck+$symbseed+$namechck;
                   9549: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9550: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9551: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9552: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9553: 	return "$num1,$num2";
                   9554:     }
                   9555: }
                   9556: 
                   9557: sub rndseed_64bit3 {
                   9558:     my ($symb,$courseid,$domain,$username)=@_;
                   9559:     {
                   9560: 	use integer;
                   9561: 	# strings need to be an even # of cahracters long, it it is odd the
                   9562:         # last characters gets thrown away
                   9563: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9564: 	my $symbseed=numval2($symb) << 10;
                   9565: 	my $namechck=unpack("%32S*",$username.' ');
                   9566: 	
                   9567: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9568: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9569: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9570: 	
                   9571: 	my $num1=$symbchck+$symbseed+$namechck;
                   9572: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9573: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9574: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9575: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9576: 	
1.503     albertel 9577: 	return "$num1:$num2";
1.443     albertel 9578:     }
                   9579: }
                   9580: 
1.575     albertel 9581: sub rndseed_64bit4 {
                   9582:     my ($symb,$courseid,$domain,$username)=@_;
                   9583:     {
                   9584: 	use integer;
                   9585: 	# strings need to be an even # of cahracters long, it it is odd the
                   9586:         # last characters gets thrown away
                   9587: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9588: 	my $symbseed=numval3($symb) << 10;
                   9589: 	my $namechck=unpack("%32S*",$username.' ');
                   9590: 	
                   9591: 	my $nameseed=numval3($username) << 21;
                   9592: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9593: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9594: 	
                   9595: 	my $num1=$symbchck+$symbseed+$namechck;
                   9596: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9597: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9598: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9599: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9600: 	
1.575     albertel 9601: 	return "$num1:$num2";
                   9602:     }
                   9603: }
                   9604: 
1.675     albertel 9605: sub rndseed_64bit5 {
                   9606:     my ($symb,$courseid,$domain,$username)=@_;
                   9607:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9608:     return "$num1:$num2";
                   9609: }
                   9610: 
1.366     albertel 9611: sub rndseed_CODE_64bit {
                   9612:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9613:     {
1.366     albertel 9614: 	use integer;
1.443     albertel 9615: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9616: 	my $symbseed=numval2($symb);
1.491     albertel 9617: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9618: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9619: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9620: 	my $num1=$symbseed+$CODEchck;
                   9621: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9622: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9623: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9624: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9625: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9626: 	return "$num1:$num2";
1.366     albertel 9627:     }
                   9628: }
                   9629: 
1.575     albertel 9630: sub rndseed_CODE_64bit4 {
                   9631:     my ($symb,$courseid,$domain,$username)=@_;
                   9632:     {
                   9633: 	use integer;
                   9634: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9635: 	my $symbseed=numval3($symb);
                   9636: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9637: 	my $CODEseed=numval3(&getCODE());
                   9638: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9639: 	my $num1=$symbseed+$CODEchck;
                   9640: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9641: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9642: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9643: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9644: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9645: 	return "$num1:$num2";
                   9646:     }
                   9647: }
                   9648: 
1.675     albertel 9649: sub rndseed_CODE_64bit5 {
                   9650:     my ($symb,$courseid,$domain,$username)=@_;
                   9651:     my $code = &getCODE();
                   9652:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9653:     return "$num1:$num2";
                   9654: }
                   9655: 
1.366     albertel 9656: sub setup_random_from_rndseed {
                   9657:     my ($rndseed)=@_;
1.503     albertel 9658:     if ($rndseed =~/([,:])/) {
                   9659: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9660: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9661:     } else {
                   9662: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9663:     }
1.36      albertel 9664: }
                   9665: 
1.474     albertel 9666: sub latest_receipt_algorithm_id {
1.835     albertel 9667:     return 'receipt3';
1.474     albertel 9668: }
                   9669: 
1.480     www      9670: sub recunique {
                   9671:     my $fucourseid=shift;
                   9672:     my $unique;
1.835     albertel 9673:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9674: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9675: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9676:     } else {
                   9677: 	$unique=$perlvar{'lonReceipt'};
                   9678:     }
                   9679:     return unpack("%32C*",$unique);
                   9680: }
                   9681: 
                   9682: sub recprefix {
                   9683:     my $fucourseid=shift;
                   9684:     my $prefix;
1.835     albertel 9685:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9686: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9687: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9688:     } else {
                   9689: 	$prefix=$perlvar{'lonHostID'};
                   9690:     }
                   9691:     return unpack("%32C*",$prefix);
                   9692: }
                   9693: 
1.76      www      9694: sub ireceipt {
1.474     albertel 9695:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9696: 
                   9697:     my $return =&recprefix($fucourseid).'-';
                   9698: 
                   9699:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9700: 	$env{'request.state'} eq 'construct') {
                   9701: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9702: 	return $return;
                   9703:     }
                   9704: 
1.76      www      9705:     my $cuname=unpack("%32C*",$funame);
                   9706:     my $cudom=unpack("%32C*",$fudom);
                   9707:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9708:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9709:     my $cunique=&recunique($fucourseid);
1.474     albertel 9710:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9711:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9712: 
1.790     albertel 9713: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9714: 			       
                   9715: 	$return.= ($cunique%$cuname+
                   9716: 		   $cunique%$cudom+
                   9717: 		   $cusymb%$cuname+
                   9718: 		   $cusymb%$cudom+
                   9719: 		   $cucourseid%$cuname+
                   9720: 		   $cucourseid%$cudom+
                   9721: 		   $cpart%$cuname+
                   9722: 		   $cpart%$cudom);
                   9723:     } else {
                   9724: 	$return.= ($cunique%$cuname+
                   9725: 		   $cunique%$cudom+
                   9726: 		   $cusymb%$cuname+
                   9727: 		   $cusymb%$cudom+
                   9728: 		   $cucourseid%$cuname+
                   9729: 		   $cucourseid%$cudom);
                   9730:     }
                   9731:     return $return;
1.76      www      9732: }
                   9733: 
                   9734: sub receipt {
1.474     albertel 9735:     my ($part)=@_;
1.790     albertel 9736:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9737:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9738: }
1.260     ng       9739: 
1.790     albertel 9740: sub whichuser {
                   9741:     my ($passedsymb)=@_;
                   9742:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9743:     if (defined($env{'form.grade_symb'})) {
                   9744: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9745: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9746: 	if (!$allowed &&
                   9747: 	    exists($env{'request.course.sec'}) &&
                   9748: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9749: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9750: 			      '/'.$env{'request.course.sec'});
                   9751: 	}
                   9752: 	if ($allowed) {
                   9753: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9754: 	    $courseid=$tmp_courseid;
                   9755: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9756: 	    ($name)=&get_env_multiple('form.grade_username');
                   9757: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9758: 	}
                   9759:     }
                   9760:     if (!$passedsymb) {
                   9761: 	$symb=&symbread();
                   9762:     } else {
                   9763: 	$symb=$passedsymb;
                   9764:     }
                   9765:     $courseid=$env{'request.course.id'};
                   9766:     $domain=$env{'user.domain'};
                   9767:     $name=$env{'user.name'};
                   9768:     if ($name eq 'public' && $domain eq 'public') {
                   9769: 	if (!defined($env{'form.username'})) {
                   9770: 	    $env{'form.username'}.=time.rand(10000000);
                   9771: 	}
                   9772: 	$name.=$env{'form.username'};
                   9773:     }
                   9774:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9775: 
                   9776: }
                   9777: 
1.36      albertel 9778: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9779: # returns either the contents of the file or 
                   9780: # -1 if the file doesn't exist
1.481     raeburn  9781: #
                   9782: # if the target is a file that was uploaded via DOCS, 
                   9783: # a check will be made to see if a current copy exists on the local server,
                   9784: # if it does this will be served, otherwise a copy will be retrieved from
                   9785: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9786: # the local server.   
1.472     albertel 9787: 
1.36      albertel 9788: sub getfile {
1.538     albertel 9789:     my ($file) = @_;
1.609     banghart 9790:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9791:     &repcopy($file);
                   9792:     return &readfile($file);
                   9793: }
                   9794: 
                   9795: sub repcopy_userfile {
                   9796:     my ($file)=@_;
1.609     banghart 9797:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9798:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9799:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9800: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9801:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9802:     if (-e "$file") {
1.828     www      9803: # we already have a local copy, check it out
1.538     albertel 9804: 	my @fileinfo = stat($file);
1.828     www      9805: 	my $rtncode;
                   9806: 	my $info;
1.538     albertel 9807: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9808: 	if ($lwpresp ne 'ok') {
1.828     www      9809: # there is no such file anymore, even though we had a local copy
1.482     albertel 9810: 	    if ($rtncode eq '404') {
1.538     albertel 9811: 		unlink($file);
1.482     albertel 9812: 	    }
                   9813: 	    return -1;
                   9814: 	}
                   9815: 	if ($info < $fileinfo[9]) {
1.828     www      9816: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9817: 	    return 'ok';
1.828     www      9818: 	} else {
                   9819: # the file is outdated, get rid of it
                   9820: 	    unlink($file);
1.482     albertel 9821: 	}
1.828     www      9822:     }
                   9823: # one way or the other, at this point, we don't have the file
                   9824: # construct the correct path for the file
                   9825:     my @parts = ($cdom,$cnum); 
                   9826:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9827: 	push @parts, split(/\//,$1);
                   9828:     }
                   9829:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9830:     foreach my $part (@parts) {
                   9831: 	$path .= '/'.$part;
                   9832: 	if (!-e $path) {
                   9833: 	    mkdir($path,0770);
1.482     albertel 9834: 	}
                   9835:     }
1.828     www      9836: # now the path exists for sure
                   9837: # get a user agent
                   9838:     my $ua=new LWP::UserAgent;
                   9839:     my $transferfile=$file.'.in.transfer';
                   9840: # FIXME: this should flock
                   9841:     if (-e $transferfile) { return 'ok'; }
                   9842:     my $request;
                   9843:     $uri=~s/^\///;
1.980     raeburn  9844:     my $homeserver = &homeserver($cnum,$cdom);
                   9845:     my $protocol = $protocol{$homeserver};
                   9846:     $protocol = 'http' if ($protocol ne 'https');
                   9847:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9848:     my $response=$ua->request($request,$transferfile);
                   9849: # did it work?
                   9850:     if ($response->is_error()) {
                   9851: 	unlink($transferfile);
                   9852: 	&logthis("Userfile repcopy failed for $uri");
                   9853: 	return -1;
                   9854:     }
                   9855: # worked, rename the transfer file
                   9856:     rename($transferfile,$file);
1.607     raeburn  9857:     return 'ok';
1.481     raeburn  9858: }
                   9859: 
1.517     albertel 9860: sub tokenwrapper {
                   9861:     my $uri=shift;
1.980     raeburn  9862:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9863:     $uri=~s|^/||;
1.620     albertel 9864:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9865:     my $token=$1;
1.552     albertel 9866:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9867:     if ($udom && $uname && $file) {
                   9868: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9869:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9870:         my $homeserver = &homeserver($uname,$udom);
                   9871:         my $protocol = $protocol{$homeserver};
                   9872:         $protocol = 'http' if ($protocol ne 'https');
                   9873:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9874:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9875:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9876:     } else {
                   9877:         return '/adm/notfound.html';
                   9878:     }
                   9879: }
                   9880: 
1.828     www      9881: # call with reqtype HEAD: get last modification time
                   9882: # call with reqtype GET: get the file contents
                   9883: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9884: #
1.481     raeburn  9885: sub getuploaded {
                   9886:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9887:     $uri=~s/^\///;
1.980     raeburn  9888:     my $homeserver = &homeserver($cnum,$cdom);
                   9889:     my $protocol = $protocol{$homeserver};
                   9890:     $protocol = 'http' if ($protocol ne 'https');
                   9891:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9892:     my $ua=new LWP::UserAgent;
                   9893:     my $request=new HTTP::Request($reqtype,$uri);
                   9894:     my $response=$ua->request($request);
                   9895:     $$rtncode = $response->code;
1.482     albertel 9896:     if (! $response->is_success()) {
                   9897: 	return 'failed';
                   9898:     }      
                   9899:     if ($reqtype eq 'HEAD') {
1.486     www      9900: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9901:     } elsif ($reqtype eq 'GET') {
                   9902: 	$$info = $response->content;
1.472     albertel 9903:     }
1.482     albertel 9904:     return 'ok';
1.36      albertel 9905: }
                   9906: 
1.481     raeburn  9907: sub readfile {
                   9908:     my $file = shift;
                   9909:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9910:     my $fh;
                   9911:     open($fh,"<$file");
                   9912:     my $a='';
1.800     albertel 9913:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9914:     return $a;
                   9915: }
                   9916: 
1.36      albertel 9917: sub filelocation {
1.590     banghart 9918:     my ($dir,$file) = @_;
                   9919:     my $location;
                   9920:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9921: 
                   9922:     if ($file =~ m-^/adm/-) {
                   9923: 	$file=~s-^/adm/wrapper/-/-;
                   9924: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9925:     }
1.882     albertel 9926: 
1.590     banghart 9927:     if ($file=~m:^/~:) { # is a contruction space reference
                   9928:         $location = $file;
                   9929:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9930:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9931: 	# is a correct contruction space reference
                   9932:         $location = $file;
1.956     raeburn  9933:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9934:         $location = $file;
1.609     banghart 9935:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9936:         my ($udom,$uname,$filename)=
1.811     albertel 9937:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9938:         my $home=&homeserver($uname,$udom);
                   9939:         my $is_me=0;
                   9940:         my @ids=&current_machine_ids();
                   9941:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9942:         if ($is_me) {
1.1117    foxr     9943:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9944:         } else {
                   9945:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9946:   	      $udom.'/'.$uname.'/'.$filename;
                   9947:         }
1.882     albertel 9948:     } elsif ($file =~ m-^/adm/-) {
                   9949: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9950:     } else {
                   9951:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9952:         $file=~s:^/res/:/:;
                   9953:         if ( !( $file =~ m:^/:) ) {
                   9954:             $location = $dir. '/'.$file;
                   9955:         } else {
                   9956:             $location = '/home/httpd/html/res'.$file;
                   9957:         }
1.59      albertel 9958:     }
1.590     banghart 9959:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9960:     while ($location=~m{/\.\./}) {
                   9961: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9962: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9963: 	} else {
                   9964: 	    $location=~ s{/\.\./}{/}g;
                   9965: 	}
                   9966:     } #remove dir/..
1.590     banghart 9967:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9968:     return $location;
1.46      www      9969: }
1.36      albertel 9970: 
1.46      www      9971: sub hreflocation {
                   9972:     my ($dir,$file)=@_;
1.980     raeburn  9973:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9974: 	$file=filelocation($dir,$file);
1.700     albertel 9975:     } elsif ($file=~m-^/adm/-) {
                   9976: 	$file=~s-^/adm/wrapper/-/-;
                   9977: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9978:     }
                   9979:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9980: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9981:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9982: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9983:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9984: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9985: 	    -/uploaded/$1/$2/-x;
1.46      www      9986:     }
1.913     albertel 9987:     if ($file=~ m{^/userfiles/}) {
                   9988: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9989:     }
1.462     albertel 9990:     return $file;
1.465     albertel 9991: }
                   9992: 
                   9993: sub current_machine_domains {
1.853     albertel 9994:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9995: }
                   9996: 
                   9997: sub machine_domains {
                   9998:     my ($hostname) = @_;
1.465     albertel 9999:     my @domains;
1.838     albertel 10000:     my %hostname = &all_hostnames();
1.465     albertel 10001:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10002: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10003: 	if ($hostname eq $name) {
1.844     albertel 10004: 	    push(@domains,&host_domain($id));
1.465     albertel 10005: 	}
                   10006:     }
                   10007:     return @domains;
                   10008: }
                   10009: 
                   10010: sub current_machine_ids {
1.853     albertel 10011:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10012: }
                   10013: 
                   10014: sub machine_ids {
                   10015:     my ($hostname) = @_;
                   10016:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10017:     my @ids;
1.888     albertel 10018:     my %name_to_host = &all_names();
1.889     albertel 10019:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10020: 	return @{ $name_to_host{$hostname} };
                   10021:     }
                   10022:     return;
1.31      www      10023: }
                   10024: 
1.824     raeburn  10025: sub additional_machine_domains {
                   10026:     my @domains;
                   10027:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10028:     while( my $line = <$fh>) {
                   10029:         $line =~ s/\s//g;
                   10030:         push(@domains,$line);
                   10031:     }
                   10032:     return @domains;
                   10033: }
                   10034: 
                   10035: sub default_login_domain {
                   10036:     my $domain = $perlvar{'lonDefDomain'};
                   10037:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10038:     foreach my $posdom (&current_machine_domains(),
                   10039:                         &additional_machine_domains()) {
                   10040:         if (lc($posdom) eq lc($testdomain)) {
                   10041:             $domain=$posdom;
                   10042:             last;
                   10043:         }
                   10044:     }
                   10045:     return $domain;
                   10046: }
                   10047: 
1.31      www      10048: # ------------------------------------------------------------- Declutters URLs
                   10049: 
                   10050: sub declutter {
                   10051:     my $thisfn=shift;
1.569     albertel 10052:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10053:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10054:     $thisfn=~s/^\///;
1.697     albertel 10055:     $thisfn=~s|^adm/wrapper/||;
                   10056:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10057:     $thisfn=~s/^res\///;
1.1032    raeburn  10058:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10059:         $thisfn=~s/\?.+$//;
                   10060:     }
1.268     www      10061:     return $thisfn;
                   10062: }
                   10063: 
                   10064: # ------------------------------------------------------------- Clutter up URLs
                   10065: 
                   10066: sub clutter {
                   10067:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10068:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10069: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10070:        $thisfn='/res'.$thisfn; 
                   10071:     }
1.1031    raeburn  10072:     if ($thisfn !~m|^/adm|) {
                   10073: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10074: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10075: 	} else {
                   10076: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10077: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10078: 	    if ($embstyle eq 'ssi'
                   10079: 		|| ($embstyle eq 'hdn')
                   10080: 		|| ($embstyle eq 'rat')
                   10081: 		|| ($embstyle eq 'prv')
                   10082: 		|| ($embstyle eq 'ign')) {
                   10083: 		#do nothing with these
                   10084: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10085: 		|| ($embstyle eq 'emb')
                   10086: 		|| ($embstyle eq 'wrp')) {
                   10087: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10088: 	    } elsif ($embstyle eq 'unk'
                   10089: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10090: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10091: 	    } else {
1.718     www      10092: #		&logthis("Got a blank emb style");
1.695     albertel 10093: 	    }
1.694     albertel 10094: 	}
                   10095:     }
1.31      www      10096:     return $thisfn;
1.12      www      10097: }
                   10098: 
1.787     albertel 10099: sub clutter_with_no_wrapper {
                   10100:     my $uri = &clutter(shift);
                   10101:     if ($uri =~ m-^/adm/-) {
                   10102: 	$uri =~ s-^/adm/wrapper/-/-;
                   10103: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10104:     }
                   10105:     return $uri;
                   10106: }
                   10107: 
1.557     albertel 10108: sub freeze_escape {
                   10109:     my ($value)=@_;
                   10110:     if (ref($value)) {
                   10111: 	$value=&nfreeze($value);
                   10112: 	return '__FROZEN__'.&escape($value);
                   10113:     }
                   10114:     return &escape($value);
                   10115: }
                   10116: 
1.11      www      10117: 
1.557     albertel 10118: sub thaw_unescape {
                   10119:     my ($value)=@_;
                   10120:     if ($value =~ /^__FROZEN__/) {
                   10121: 	substr($value,0,10,undef);
                   10122: 	$value=&unescape($value);
                   10123: 	return &thaw($value);
                   10124:     }
                   10125:     return &unescape($value);
                   10126: }
                   10127: 
1.436     albertel 10128: sub correct_line_ends {
                   10129:     my ($result)=@_;
                   10130:     $$result =~s/\r\n/\n/mg;
                   10131:     $$result =~s/\r/\n/mg;
1.415     albertel 10132: }
1.1       albertel 10133: # ================================================================ Main Program
                   10134: 
1.184     www      10135: sub goodbye {
1.204     albertel 10136:    &logthis("Starting Shut down");
1.443     albertel 10137: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10138:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10139: #converted
1.599     albertel 10140: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10141:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10142: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10143: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10144: #1.1 only
1.870     albertel 10145: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10146: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10147: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10148: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10149:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10150:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10151:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10152:    &flushcourselogs();
                   10153:    &logthis("Shutting down");
                   10154: }
                   10155: 
1.852     albertel 10156: sub get_dns {
1.869     albertel 10157:     my ($url,$func,$ignore_cache) = @_;
                   10158:     if (!$ignore_cache) {
                   10159: 	my ($content,$cached)=
                   10160: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10161: 	if ($cached) {
                   10162: 	    &$func($content);
                   10163: 	    return;
                   10164: 	}
                   10165:     }
                   10166: 
                   10167:     my %alldns;
1.852     albertel 10168:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10169:     foreach my $dns (<$config>) {
                   10170: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10171:         my $line = $1;
                   10172:         my ($host,$protocol) = split(/:/,$line);
                   10173:         if ($protocol ne 'https') {
                   10174:             $protocol = 'http';
                   10175:         }
                   10176: 	$alldns{$host} = $protocol;
1.869     albertel 10177:     }
                   10178:     while (%alldns) {
                   10179: 	my ($dns) = keys(%alldns);
1.852     albertel 10180: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10181: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10182: 	my $response=$ua->request($request);
1.979     raeburn  10183:         delete($alldns{$dns});
1.852     albertel 10184: 	next if ($response->is_error());
                   10185: 	my @content = split("\n",$response->content);
1.869     albertel 10186: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10187: 	&$func(\@content);
1.869     albertel 10188: 	return;
1.852     albertel 10189:     }
                   10190:     close($config);
1.871     albertel 10191:     my $which = (split('/',$url))[3];
                   10192:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10193:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10194:     my @content = <$config>;
                   10195:     &$func(\@content);
                   10196:     return;
1.852     albertel 10197: }
1.327     albertel 10198: # ------------------------------------------------------------ Read domain file
                   10199: {
1.852     albertel 10200:     my $loaded;
1.846     albertel 10201:     my %domain;
                   10202: 
1.852     albertel 10203:     sub parse_domain_tab {
                   10204: 	my ($lines) = @_;
                   10205: 	foreach my $line (@$lines) {
                   10206: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10207: 
1.846     albertel 10208: 	    chomp($line);
1.852     albertel 10209: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10210: 	    my %this_domain;
                   10211: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10212: 			       'lang_def', 'city', 'longi', 'lati',
                   10213: 			       'primary') {
                   10214: 		$this_domain{$field} = shift(@elements);
                   10215: 	    }
                   10216: 	    $domain{$name} = \%this_domain;
1.852     albertel 10217: 	}
                   10218:     }
1.864     albertel 10219: 
                   10220:     sub reset_domain_info {
                   10221: 	undef($loaded);
                   10222: 	undef(%domain);
                   10223:     }
                   10224: 
1.852     albertel 10225:     sub load_domain_tab {
1.869     albertel 10226: 	my ($ignore_cache) = @_;
                   10227: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10228: 	my $fh;
                   10229: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10230: 	    my @lines = <$fh>;
                   10231: 	    &parse_domain_tab(\@lines);
1.448     albertel 10232: 	}
1.852     albertel 10233: 	close($fh);
                   10234: 	$loaded = 1;
1.327     albertel 10235:     }
1.846     albertel 10236: 
                   10237:     sub domain {
1.852     albertel 10238: 	&load_domain_tab() if (!$loaded);
                   10239: 
1.846     albertel 10240: 	my ($name,$what) = @_;
                   10241: 	return if ( !exists($domain{$name}) );
                   10242: 
                   10243: 	if (!$what) {
                   10244: 	    return $domain{$name}{'description'};
                   10245: 	}
                   10246: 	return $domain{$name}{$what};
                   10247:     }
1.974     raeburn  10248: 
                   10249:     sub domain_info {
                   10250:         &load_domain_tab() if (!$loaded);
                   10251:         return %domain;
                   10252:     }
                   10253: 
1.327     albertel 10254: }
                   10255: 
                   10256: 
1.1       albertel 10257: # ------------------------------------------------------------- Read hosts file
                   10258: {
1.838     albertel 10259:     my %hostname;
1.844     albertel 10260:     my %hostdom;
1.845     albertel 10261:     my %libserv;
1.852     albertel 10262:     my $loaded;
1.888     albertel 10263:     my %name_to_host;
1.1074    raeburn  10264:     my %internetdom;
1.1107    raeburn  10265:     my %LC_dns_serv;
1.852     albertel 10266: 
                   10267:     sub parse_hosts_tab {
                   10268: 	my ($file) = @_;
                   10269: 	foreach my $configline (@$file) {
                   10270: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10271:             chomp($configline);
                   10272: 	    if ($configline =~ /^\^/) {
                   10273:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10274:                     $LC_dns_serv{$1} = 1;
                   10275:                 }
                   10276:                 next;
                   10277:             }
1.1074    raeburn  10278: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10279: 	    $name=~s/\s//g;
                   10280: 	    if ($id && $domain && $role && $name) {
                   10281: 		$hostname{$id}=$name;
1.888     albertel 10282: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10283: 		$hostdom{$id}=$domain;
                   10284: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10285:                 if (defined($protocol)) {
                   10286:                     if ($protocol eq 'https') {
                   10287:                         $protocol{$id} = $protocol;
                   10288:                     } else {
                   10289:                         $protocol{$id} = 'http'; 
                   10290:                     }
1.968     raeburn  10291:                 } else {
1.969     raeburn  10292:                     $protocol{$id} = 'http';
1.968     raeburn  10293:                 }
1.1074    raeburn  10294:                 if (defined($intdom)) {
                   10295:                     $internetdom{$id} = $intdom;
                   10296:                 }
1.852     albertel 10297: 	    }
                   10298: 	}
                   10299:     }
1.864     albertel 10300:     
                   10301:     sub reset_hosts_info {
1.897     albertel 10302: 	&purge_remembered();
1.864     albertel 10303: 	&reset_domain_info();
                   10304: 	&reset_hosts_ip_info();
1.892     albertel 10305: 	undef(%name_to_host);
1.864     albertel 10306: 	undef(%hostname);
                   10307: 	undef(%hostdom);
                   10308: 	undef(%libserv);
                   10309: 	undef($loaded);
                   10310:     }
1.1       albertel 10311: 
1.852     albertel 10312:     sub load_hosts_tab {
1.869     albertel 10313: 	my ($ignore_cache) = @_;
                   10314: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10315: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10316: 	my @config = <$config>;
                   10317: 	&parse_hosts_tab(\@config);
                   10318: 	close($config);
                   10319: 	$loaded=1;
1.1       albertel 10320:     }
1.852     albertel 10321: 
1.838     albertel 10322:     sub hostname {
1.852     albertel 10323: 	&load_hosts_tab() if (!$loaded);
                   10324: 
1.838     albertel 10325: 	my ($lonid) = @_;
                   10326: 	return $hostname{$lonid};
                   10327:     }
1.845     albertel 10328: 
1.838     albertel 10329:     sub all_hostnames {
1.852     albertel 10330: 	&load_hosts_tab() if (!$loaded);
                   10331: 
1.838     albertel 10332: 	return %hostname;
                   10333:     }
1.845     albertel 10334: 
1.888     albertel 10335:     sub all_names {
                   10336: 	&load_hosts_tab() if (!$loaded);
                   10337: 
                   10338: 	return %name_to_host;
                   10339:     }
                   10340: 
1.974     raeburn  10341:     sub all_host_domain {
                   10342:         &load_hosts_tab() if (!$loaded);
                   10343:         return %hostdom;
                   10344:     }
                   10345: 
1.845     albertel 10346:     sub is_library {
1.852     albertel 10347: 	&load_hosts_tab() if (!$loaded);
                   10348: 
1.845     albertel 10349: 	return exists($libserv{$_[0]});
                   10350:     }
                   10351: 
                   10352:     sub all_library {
1.852     albertel 10353: 	&load_hosts_tab() if (!$loaded);
                   10354: 
1.845     albertel 10355: 	return %libserv;
                   10356:     }
                   10357: 
1.1062    droeschl 10358:     sub unique_library {
                   10359: 	#2x reverse removes all hostnames that appear more than once
                   10360:         my %unique = reverse &all_library();
                   10361:         return reverse %unique;
                   10362:     }
                   10363: 
1.841     albertel 10364:     sub get_servers {
1.852     albertel 10365: 	&load_hosts_tab() if (!$loaded);
                   10366: 
1.841     albertel 10367: 	my ($domain,$type) = @_;
                   10368: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10369: 	                                          : %hostname;
                   10370: 	my %result;
1.842     albertel 10371: 	if (ref($domain) eq 'ARRAY') {
                   10372: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10373: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10374: 		    $result{$host} = $hostname;
                   10375: 		}
                   10376: 	    }
                   10377: 	} else {
                   10378: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10379: 		if ($hostdom{$host} eq $domain) {
                   10380: 		    $result{$host} = $hostname;
                   10381: 		}
1.841     albertel 10382: 	    }
                   10383: 	}
                   10384: 	return %result;
                   10385:     }
1.845     albertel 10386: 
1.1062    droeschl 10387:     sub get_unique_servers {
                   10388:         my %unique = reverse &get_servers(@_);
                   10389: 	return reverse %unique;
                   10390:     }
                   10391: 
1.844     albertel 10392:     sub host_domain {
1.852     albertel 10393: 	&load_hosts_tab() if (!$loaded);
                   10394: 
1.844     albertel 10395: 	my ($lonid) = @_;
                   10396: 	return $hostdom{$lonid};
                   10397:     }
                   10398: 
1.841     albertel 10399:     sub all_domains {
1.852     albertel 10400: 	&load_hosts_tab() if (!$loaded);
                   10401: 
1.841     albertel 10402: 	my %seen;
                   10403: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10404: 	return @uniq;
                   10405:     }
1.1074    raeburn  10406: 
                   10407:     sub internet_dom {
                   10408:         &load_hosts_tab() if (!$loaded);
                   10409: 
                   10410:         my ($lonid) = @_;
                   10411:         return $internetdom{$lonid};
                   10412:     }
1.1107    raeburn  10413: 
                   10414:     sub is_LC_dns {
                   10415:         &load_hosts_tab() if (!$loaded);
                   10416: 
                   10417:         my ($hostname) = @_;
                   10418:         return exists($LC_dns_serv{$hostname});
                   10419:     }
                   10420: 
1.1       albertel 10421: }
                   10422: 
1.847     albertel 10423: { 
                   10424:     my %iphost;
1.856     albertel 10425:     my %name_to_ip;
                   10426:     my %lonid_to_ip;
1.869     albertel 10427: 
1.847     albertel 10428:     sub get_hosts_from_ip {
                   10429: 	my ($ip) = @_;
                   10430: 	my %iphosts = &get_iphost();
                   10431: 	if (ref($iphosts{$ip})) {
                   10432: 	    return @{$iphosts{$ip}};
                   10433: 	}
                   10434: 	return;
1.839     albertel 10435:     }
1.864     albertel 10436:     
                   10437:     sub reset_hosts_ip_info {
                   10438: 	undef(%iphost);
                   10439: 	undef(%name_to_ip);
                   10440: 	undef(%lonid_to_ip);
                   10441:     }
1.856     albertel 10442: 
                   10443:     sub get_host_ip {
                   10444: 	my ($lonid) = @_;
                   10445: 	if (exists($lonid_to_ip{$lonid})) {
                   10446: 	    return $lonid_to_ip{$lonid};
                   10447: 	}
                   10448: 	my $name=&hostname($lonid);
                   10449:    	my $ip = gethostbyname($name);
                   10450: 	return if (!$ip || length($ip) ne 4);
                   10451: 	$ip=inet_ntoa($ip);
                   10452: 	$name_to_ip{$name}   = $ip;
                   10453: 	$lonid_to_ip{$lonid} = $ip;
                   10454: 	return $ip;
                   10455:     }
1.847     albertel 10456:     
                   10457:     sub get_iphost {
1.869     albertel 10458: 	my ($ignore_cache) = @_;
1.894     albertel 10459: 
1.869     albertel 10460: 	if (!$ignore_cache) {
                   10461: 	    if (%iphost) {
                   10462: 		return %iphost;
                   10463: 	    }
                   10464: 	    my ($ip_info,$cached)=
                   10465: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10466: 	    if ($cached) {
                   10467: 		%iphost      = %{$ip_info->[0]};
                   10468: 		%name_to_ip  = %{$ip_info->[1]};
                   10469: 		%lonid_to_ip = %{$ip_info->[2]};
                   10470: 		return %iphost;
                   10471: 	    }
                   10472: 	}
1.894     albertel 10473: 
                   10474: 	# get yesterday's info for fallback
                   10475: 	my %old_name_to_ip;
                   10476: 	my ($ip_info,$cached)=
                   10477: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10478: 	if ($cached) {
                   10479: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10480: 	}
                   10481: 
1.888     albertel 10482: 	my %name_to_host = &all_names();
                   10483: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10484: 	    my $ip;
                   10485: 	    if (!exists($name_to_ip{$name})) {
                   10486: 		$ip = gethostbyname($name);
                   10487: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10488: 		    if (defined($old_name_to_ip{$name})) {
                   10489: 			$ip = $old_name_to_ip{$name};
                   10490: 			&logthis("Can't find $name defaulting to old $ip");
                   10491: 		    } else {
                   10492: 			&logthis("Name $name no IP found");
                   10493: 			next;
                   10494: 		    }
                   10495: 		} else {
                   10496: 		    $ip=inet_ntoa($ip);
1.847     albertel 10497: 		}
                   10498: 		$name_to_ip{$name} = $ip;
                   10499: 	    } else {
                   10500: 		$ip = $name_to_ip{$name};
1.653     albertel 10501: 	    }
1.888     albertel 10502: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10503: 		$lonid_to_ip{$id} = $ip;
                   10504: 	    }
                   10505: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10506: 	}
1.869     albertel 10507: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10508: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10509: 				      48*60*60);
1.869     albertel 10510: 
1.847     albertel 10511: 	return %iphost;
1.598     albertel 10512:     }
                   10513: 
1.992     raeburn  10514:     #
                   10515:     #  Given a DNS returns the loncapa host name for that DNS 
                   10516:     # 
                   10517:     sub host_from_dns {
                   10518:         my ($dns) = @_;
                   10519:         my @hosts;
                   10520:         my $ip;
                   10521: 
1.993     raeburn  10522:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10523:             $ip = $name_to_ip{$dns};
                   10524:         }
                   10525:         if (!$ip) {
                   10526:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10527:             if (length($ip) == 4) { 
                   10528: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10529:             }
                   10530:         }
                   10531:         if ($ip) {
                   10532: 	    @hosts = get_hosts_from_ip($ip);
                   10533: 	    return $hosts[0];
                   10534:         }
                   10535:         return undef;
1.986     foxr     10536:     }
1.992     raeburn  10537: 
1.1074    raeburn  10538:     sub get_internet_names {
                   10539:         my ($lonid) = @_;
                   10540:         return if ($lonid eq '');
                   10541:         my ($idnref,$cached)=
                   10542:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10543:         if ($cached) {
                   10544:             return $idnref;
                   10545:         }
                   10546:         my $ip = &get_host_ip($lonid);
                   10547:         my @hosts = &get_hosts_from_ip($ip);
                   10548:         my %iphost = &get_iphost();
                   10549:         my (@idns,%seen);
                   10550:         foreach my $id (@hosts) {
                   10551:             my $dom = &host_domain($id);
                   10552:             my $prim_id = &domain($dom,'primary');
                   10553:             my $prim_ip = &get_host_ip($prim_id);
                   10554:             next if ($seen{$prim_ip});
                   10555:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10556:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10557:                     my $intdom = &internet_dom($id);
                   10558:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10559:                         push(@idns,$intdom);
                   10560:                     }
                   10561:                 }
                   10562:             }
                   10563:             $seen{$prim_ip} = 1;
                   10564:         }
                   10565:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10566:     }
                   10567: 
1.986     foxr     10568: }
                   10569: 
1.1079    raeburn  10570: sub all_loncaparevs {
                   10571:     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);
                   10572: }
                   10573: 
1.862     albertel 10574: BEGIN {
                   10575: 
                   10576: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10577:     unless ($readit) {
                   10578: {
                   10579:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10580:     %perlvar = (%perlvar,%{$configvars});
                   10581: }
                   10582: 
                   10583: 
1.1       albertel 10584: # ------------------------------------------------------ Read spare server file
                   10585: {
1.448     albertel 10586:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10587: 
                   10588:     while (my $configline=<$config>) {
                   10589:        chomp($configline);
1.284     matthew  10590:        if ($configline) {
1.784     albertel 10591: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10592: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10593: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10594:        }
                   10595:     }
1.448     albertel 10596:     close($config);
1.1       albertel 10597: }
1.11      www      10598: # ------------------------------------------------------------ Read permissions
                   10599: {
1.448     albertel 10600:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10601: 
                   10602:     while (my $configline=<$config>) {
1.448     albertel 10603: 	chomp($configline);
                   10604: 	if ($configline) {
                   10605: 	    my ($role,$perm)=split(/ /,$configline);
                   10606: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10607: 	}
1.11      www      10608:     }
1.448     albertel 10609:     close($config);
1.11      www      10610: }
                   10611: 
                   10612: # -------------------------------------------- Read plain texts for permissions
                   10613: {
1.448     albertel 10614:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10615: 
                   10616:     while (my $configline=<$config>) {
1.448     albertel 10617: 	chomp($configline);
                   10618: 	if ($configline) {
1.742     raeburn  10619: 	    my ($short,@plain)=split(/:/,$configline);
                   10620:             %{$prp{$short}} = ();
                   10621: 	    if (@plain > 0) {
                   10622:                 $prp{$short}{'std'} = $plain[0];
                   10623:                 for (my $i=1; $i<@plain; $i++) {
                   10624:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10625:                 }
                   10626:             }
1.448     albertel 10627: 	}
1.135     www      10628:     }
1.448     albertel 10629:     close($config);
1.135     www      10630: }
                   10631: 
                   10632: # ---------------------------------------------------------- Read package table
                   10633: {
1.448     albertel 10634:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10635: 
                   10636:     while (my $configline=<$config>) {
1.483     albertel 10637: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10638: 	chomp($configline);
                   10639: 	my ($short,$plain)=split(/:/,$configline);
                   10640: 	my ($pack,$name)=split(/\&/,$short);
                   10641: 	if ($plain ne '') {
                   10642: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10643: 	    $packagetab{$short}=$plain; 
                   10644: 	}
1.11      www      10645:     }
1.448     albertel 10646:     close($config);
1.329     matthew  10647: }
                   10648: 
1.1073    raeburn  10649: # ---------------------------------------------------------- Read loncaparev table
                   10650: {
                   10651:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10652:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10653:             while (my $configline=<$config>) {
                   10654:                 chomp($configline);
                   10655:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10656:                 $loncaparevs{$hostid}=$loncaparev;
                   10657:             }
                   10658:             close($config);
                   10659:         }
                   10660:     }
                   10661: }
                   10662: 
1.1074    raeburn  10663: # ---------------------------------------------------------- Read serverhostID table
                   10664: {
                   10665:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10666:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10667:             while (my $configline=<$config>) {
                   10668:                 chomp($configline);
                   10669:                 my ($name,$id)=split(/:/,$configline);
                   10670:                 $serverhomeIDs{$name}=$id;
                   10671:             }
                   10672:             close($config);
                   10673:         }
                   10674:     }
                   10675: }
                   10676: 
1.1079    raeburn  10677: {
                   10678:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10679:     if (-e $file) {
                   10680:         my $parser = HTML::LCParser->new($file);
                   10681:         while (my $token = $parser->get_token()) {
                   10682:             if ($token->[0] eq 'S') {
                   10683:                 my $item = $token->[1];
                   10684:                 my $name = $token->[2]{'name'};
                   10685:                 my $value = $token->[2]{'value'};
                   10686:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10687:                     my $release = $parser->get_text();
                   10688:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10689:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10690:                 }
                   10691:             }
                   10692:         }
                   10693:     }
1.1073    raeburn  10694: }
                   10695: 
1.329     matthew  10696: # ------------- set up temporary directory
                   10697: {
1.1117    foxr     10698:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10699: 
1.11      www      10700: }
                   10701: 
1.794     albertel 10702: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10703: 				'compress_threshold'=> 20_000,
                   10704:  			        });
1.185     www      10705: 
1.281     www      10706: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10707: $dumpcount=0;
1.958     www      10708: $locknum=0;
1.22      www      10709: 
1.163     harris41 10710: &logtouch();
1.672     albertel 10711: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10712: $readit=1;
1.564     albertel 10713:     {
                   10714: 	use integer;
                   10715: 	my $test=(2**32)+1;
1.568     albertel 10716: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10717: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10718:     }
1.195     www      10719: }
1.1       albertel 10720: }
1.179     www      10721: 
1.1       albertel 10722: 1;
1.191     harris41 10723: __END__
                   10724: 
1.243     albertel 10725: =pod
                   10726: 
1.191     harris41 10727: =head1 NAME
                   10728: 
1.243     albertel 10729: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10730: 
                   10731: =head1 SYNOPSIS
                   10732: 
1.243     albertel 10733: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10734: 
                   10735:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10736: 
1.243     albertel 10737: Common parameters:
                   10738: 
                   10739: =over 4
                   10740: 
                   10741: =item *
                   10742: 
                   10743: $uname : an internal username (if $cname expecting a course Id specifically)
                   10744: 
                   10745: =item *
                   10746: 
                   10747: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10748: 
                   10749: =item *
                   10750: 
                   10751: $symb : a resource instance identifier
                   10752: 
                   10753: =item *
                   10754: 
                   10755: $namespace : the name of a .db file that contains the data needed or
                   10756: being set.
                   10757: 
                   10758: =back
                   10759: 
1.394     bowersj2 10760: =head1 OVERVIEW
1.191     harris41 10761: 
1.394     bowersj2 10762: lonnet provides subroutines which interact with the
                   10763: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10764: about classes, users, and resources.
1.243     albertel 10765: 
                   10766: For many of these objects you can also use this to store data about
                   10767: them or modify them in various ways.
1.191     harris41 10768: 
1.394     bowersj2 10769: =head2 Symbs
1.191     harris41 10770: 
1.394     bowersj2 10771: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10772: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10773: map, the resource number of the resource in the map, and the URL of
                   10774: the resource itself. The latter is somewhat redundant, but might help
                   10775: if maps change.
                   10776: 
                   10777: An example is
                   10778: 
                   10779:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10780: 
                   10781: The respective map entry is
                   10782: 
                   10783:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10784:   title="Problem 2">
                   10785:  </resource>
                   10786: 
                   10787: Symbs are used by the random number generator, as well as to store and
                   10788: restore data specific to a certain instance of for example a problem.
                   10789: 
                   10790: =head2 Storing And Retrieving Data
                   10791: 
                   10792: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10793: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10794: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10795: is is the non-critical message twin of cstore. These functions are for
                   10796: handlers to store a perl hash to a user's permanent data space in an
                   10797: easy manner, and to retrieve it again on another call. It is expected
                   10798: that a handler would use this once at the beginning to retrieve data,
                   10799: and then again once at the end to send only the new data back.
                   10800: 
                   10801: The data is stored in the user's data directory on the user's
                   10802: homeserver under the ID of the course.
                   10803: 
                   10804: The hash that is returned by restore will have all of the previous
                   10805: value for all of the elements of the hash.
                   10806: 
                   10807: Example:
                   10808: 
                   10809:  #creating a hash
                   10810:  my %hash;
                   10811:  $hash{'foo'}='bar';
                   10812: 
                   10813:  #storing it
                   10814:  &Apache::lonnet::cstore(\%hash);
                   10815: 
                   10816:  #changing a value
                   10817:  $hash{'foo'}='notbar';
                   10818: 
                   10819:  #adding a new value
                   10820:  $hash{'bar'}='foo';
                   10821:  &Apache::lonnet::cstore(\%hash);
                   10822: 
                   10823:  #retrieving the hash
                   10824:  my %history=&Apache::lonnet::restore();
                   10825: 
                   10826:  #print the hash
                   10827:  foreach my $key (sort(keys(%history))) {
                   10828:    print("\%history{$key} = $history{$key}");
                   10829:  }
                   10830: 
                   10831: Will print out:
1.191     harris41 10832: 
1.394     bowersj2 10833:  %history{1:foo} = bar
                   10834:  %history{1:keys} = foo:timestamp
                   10835:  %history{1:timestamp} = 990455579
                   10836:  %history{2:bar} = foo
                   10837:  %history{2:foo} = notbar
                   10838:  %history{2:keys} = foo:bar:timestamp
                   10839:  %history{2:timestamp} = 990455580
                   10840:  %history{bar} = foo
                   10841:  %history{foo} = notbar
                   10842:  %history{timestamp} = 990455580
                   10843:  %history{version} = 2
                   10844: 
                   10845: Note that the special hash entries C<keys>, C<version> and
                   10846: C<timestamp> were added to the hash. C<version> will be equal to the
                   10847: total number of versions of the data that have been stored. The
                   10848: C<timestamp> attribute will be the UNIX time the hash was
                   10849: stored. C<keys> is available in every historical section to list which
                   10850: keys were added or changed at a specific historical revision of a
                   10851: hash.
                   10852: 
                   10853: B<Warning>: do not store the hash that restore returns directly. This
                   10854: will cause a mess since it will restore the historical keys as if the
                   10855: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10856: 
1.394     bowersj2 10857: Calling convention:
1.191     harris41 10858: 
1.394     bowersj2 10859:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10860:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10861: 
1.394     bowersj2 10862: For more detailed information, see lonnet specific documentation.
1.191     harris41 10863: 
1.394     bowersj2 10864: =head1 RETURN MESSAGES
1.191     harris41 10865: 
1.394     bowersj2 10866: =over 4
1.191     harris41 10867: 
1.394     bowersj2 10868: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10869: 
1.394     bowersj2 10870: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10871: when the connection is brought back up
1.191     harris41 10872: 
1.394     bowersj2 10873: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10874: for later delivery
1.191     harris41 10875: 
1.967     bisitz   10876: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10877: 
1.394     bowersj2 10878: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10879: that was requested
1.191     harris41 10880: 
1.243     albertel 10881: =back
1.191     harris41 10882: 
1.243     albertel 10883: =head1 PUBLIC SUBROUTINES
1.191     harris41 10884: 
1.243     albertel 10885: =head2 Session Environment Functions
1.191     harris41 10886: 
1.243     albertel 10887: =over 4
1.191     harris41 10888: 
1.394     bowersj2 10889: =item * 
                   10890: X<appenv()>
1.949     raeburn  10891: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10892: the user envirnoment file, and will be restored for each access this
1.620     albertel 10893: user makes during this session, also modifies the %env for the current
1.949     raeburn  10894: process. Optional rolesarrayref - if defined contains a reference to an array
                   10895: of roles which are exempt from the restriction on modifying user.role entries 
                   10896: in the user's environment.db and in %env.    
1.191     harris41 10897: 
                   10898: =item *
1.394     bowersj2 10899: X<delenv()>
1.987     raeburn  10900: B<delenv($delthis,$regexp)>: removes all items from the session
                   10901: environment file that begin with $delthis. If the 
                   10902: optional second arg - $regexp - is true, $delthis is treated as a 
                   10903: regular expression, otherwise \Q$delthis\E is used. 
                   10904: The values are also deleted from the current processes %env.
1.191     harris41 10905: 
1.795     albertel 10906: =item * get_env_multiple($name) 
                   10907: 
                   10908: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10909: values may be defined and end up as an array ref.
                   10910: 
                   10911: returns an array of values
                   10912: 
1.243     albertel 10913: =back
                   10914: 
                   10915: =head2 User Information
1.191     harris41 10916: 
1.243     albertel 10917: =over 4
1.191     harris41 10918: 
                   10919: =item *
1.394     bowersj2 10920: X<queryauthenticate()>
                   10921: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10922: authentication scheme
                   10923: 
                   10924: =item *
1.394     bowersj2 10925: X<authenticate()>
1.1073    raeburn  10926: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10927: authenticate user from domain's lib servers (first use the current
                   10928: one). C<$upass> should be the users password.
1.1073    raeburn  10929: $checkdefauth is optional (value is 1 if a check should be made to
                   10930:    authenticate user using default authentication method, and allow
                   10931:    account creation if username does not have account in the domain).
                   10932: $clientcancheckhost is optional (value is 1 if checking whether the
                   10933:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10934: 
                   10935: =item *
1.394     bowersj2 10936: X<homeserver()>
                   10937: B<homeserver($uname,$udom)>: find the server which has
                   10938: the user's directory and files (there must be only one), this caches
                   10939: the answer, and also caches if there is a borken connection.
1.191     harris41 10940: 
                   10941: =item *
1.394     bowersj2 10942: X<idget()>
                   10943: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10944: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10945: username, and only 1 username per ID in a specific domain) (returns
                   10946: hash: id=>name,id=>name)
1.191     harris41 10947: 
                   10948: =item *
1.394     bowersj2 10949: X<idrget()>
                   10950: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10951: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10952: 
                   10953: =item *
1.394     bowersj2 10954: X<idput()>
                   10955: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10956: 
                   10957: =item *
1.394     bowersj2 10958: X<rolesinit()>
                   10959: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10960: 
                   10961: =item *
1.551     albertel 10962: X<getsection()>
                   10963: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10964: course $cname, return section name/number or '' for "not in course"
                   10965: and '-1' for "no section"
                   10966: 
                   10967: =item *
1.394     bowersj2 10968: X<userenvironment()>
                   10969: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10970: passed in @what from the requested user's environment, returns a hash
                   10971: 
1.858     raeburn  10972: =item * 
                   10973: X<userlog_query()>
1.859     albertel 10974: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10975: activity.log file. %filters defines filters applied when parsing the
                   10976: log file. These can be start or end timestamps, or the type of action
                   10977: - log to look for Login or Logout events, check for Checkin or
                   10978: Checkout, role for role selection. The response is in the form
                   10979: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10980: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10981: 
1.243     albertel 10982: =back
                   10983: 
                   10984: =head2 User Roles
                   10985: 
                   10986: =over 4
                   10987: 
                   10988: =item *
                   10989: 
1.810     raeburn  10990: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10991:  F: full access
                   10992:  U,I,K: authentication modes (cxx only)
                   10993:  '': forbidden
                   10994:  1: user needs to choose course
                   10995:  2: browse allowed
1.766     albertel 10996:  A: passphrase authentication needed
1.243     albertel 10997: 
                   10998: =item *
                   10999: 
                   11000: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11001: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11002: and course level
                   11003: 
                   11004: =item *
                   11005: 
1.988     raeburn  11006: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11007: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11008: $type is Course (default) or Community.
1.988     raeburn  11009: If $forcedefault evaluates to true, text returned will be default 
                   11010: text for $type. Otherwise, if this is a course, the text returned 
                   11011: will be a custom name for the role (if defined in the course's 
                   11012: environment).  If no custom name is defined the default is returned.
                   11013:    
1.832     raeburn  11014: =item *
                   11015: 
1.935     raeburn  11016: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11017: All arguments are optional. Returns a hash of a roles, either for
                   11018: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11019: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11020: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11021: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11022: For each key, value is set to colon-separated start and end times for
                   11023: the role.  If no username and domain are specified, will default to
1.934     raeburn  11024: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11025: of role statuses (active, future or previous), roles 
                   11026: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11027: to restrict the list of roles reported. If no array ref is 
                   11028: provided for types, will default to return only active roles.
1.834     albertel 11029: 
1.243     albertel 11030: =back
                   11031: 
                   11032: =head2 User Modification
                   11033: 
                   11034: =over 4
                   11035: 
                   11036: =item *
                   11037: 
1.957     raeburn  11038: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11039: user for the level given by URL.  Optional start and end dates (leave empty
                   11040: string or zero for "no date")
1.191     harris41 11041: 
                   11042: =item *
                   11043: 
1.243     albertel 11044: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11045: change a users, password, possible return values are: ok,
                   11046: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11047: refused
1.191     harris41 11048: 
                   11049: =item *
                   11050: 
1.243     albertel 11051: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11052: 
                   11053: =item *
                   11054: 
1.1058    raeburn  11055: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11056:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11057: 
                   11058: will update user information (firstname,middlename,lastname,generation,
                   11059: permanentemail), and if forceid is true, student/employee ID also.
                   11060: A user's institutional affiliation(s) can also be updated.
                   11061: User information fields will not be overwritten with empty entries 
                   11062: unless the field is included in the $candelete array reference.
                   11063: This array is included when a single user is modified via "Manage Users",
                   11064: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11065: 
                   11066: =item *
                   11067: 
1.286     matthew  11068: modifystudent
                   11069: 
1.957     raeburn  11070: modify a student's enrollment and identification information.
1.286     matthew  11071: The course id is resolved based on the current users environment.  
                   11072: This means the envoking user must be a course coordinator or otherwise
                   11073: associated with a course.
                   11074: 
1.297     matthew  11075: This call is essentially a wrapper for lonnet::modifyuser and
                   11076: lonnet::modify_student_enrollment
1.286     matthew  11077: 
                   11078: Inputs: 
                   11079: 
                   11080: =over 4
                   11081: 
1.957     raeburn  11082: =item B<$udom> Student's loncapa domain
1.286     matthew  11083: 
1.957     raeburn  11084: =item B<$uname> Student's loncapa login name
1.286     matthew  11085: 
1.964     bisitz   11086: =item B<$uid> Student/Employee ID
1.286     matthew  11087: 
1.957     raeburn  11088: =item B<$umode> Student's authentication mode
1.286     matthew  11089: 
1.957     raeburn  11090: =item B<$upass> Student's password
1.286     matthew  11091: 
1.957     raeburn  11092: =item B<$first> Student's first name
1.286     matthew  11093: 
1.957     raeburn  11094: =item B<$middle> Student's middle name
1.286     matthew  11095: 
1.957     raeburn  11096: =item B<$last> Student's last name
1.286     matthew  11097: 
1.957     raeburn  11098: =item B<$gene> Student's generation
1.286     matthew  11099: 
1.957     raeburn  11100: =item B<$usec> Student's section in course
1.286     matthew  11101: 
                   11102: =item B<$end> Unix time of the roles expiration
                   11103: 
                   11104: =item B<$start> Unix time of the roles start date
                   11105: 
                   11106: =item B<$forceid> If defined, allow $uid to be changed
                   11107: 
                   11108: =item B<$desiredhome> server to use as home server for student
                   11109: 
1.957     raeburn  11110: =item B<$email> Student's permanent e-mail address
                   11111: 
                   11112: =item B<$type> Type of enrollment (auto or manual)
                   11113: 
1.963     raeburn  11114: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11115: 
                   11116: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11117: 
1.963     raeburn  11118: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11119: 
1.963     raeburn  11120: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11121: 
1.963     raeburn  11122: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11123: 
1.286     matthew  11124: =back
1.297     matthew  11125: 
                   11126: =item *
                   11127: 
                   11128: modify_student_enrollment
                   11129: 
                   11130: Change a students enrollment status in a class.  The environment variable
                   11131: 'role.request.course' must be defined for this function to proceed.
                   11132: 
                   11133: Inputs:
                   11134: 
                   11135: =over 4
                   11136: 
                   11137: =item $udom, students domain
                   11138: 
                   11139: =item $uname, students name
                   11140: 
                   11141: =item $uid, students user id
                   11142: 
                   11143: =item $first, students first name
                   11144: 
                   11145: =item $middle
                   11146: 
                   11147: =item $last
                   11148: 
                   11149: =item $gene
                   11150: 
                   11151: =item $usec
                   11152: 
                   11153: =item $end
                   11154: 
                   11155: =item $start
                   11156: 
1.957     raeburn  11157: =item $type
                   11158: 
                   11159: =item $locktype
                   11160: 
                   11161: =item $cid
                   11162: 
                   11163: =item $selfenroll
                   11164: 
                   11165: =item $context
                   11166: 
1.297     matthew  11167: =back
                   11168: 
1.191     harris41 11169: 
                   11170: =item *
                   11171: 
1.243     albertel 11172: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11173: custom role; give a custom role to a user for the level given by URL.  Specify
                   11174: name and domain of role author, and role name
1.191     harris41 11175: 
                   11176: =item *
                   11177: 
1.243     albertel 11178: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11179: 
                   11180: =item *
                   11181: 
1.243     albertel 11182: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11183: 
                   11184: =back
                   11185: 
                   11186: =head2 Course Infomation
                   11187: 
                   11188: =over 4
1.191     harris41 11189: 
                   11190: =item *
                   11191: 
1.1118    foxr     11192: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11193: specified course id, including all environment settings for the
                   11194: course, the description of the course will be in the hash under the
                   11195: key 'description'
1.191     harris41 11196: 
1.1118    foxr     11197: $options is an optional parameter that if supplied is a hash reference that controls
                   11198: what how this function works.  It has the following key/values:
                   11199: 
                   11200: =over 4
                   11201: 
                   11202: =item freshen_cache
                   11203: 
                   11204: If defined, and the environment cache for the course is valid, it is 
                   11205: returned in the returned hash.
                   11206: 
                   11207: =item one_time
                   11208: 
                   11209: If defined, the last cache time is set to _now_
                   11210: 
                   11211: =item user
                   11212: 
                   11213: If defined, the supplied username is used instead of the current user.
                   11214: 
                   11215: 
                   11216: =back
                   11217: 
1.191     harris41 11218: =item *
                   11219: 
1.624     albertel 11220: resdata($name,$domain,$type,@which) : request for current parameter
                   11221: setting for a specific $type, where $type is either 'course' or 'user',
                   11222: @what should be a list of parameters to ask about. This routine caches
                   11223: answers for 5 minutes.
1.243     albertel 11224: 
1.877     foxr     11225: =item *
                   11226: 
                   11227: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11228: data base, returning a hash that is keyed by the resource name and has
                   11229: values that are the resource value.  I believe that the timestamps and
                   11230: versions are also returned.
                   11231: 
                   11232: 
1.243     albertel 11233: =back
                   11234: 
                   11235: =head2 Course Modification
                   11236: 
                   11237: =over 4
1.191     harris41 11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: writecoursepref($courseid,%prefs) : write preferences (environment
                   11242: database) for a course
1.191     harris41 11243: 
                   11244: =item *
                   11245: 
1.1011    raeburn  11246: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11247: 
                   11248: =item *
                   11249: 
1.1038    raeburn  11250: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11251: 
                   11252: =back
                   11253: 
                   11254: =head2 Resource Subroutines
                   11255: 
                   11256: =over 4
1.191     harris41 11257: 
                   11258: =item *
                   11259: 
1.243     albertel 11260: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11261: 
                   11262: =item *
                   11263: 
1.243     albertel 11264: repcopy($filename) : subscribes to the requested file, and attempts to
                   11265: replicate from the owning library server, Might return
1.607     raeburn  11266: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11267: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11268: resource. Expects the local filesystem pathname
                   11269: (/home/httpd/html/res/....)
                   11270: 
                   11271: =back
                   11272: 
                   11273: =head2 Resource Information
                   11274: 
                   11275: =over 4
1.191     harris41 11276: 
                   11277: =item *
                   11278: 
1.243     albertel 11279: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11280: a vairety of different possible values, $varname should be a request
                   11281: string, and the other parameters can be used to specify who and what
                   11282: one is asking about.
                   11283: 
                   11284: Possible values for $varname are environment.lastname (or other item
                   11285: from the envirnment hash), user.name (or someother aspect about the
                   11286: user), resource.0.maxtries (or some other part and parameter of a
                   11287: resource)
1.204     albertel 11288: 
                   11289: =item *
                   11290: 
1.243     albertel 11291: directcondval($number) : get current value of a condition; reads from a state
                   11292: string
1.204     albertel 11293: 
                   11294: =item *
                   11295: 
1.243     albertel 11296: condval($condidx) : value of condition index based on state
1.204     albertel 11297: 
                   11298: =item *
                   11299: 
1.243     albertel 11300: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11301: resource's metadata, $what should be either a specific key, or either
                   11302: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11303: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11304: 
                   11305: this function automatically caches all requests
1.191     harris41 11306: 
                   11307: =item *
                   11308: 
1.243     albertel 11309: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11310: network of library servers; returns file handle of where SQL and regex results
                   11311: will be stored for query
1.191     harris41 11312: 
                   11313: =item *
                   11314: 
1.243     albertel 11315: symbread($filename) : return symbolic list entry (filename argument optional);
                   11316: returns the data handle
1.191     harris41 11317: 
                   11318: =item *
                   11319: 
1.243     albertel 11320: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11321: a possible symb for the URL in $thisfn, and if is an encryypted
                   11322: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11323: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11324: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11325: 
1.191     harris41 11326: 
                   11327: =item *
                   11328: 
1.243     albertel 11329: symbclean($symb) : removes versions numbers from a symb, returns the
                   11330: cleaned symb
1.191     harris41 11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11335: course map, user must be in a course for it to work.
1.191     harris41 11336: 
                   11337: =item *
                   11338: 
1.243     albertel 11339: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11340: 
                   11341: =item *
                   11342: 
1.243     albertel 11343: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11344: a random seed, all arguments are optional, if they aren't sent it uses the
                   11345: environment to derive them. Note: if symb isn't sent and it can't get one
                   11346: from &symbread it will use the current time as its return value
1.191     harris41 11347: 
                   11348: =item *
                   11349: 
1.243     albertel 11350: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11351: unfakeable, receipt
1.191     harris41 11352: 
                   11353: =item *
                   11354: 
1.620     albertel 11355: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11356: 
                   11357: =item *
                   11358: 
1.243     albertel 11359: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11360: 
                   11361: =item *
                   11362: 
1.243     albertel 11363: 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 11364: 
                   11365: =item *
                   11366: 
1.243     albertel 11367: 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 11368: 
                   11369: =item *
                   11370: 
1.243     albertel 11371: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11372: 
                   11373: =item *
                   11374: 
1.243     albertel 11375: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11376: forcing spreadsheet to reevaluate the resource scores next time.
                   11377: 
                   11378: =back
                   11379: 
                   11380: =head2 Storing/Retreiving Data
                   11381: 
                   11382: =over 4
1.191     harris41 11383: 
                   11384: =item *
                   11385: 
1.243     albertel 11386: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11387: for this url; hashref needs to be given and should be a \%hashname; the
                   11388: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11389: be derived from the env
1.191     harris41 11390: 
                   11391: =item *
                   11392: 
1.243     albertel 11393: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11394: uses critical subroutine
1.191     harris41 11395: 
                   11396: =item *
                   11397: 
1.243     albertel 11398: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11399: all args are optional
1.191     harris41 11400: 
                   11401: =item *
                   11402: 
1.717     albertel 11403: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11404: dumps the complete (or key matching regexp) namespace into a hash
                   11405: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11406: normally &store()ed into
                   11407: 
                   11408: $range should be either an integer '100' (give me the first 100
                   11409:                                            matching records)
                   11410:               or be  two integers sperated by a - with no spaces
                   11411:                  '30-50' (give me the 30th through the 50th matching
                   11412:                           records)
                   11413: 
                   11414: 
                   11415: =item *
                   11416: 
                   11417: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11418: replaces a &store() version of data with a replacement set of data
                   11419: for a particular resource in a namespace passed in the $storehash hash 
                   11420: reference
                   11421: 
                   11422: =item *
                   11423: 
1.243     albertel 11424: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11425: works very similar to store/cstore, but all data is stored in a
                   11426: temporary location and can be reset using tmpreset, $storehash should
                   11427: be a hash reference, returns nothing on success
1.191     harris41 11428: 
                   11429: =item *
                   11430: 
1.243     albertel 11431: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11432: similar to restore, but all data is stored in a temporary location and
                   11433: can be reset using tmpreset. Returns a hash of values on success,
                   11434: error string otherwise.
1.191     harris41 11435: 
                   11436: =item *
                   11437: 
1.243     albertel 11438: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11439: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11440: 
                   11441: =item *
                   11442: 
1.243     albertel 11443: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11444: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11445: 
                   11446: =item *
                   11447: 
1.243     albertel 11448: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11449: namesp ($udom and $uname are optional)
1.191     harris41 11450: 
                   11451: =item *
                   11452: 
1.702     albertel 11453: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11454: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11455: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11456: 
1.702     albertel 11457: $range should be either an integer '100' (give me the first 100
                   11458:                                            matching records)
                   11459:               or be  two integers sperated by a - with no spaces
                   11460:                  '30-50' (give me the 30th through the 50th matching
                   11461:                           records)
1.449     matthew  11462: =item *
                   11463: 
                   11464: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11465: $store can be a scalar, an array reference, or if the amount to be 
                   11466: incremented is > 1, a hash reference.
                   11467: 
                   11468: ($udom and $uname are optional)
1.191     harris41 11469: 
                   11470: =item *
                   11471: 
1.243     albertel 11472: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11473: ($udom and $uname are optional)
1.191     harris41 11474: 
                   11475: =item *
                   11476: 
1.243     albertel 11477: cput($namespace,$storehash,$udom,$uname) : critical put
                   11478: ($udom and $uname are optional)
1.191     harris41 11479: 
                   11480: =item *
                   11481: 
1.748     albertel 11482: newput($namespace,$storehash,$udom,$uname) :
                   11483: 
                   11484: Attempts to store the items in the $storehash, but only if they don't
                   11485: currently exist, if this succeeds you can be certain that you have 
                   11486: successfully created a new key value pair in the $namespace db.
                   11487: 
                   11488: 
                   11489: Args:
                   11490:  $namespace: name of database to store values to
                   11491:  $storehash: hashref to store to the db
                   11492:  $udom: (optional) domain of user containing the db
                   11493:  $uname: (optional) name of user caontaining the db
                   11494: 
                   11495: Returns:
                   11496:  'ok' -> succeeded in storing all keys of $storehash
                   11497:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11498:                         least <key> already existed in the db (other
                   11499:                         requested keys may also already exist)
1.967     bisitz   11500:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11501:  'con_lost' -> unable to contact request server
                   11502:  'refused' -> action was not allowed by remote machine
                   11503: 
                   11504: 
                   11505: =item *
                   11506: 
1.243     albertel 11507: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11508: reference filled in from namesp (encrypts the return communication)
                   11509: ($udom and $uname are optional)
1.191     harris41 11510: 
                   11511: =item *
                   11512: 
1.243     albertel 11513: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11514: critical subroutine
                   11515: 
1.806     raeburn  11516: =item *
                   11517: 
1.860     raeburn  11518: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11519: array reference filled in from namespace found in domain level on either
                   11520: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11521: 
                   11522: =item *
                   11523: 
1.860     raeburn  11524: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11525: domain level either on specified domain server ($uhome) or primary domain 
                   11526: server ($udom and $uhome are optional)
1.806     raeburn  11527: 
1.943     raeburn  11528: =item * 
                   11529: 
                   11530: get_domain_defaults($target_domain) : returns hash with defaults for
                   11531: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11532: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11533: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11534: Values are retrieved from cache (if current), or from domain's configuration.db
                   11535: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11536: or lonTabs/domain.tab. 
                   11537: 
                   11538: %domdefaults = &get_auth_defaults($target_domain);
                   11539: 
1.243     albertel 11540: =back
                   11541: 
                   11542: =head2 Network Status Functions
                   11543: 
                   11544: =over 4
1.191     harris41 11545: 
                   11546: =item *
                   11547: 
                   11548: dirlist($uri) : return directory list based on URI
                   11549: 
                   11550: =item *
                   11551: 
1.243     albertel 11552: spareserver() : find server with least workload from spare.tab
                   11553: 
1.986     foxr     11554: 
                   11555: =item *
                   11556: 
                   11557: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11558: if there is no corresponding loncapa host.
                   11559: 
1.243     albertel 11560: =back
                   11561: 
1.986     foxr     11562: 
1.243     albertel 11563: =head2 Apache Request
                   11564: 
                   11565: =over 4
1.191     harris41 11566: 
                   11567: =item *
                   11568: 
1.243     albertel 11569: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11570: localhost, posts hash
                   11571: 
                   11572: =back
                   11573: 
                   11574: =head2 Data to String to Data
                   11575: 
                   11576: =over 4
1.191     harris41 11577: 
                   11578: =item *
                   11579: 
1.243     albertel 11580: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11581: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11582: 
                   11583: =item *
                   11584: 
1.243     albertel 11585: hashref2str($hashref) : convert a hashref into a string complete with
                   11586: escaping and '=' and '&' separators, supports elements that are
                   11587: arrayrefs and hashrefs
1.191     harris41 11588: 
                   11589: =item *
                   11590: 
1.243     albertel 11591: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11592: with escaping and '&' separators, supports elements that are arrayrefs
                   11593: and hashrefs
1.191     harris41 11594: 
                   11595: =item *
                   11596: 
1.243     albertel 11597: str2hash($string) : convert string to hash using unescaping and
                   11598: splitting on '=' and '&', supports elements that are arrayrefs and
                   11599: hashrefs
1.191     harris41 11600: 
                   11601: =item *
                   11602: 
1.243     albertel 11603: str2array($string) : convert string to hash using unescaping and
                   11604: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11605: 
                   11606: =back
                   11607: 
                   11608: =head2 Logging Routines
                   11609: 
                   11610: 
                   11611: These routines allow one to make log messages in the lonnet.log and
                   11612: lonnet.perm logfiles.
1.191     harris41 11613: 
1.1119    foxr     11614: =over 4
                   11615: 
1.191     harris41 11616: =item *
                   11617: 
1.243     albertel 11618: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11619: 
                   11620: =item *
                   11621: 
1.243     albertel 11622: logthis() : append message to the normal lonnet.log file, it gets
                   11623: preiodically rolled over and deleted.
1.191     harris41 11624: 
                   11625: =item *
                   11626: 
1.243     albertel 11627: logperm() : append a permanent message to lonnet.perm.log, this log
                   11628: file never gets deleted by any automated portion of the system, only
                   11629: messages of critical importance should go in here.
                   11630: 
1.1119    foxr     11631: 
1.243     albertel 11632: =back
                   11633: 
                   11634: =head2 General File Helper Routines
                   11635: 
                   11636: =over 4
1.191     harris41 11637: 
                   11638: =item *
                   11639: 
1.481     raeburn  11640: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11641: (a) files in /uploaded
                   11642:   (i) If a local copy of the file exists - 
                   11643:       compares modification date of local copy with last-modified date for 
                   11644:       definitive version stored on home server for course. If local copy is 
                   11645:       stale, requests a new version from the home server and stores it. 
                   11646:       If the original has been removed from the home server, then local copy 
                   11647:       is unlinked.
                   11648:   (ii) If local copy does not exist -
                   11649:       requests the file from the home server and stores it. 
                   11650:   
                   11651:   If $caller is 'uploadrep':  
                   11652:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11653:     for request for files originally uploaded via DOCS. 
                   11654:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11655:   
                   11656:   Otherwise:
                   11657:      This indicates a call from the content generation phase of the request.
                   11658:      -  returns the entire contents of the file or -1.
                   11659:      
                   11660: (b) files in /res
                   11661:    - returns the entire contents of a file or -1; 
                   11662:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11663: 
1.712     albertel 11664: 
                   11665: =item *
                   11666: 
                   11667: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11668:                   reference
                   11669: 
                   11670: returns either a stat() list of data about the file or an empty list
                   11671: if the file doesn't exist or couldn't find out about it (connection
                   11672: problems or user unknown)
                   11673: 
1.191     harris41 11674: =item *
                   11675: 
1.243     albertel 11676: filelocation($dir,$file) : returns file system location of a file
                   11677: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11678: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11679: and a file of ../bob will become /a/bob)
1.191     harris41 11680: 
                   11681: =item *
                   11682: 
                   11683: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11684: filelocation except for hrefs
                   11685: 
                   11686: =item *
                   11687: 
                   11688: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11689: 
1.243     albertel 11690: =back
                   11691: 
1.608     albertel 11692: =head2 Usererfile file routines (/uploaded*)
                   11693: 
                   11694: =over 4
                   11695: 
                   11696: =item *
                   11697: 
                   11698: userfileupload(): main rotine for putting a file in a user or course's
                   11699:                   filespace, arguments are,
                   11700: 
1.620     albertel 11701:  formname - required - this is the name of the element in $env where the
1.608     albertel 11702:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11703:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11704:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11705:  context - if coursedoc, store the file in the course of the active role
                   11706:              of the current user; 
                   11707:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11708:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11709:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11710:          if undefined, it will be placed in "unknown"
                   11711: 
                   11712:  (This routine calls clean_filename() to remove any dangerous
                   11713:  characters from the filename, and then calls finuserfileupload() to
                   11714:  complete the transaction)
                   11715: 
                   11716:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11717:  and /adm/notfound.html if unsuccessful
                   11718: 
                   11719: =item *
                   11720: 
                   11721: clean_filename(): routine for cleaing a filename up for storage in
                   11722:                  userfile space, argument is:
                   11723: 
                   11724:  filename - proposed filename
                   11725: 
                   11726: returns: the new clean filename
                   11727: 
                   11728: =item *
                   11729: 
1.1090    raeburn  11730: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11731: userspace, probably shouldn't be called directly
                   11732: 
                   11733:   docuname: username or courseid of destination for the file
                   11734:   docudom: domain of user/course of destination for the file
                   11735:   formname: same as for userfileupload()
1.1090    raeburn  11736:   fname: filename (including subdirectories) for the file
                   11737:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11738:   allfiles: reference to hash used to store objects found by parser
                   11739:   codebase: reference to hash used for codebases of java objects found by parser
                   11740:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11741:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11742:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11743:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11744:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11745:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11746:   mimetype: reference to scalar to accommodate mime type determined
                   11747:             from File::MMagic if $parser = parse.
1.608     albertel 11748: 
                   11749:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11750:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11751:  was 'overwrite').
                   11752:  
1.608     albertel 11753: 
                   11754: =item *
                   11755: 
                   11756: renameuserfile(): renames an existing userfile to a new name
                   11757: 
                   11758:   Args:
                   11759:    docuname: username or courseid of destination for the file
                   11760:    docudom: domain of user/course of destination for the file
                   11761:    old: current file name (including any subdirs under userfiles)
                   11762:    new: desired file name (including any subdirs under userfiles)
                   11763: 
                   11764: =item *
                   11765: 
                   11766: mkdiruserfile(): creates a directory is a userfiles dir
                   11767: 
                   11768:   Args:
                   11769:    docuname: username or courseid of destination for the file
                   11770:    docudom: domain of user/course of destination for the file
                   11771:    dir: dir to create (including any subdirs under userfiles)
                   11772: 
                   11773: =item *
                   11774: 
                   11775: removeuserfile(): removes a file that exists in userfiles
                   11776: 
                   11777:   Args:
                   11778:    docuname: username or courseid of destination for the file
                   11779:    docudom: domain of user/course of destination for the file
                   11780:    fname: filname to delete (including any subdirs under userfiles)
                   11781: 
                   11782: =item *
                   11783: 
                   11784: removeuploadedurl(): convience function for removeuserfile()
                   11785: 
                   11786:   Args:
                   11787:    url:  a full /uploaded/... url to delete
                   11788: 
1.747     albertel 11789: =item * 
                   11790: 
                   11791: get_portfile_permissions():
                   11792:   Args:
                   11793:     domain: domain of user or course contain the portfolio files
                   11794:     user: name of user or num of course contain the portfolio files
                   11795:   Returns:
                   11796:     hashref of a dump of the proper file_permissions.db
                   11797:    
                   11798: 
                   11799: =item * 
                   11800: 
                   11801: get_access_controls():
                   11802: 
                   11803: Args:
                   11804:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11805:   group: (optional) the group you want the files associated with
                   11806:   file: (optional) the file you want access info on
                   11807: 
                   11808: Returns:
1.749     raeburn  11809:     a hash (keys are file names) of hashes containing
                   11810:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11811:         values are XML containing access control settings (see below) 
1.747     albertel 11812: 
                   11813: Internal notes:
                   11814: 
1.749     raeburn  11815:  access controls are stored in file_permissions.db as key=value pairs.
                   11816:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11817:         where scope -> public,guest,course,group,domains or users.
                   11818:               end -> UNIX time for end of access (0 -> no end date)
                   11819:               start -> UNIX time for start of access
                   11820: 
                   11821:     value -> XML description of access control
                   11822:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11823:             <start></start>
                   11824:             <end></end>
                   11825: 
                   11826:             <password></password>  for scope type = guest
                   11827: 
                   11828:             <domain></domain>     for scope type = course or group
                   11829:             <number></number>
                   11830:             <roles id="">
                   11831:              <role></role>
                   11832:              <access></access>
                   11833:              <section></section>
                   11834:              <group></group>
                   11835:             </roles>
                   11836: 
                   11837:             <dom></dom>         for scope type = domains
                   11838: 
                   11839:             <users>             for scope type = users
                   11840:              <user>
                   11841:               <uname></uname>
                   11842:               <udom></udom>
                   11843:              </user>
                   11844:             </users>
                   11845:            </scope> 
                   11846:               
                   11847:  Access data is also aggregated for each file in an additional key=value pair:
                   11848:  key -> path to file/file_name\0accesscontrol 
                   11849:  value -> reference to hash
                   11850:           hash contains key = value pairs
                   11851:           where key = uniqueID:scope_end_start
                   11852:                 value = UNIX time record was last updated
                   11853: 
                   11854:           Used to improve speed of look-ups of access controls for each file.  
                   11855:  
                   11856:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11857: 
                   11858: modify_access_controls():
                   11859: 
                   11860: Modifies access controls for a portfolio file
                   11861: Args
                   11862: 1. file name
                   11863: 2. reference to hash of required changes,
                   11864: 3. domain
                   11865: 4. username
                   11866:   where domain,username are the domain of the portfolio owner 
                   11867:   (either a user or a course) 
                   11868: 
                   11869: Returns:
                   11870: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11871: 2. result of deletions ('ok' or 'error', with error message).
                   11872: 3. reference to hash of any new or updated access controls.
                   11873: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11874:    key = integer (inbound ID)
                   11875:    value = uniqueID  
1.747     albertel 11876: 
1.608     albertel 11877: =back
                   11878: 
1.243     albertel 11879: =head2 HTTP Helper Routines
                   11880: 
                   11881: =over 4
                   11882: 
1.191     harris41 11883: =item *
                   11884: 
                   11885: escape() : unpack non-word characters into CGI-compatible hex codes
                   11886: 
                   11887: =item *
                   11888: 
                   11889: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11890: 
1.243     albertel 11891: =back
                   11892: 
                   11893: =head1 PRIVATE SUBROUTINES
                   11894: 
                   11895: =head2 Underlying communication routines (Shouldn't call)
                   11896: 
                   11897: =over 4
                   11898: 
                   11899: =item *
                   11900: 
                   11901: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11902: 
                   11903: =item *
                   11904: 
                   11905: reply() : uses subreply to send a message to remote machine, logs all failures
                   11906: 
                   11907: =item *
                   11908: 
                   11909: critical() : passes a critical message to another server; if cannot
                   11910: get through then place message in connection buffer directory and
                   11911: returns con_delayed, if incapable of saving message, returns
                   11912: con_failed
                   11913: 
                   11914: =item *
                   11915: 
                   11916: reconlonc() : tries to reconnect lonc client processes.
                   11917: 
                   11918: =back
                   11919: 
                   11920: =head2 Resource Access Logging
                   11921: 
                   11922: =over 4
                   11923: 
                   11924: =item *
                   11925: 
                   11926: flushcourselogs() : flush (save) buffer logs and access logs
                   11927: 
                   11928: =item *
                   11929: 
                   11930: courselog($what) : save message for course in hash
                   11931: 
                   11932: =item *
                   11933: 
                   11934: courseacclog($what) : save message for course using &courselog().  Perform
                   11935: special processing for specific resource types (problems, exams, quizzes, etc).
                   11936: 
1.191     harris41 11937: =item *
                   11938: 
                   11939: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11940: as a PerlChildExitHandler
1.243     albertel 11941: 
                   11942: =back
                   11943: 
                   11944: =head2 Other
                   11945: 
                   11946: =over 4
                   11947: 
                   11948: =item *
                   11949: 
                   11950: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11951: 
                   11952: =back
                   11953: 
                   11954: =cut
1.877     foxr     11955: 

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