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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1136  ! raeburn     4: # $Id: lonnet.pm,v 1.1135 2011/10/16 14:24:39 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1117    foxr       98: 
1.1090    raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1106    raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1073    raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1073    raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   258:                     $ua->timeout(4);
1.1073    raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1081    raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1081    raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   274:                 $loncaparev = $1;
                    275:             }
1.993     raeburn   276:         }
1.1073    raeburn   277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   278:     }
                    279: }
                    280: 
1.1074    raeburn   281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    285:         if (defined($cached)) {
                    286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') { 
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
                    299:         }
                    300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
                    305:     }
                    306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    307: }
                    308: 
1.1121    raeburn   309: sub get_remote_globals {
                    310:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   311:     my ($result,%returnhash,%whatneeded);
                    312:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   313:         foreach my $what (sort(keys(%{$whathash}))) {
                    314:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   315:             my ($response,$cached);
1.1121    raeburn   316:             unless ($ignore_cache) {
1.1125    raeburn   317:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   318:             }
                    319:             if (defined($cached)) {
1.1125    raeburn   320:                 $returnhash{$what} = $response;
1.1121    raeburn   321:             } else {
1.1125    raeburn   322:                 $whatneeded{$what} = 1;
1.1121    raeburn   323:             }
                    324:         }
1.1125    raeburn   325:         if (keys(%whatneeded) == 0) {
                    326:             $result = 'ok';
                    327:         } else {
1.1121    raeburn   328:             my $requested = &freeze_escape(\%whatneeded);
                    329:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   330:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    331:                 ($rep eq 'unknown_cmd')) {
                    332:                 $result = $rep;
                    333:             } else {
                    334:                 $result = 'ok';
1.1121    raeburn   335:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   336:                 foreach my $item (@pairs) {
                    337:                     my ($key,$value)=split(/=/,$item,2);
                    338:                     my $what = &unescape($key);
                    339:                     my $hashid = $lonhost.'-'.$what;
                    340:                     $returnhash{$what}=&thaw_unescape($value);
                    341:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   342:                 }
                    343:             }
                    344:         }
                    345:     }
1.1125    raeburn   346:     return ($result,\%returnhash);
1.1121    raeburn   347: }
                    348: 
1.1124    raeburn   349: sub remote_devalidate_cache {
                    350:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   351:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   352:     return $response;
                    353: }
                    354: 
1.1       albertel  355: # -------------------------------------------------- Non-critical communication
                    356: sub subreply {
                    357:     my ($cmd,$server)=@_;
1.838     albertel  358:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      359:     #
                    360:     #  With loncnew process trimming, there's a timing hole between lonc server
                    361:     #  process exit and the master server picking up the listen on the AF_UNIX
                    362:     #  socket.  In that time interval, a lock file will exist:
                    363: 
                    364:     my $lockfile=$peerfile.".lock";
                    365:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    366: 	sleep(1);
                    367:     }
                    368:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      369:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      370:     #
1.550     foxr      371:     #   We'll give the connection a few tries before abandoning it.  If
                    372:     #   connection is not possible, we'll con_lost back to the client.
                    373:     #   
                    374:     my $client;
                    375:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    376: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    377: 				      Type    => SOCK_STREAM,
                    378: 				      Timeout => 10);
1.869     albertel  379: 	if ($client) {
1.550     foxr      380: 	    last;		# Connected!
1.850     albertel  381: 	} else {
1.853     albertel  382: 	    &create_connection(&hostname($server),$server);
1.550     foxr      383: 	}
1.850     albertel  384:         sleep(1);		# Try again later if failed connection.
1.550     foxr      385:     }
                    386:     my $answer;
                    387:     if ($client) {
1.704     albertel  388: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      389: 	$answer=<$client>;
                    390: 	if (!$answer) { $answer="con_lost"; }
                    391: 	chomp($answer);
                    392:     } else {
                    393: 	$answer = 'con_lost';	# Failed connection.
                    394:     }
1.1       albertel  395:     return $answer;
                    396: }
                    397: 
                    398: sub reply {
                    399:     my ($cmd,$server)=@_;
1.838     albertel  400:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  401:     my $answer=subreply($cmd,$server);
1.65      www       402:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  403:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       404:                 " $cmd to $server returned $answer</font>");
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: # ----------------------------------------------------------- Send USR1 to lonc
                    410: 
                    411: sub reconlonc {
1.891     albertel  412:     my ($lonid) = @_;
                    413:     my $hostname = &hostname($lonid);
                    414:     if ($lonid) {
                    415: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    416: 	if ($hostname && -e $peerfile) {
                    417: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    418: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    419: 					     Type    => SOCK_STREAM,
                    420: 					     Timeout => 10);
                    421: 	    if ($client) {
                    422: 		print $client ("reset_retries\n");
                    423: 		my $answer=<$client>;
                    424: 		#reset just this one.
                    425: 	    }
                    426: 	}
                    427: 	return;
                    428:     }
                    429: 
1.836     www       430:     &logthis("Trying to reconnect lonc");
1.1       albertel  431:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  432:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  433: 	my $loncpid=<$fh>;
                    434:         chomp($loncpid);
                    435:         if (kill 0 => $loncpid) {
                    436: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    437:             kill USR1 => $loncpid;
                    438:             sleep 1;
1.836     www       439:          } else {
1.12      www       440: 	    &logthis(
1.672     albertel  441:                "<font color=\"blue\">WARNING:".
1.12      www       442:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  443:         }
                    444:     } else {
1.836     www       445: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  446:     }
                    447: }
                    448: 
                    449: # ------------------------------------------------------ Critical communication
1.12      www       450: 
1.1       albertel  451: sub critical {
                    452:     my ($cmd,$server)=@_;
1.838     albertel  453:     unless (&hostname($server)) {
1.672     albertel  454:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       455:                " Critical message to unknown server ($server)</font>");
                    456:         return 'no_such_host';
                    457:     }
1.1       albertel  458:     my $answer=reply($cmd,$server);
                    459:     if ($answer eq 'con_lost') {
                    460: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  461: 	my $answer=reply($cmd,$server);
1.1       albertel  462:         if ($answer eq 'con_lost') {
                    463:             my $now=time;
                    464:             my $middlename=$cmd;
1.5       www       465:             $middlename=substr($middlename,0,16);
1.1       albertel  466:             $middlename=~s/\W//g;
                    467:             my $dfilename=
1.305     www       468:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    469:             $dumpcount++;
1.1       albertel  470:             {
1.448     albertel  471: 		my $dfh;
                    472: 		if (open($dfh,">$dfilename")) {
                    473: 		    print $dfh "$cmd\n"; 
                    474: 		    close($dfh);
                    475: 		}
1.1       albertel  476:             }
                    477:             sleep 2;
                    478:             my $wcmd='';
                    479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,"<$dfilename")) {
                    482: 		    $wcmd=<$dfh>; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             chomp($wcmd);
1.7       www       487:             if ($wcmd eq $cmd) {
1.672     albertel  488: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       489:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  490:                 &logperm("D:$server:$cmd");
                    491: 	        return 'con_delayed';
                    492:             } else {
1.672     albertel  493:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       494:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  495:                 &logperm("F:$server:$cmd");
                    496:                 return 'con_failed';
                    497:             }
                    498:         }
                    499:     }
                    500:     return $answer;
1.405     albertel  501: }
                    502: 
1.755     albertel  503: # ------------------------------------------- check if return value is an error
                    504: 
                    505: sub error {
                    506:     my ($result) = @_;
1.756     albertel  507:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  508: 	if ($2 == 2) { return undef; }
                    509: 	return $1;
                    510:     }
                    511:     return undef;
                    512: }
                    513: 
1.783     albertel  514: sub convert_and_load_session_env {
                    515:     my ($lonidsdir,$handle)=@_;
                    516:     my @profile;
                    517:     {
1.917     albertel  518: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    519: 	if (!$opened) {
1.915     albertel  520: 	    return 0;
                    521: 	}
1.783     albertel  522: 	flock($idf,LOCK_SH);
                    523: 	@profile=<$idf>;
                    524: 	close($idf);
                    525:     }
                    526:     my %temp_env;
                    527:     foreach my $line (@profile) {
1.786     albertel  528: 	if ($line !~ m/=/) {
                    529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	chomp($line);
                    532: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    533: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    534:     }
                    535:     unlink("$lonidsdir/$handle.id");
                    536:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    537: 	    0640)) {
                    538: 	%disk_env = %temp_env;
                    539: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    540: 	untie(%disk_env);
                    541:     }
1.786     albertel  542:     return 1;
1.783     albertel  543: }
                    544: 
1.374     www       545: # ------------------------------------------- Transfer profile into environment
1.780     albertel  546: my $env_loaded;
                    547: sub transfer_profile_to_env {
1.788     albertel  548:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    549:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       550: 
1.720     albertel  551:     if (!defined($lonidsdir)) {
                    552: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    553:     }
                    554:     if (!defined($handle)) {
                    555:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    556:     }
                    557: 
1.786     albertel  558:     my $convert;
                    559:     {
1.917     albertel  560:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561: 	if (!$opened) {
1.915     albertel  562: 	    return;
                    563: 	}
1.786     albertel  564: 	flock($idf,LOCK_SH);
                    565: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 		&GDBM_READER(),0640)) {
                    567: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    568: 	    untie(%disk_env);
                    569: 	} else {
                    570: 	    $convert = 1;
                    571: 	}
                    572:     }
                    573:     if ($convert) {
                    574: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    575: 	    &logthis("Failed to load session, or convert session.");
                    576: 	}
1.374     www       577:     }
1.783     albertel  578: 
1.786     albertel  579:     my %remove;
1.783     albertel  580:     while ( my $envname = each(%env) ) {
1.433     matthew   581:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    582:             if ($time < time-300) {
1.783     albertel  583:                 $remove{$key}++;
1.433     matthew   584:             }
                    585:         }
                    586:     }
1.783     albertel  587: 
1.619     albertel  588:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  589:     $env_loaded=1;
1.783     albertel  590:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   591:         &delenv($expired_key);
1.374     www       592:     }
1.1       albertel  593: }
                    594: 
1.916     albertel  595: # ---------------------------------------------------- Check for valid session 
                    596: sub check_for_valid_session {
                    597:     my ($r) = @_;
                    598:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    599:     my $lonid=$cookies{'lonID'};
                    600:     return undef if (!$lonid);
                    601: 
                    602:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    603:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    604:     return undef if (!-e "$lonidsdir/$handle.id");
                    605: 
1.917     albertel  606:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    607:     return undef if (!$opened);
1.916     albertel  608: 
                    609:     flock($idf,LOCK_SH);
                    610:     my %disk_env;
                    611:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    612: 	    &GDBM_READER(),0640)) {
                    613: 	return undef;	
                    614:     }
                    615: 
                    616:     if (!defined($disk_env{'user.name'})
                    617: 	|| !defined($disk_env{'user.domain'})) {
                    618: 	return undef;
                    619:     }
                    620:     return $handle;
                    621: }
                    622: 
1.830     albertel  623: sub timed_flock {
                    624:     my ($file,$lock_type) = @_;
                    625:     my $failed=0;
                    626:     eval {
                    627: 	local $SIG{__DIE__}='DEFAULT';
                    628: 	local $SIG{ALRM}=sub {
                    629: 	    $failed=1;
                    630: 	    die("failed lock");
                    631: 	};
                    632: 	alarm(13);
                    633: 	flock($file,$lock_type);
                    634: 	alarm(0);
                    635:     };
                    636:     if ($failed) {
                    637: 	return undef;
                    638:     } else {
                    639: 	return 1;
                    640:     }
                    641: }
                    642: 
1.5       www       643: # ---------------------------------------------------------- Append Environment
                    644: 
                    645: sub appenv {
1.949     raeburn   646:     my ($newenv,$roles) = @_;
                    647:     if (ref($newenv) eq 'HASH') {
                    648:         foreach my $key (keys(%{$newenv})) {
                    649:             my $refused = 0;
                    650: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    651:                 $refused = 1;
                    652:                 if (ref($roles) eq 'ARRAY') {
                    653:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    654:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    655:                         $refused = 0;
                    656:                     }
                    657:                 }
                    658:             }
                    659:             if ($refused) {
                    660:                 &logthis("<font color=\"blue\">WARNING: ".
                    661:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    662:                          .'</font>');
                    663: 	        delete($newenv->{$key});
                    664:             } else {
                    665:                 $env{$key}=$newenv->{$key};
                    666:             }
                    667:         }
                    668:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    669:         if ($opened
                    670: 	    && &timed_flock($env_file,LOCK_EX)
                    671: 	    &&
                    672: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    673: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    674: 	    while (my ($key,$value) = each(%{$newenv})) {
                    675: 	        $disk_env{$key} = $value;
                    676: 	    }
                    677: 	    untie(%disk_env);
1.35      www       678:         }
1.191     harris41  679:     }
1.56      www       680:     return 'ok';
                    681: }
                    682: # ----------------------------------------------------- Delete from Environment
                    683: 
                    684: sub delenv {
1.1104    raeburn   685:     my ($delthis,$regexp,$roles) = @_;
                    686:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    687:         my $refused = 1;
                    688:         if (ref($roles) eq 'ARRAY') {
                    689:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    690:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    691:                 $refused = 0;
                    692:             }
                    693:         }
                    694:         if ($refused) {
                    695:             &logthis("<font color=\"blue\">WARNING: ".
                    696:                      "Attempt to delete from environment ".$delthis);
                    697:             return 'error';
                    698:         }
1.56      www       699:     }
1.917     albertel  700:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:     if ($opened
1.915     albertel  702: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  703: 	&&
                    704: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  706: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   707: 	    if ($regexp) {
                    708:                 if ($key=~/^$delthis/) {
                    709:                     delete($env{$key});
                    710:                     delete($disk_env{$key});
                    711:                 } 
                    712:             } else {
                    713:                 if ($key=~/^\Q$delthis\E/) {
                    714: 		    delete($env{$key});
                    715: 		    delete($disk_env{$key});
                    716: 	        }
                    717:             }
1.448     albertel  718: 	}
1.783     albertel  719: 	untie(%disk_env);
1.5       www       720:     }
                    721:     return 'ok';
1.369     albertel  722: }
                    723: 
1.790     albertel  724: sub get_env_multiple {
                    725:     my ($name) = @_;
                    726:     my @values;
                    727:     if (defined($env{$name})) {
                    728:         # exists is it an array
                    729:         if (ref($env{$name})) {
                    730:             @values=@{ $env{$name} };
                    731:         } else {
                    732:             $values[0]=$env{$name};
                    733:         }
                    734:     }
                    735:     return(@values);
                    736: }
                    737: 
1.958     www       738: # ------------------------------------------------------------------- Locking
                    739: 
                    740: sub set_lock {
                    741:     my ($text)=@_;
                    742:     $locknum++;
                    743:     my $id=$$.'-'.$locknum;
                    744:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    745:              'session.lock.'.$id => $text});
                    746:     return $id;
                    747: }
                    748: 
                    749: sub get_locks {
                    750:     my $num=0;
                    751:     my %texts=();
                    752:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    753:        if ($lock=~/\w/) {
                    754:           $num++;
                    755:           $texts{$lock}=$env{'session.lock.'.$lock};
                    756:        }
                    757:    }
                    758:    return ($num,%texts);
                    759: }
                    760: 
                    761: sub remove_lock {
                    762:     my ($id)=@_;
                    763:     my $newlocks='';
                    764:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    765:        if (($lock=~/\w/) && ($lock ne $id)) {
                    766:           $newlocks.=','.$lock;
                    767:        }
                    768:     }
                    769:     &appenv({'session.locks' => $newlocks});
                    770:     &delenv('session.lock.'.$id);
                    771: }
                    772: 
                    773: sub remove_all_locks {
                    774:     my $activelocks=$env{'session.locks'};
                    775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    776:        if ($lock=~/\w/) {
                    777:           &remove_lock($lock);
                    778:        }
                    779:     }
                    780: }
                    781: 
                    782: 
1.369     albertel  783: # ------------------------------------------ Find out current server userload
                    784: sub userload {
                    785:     my $numusers=0;
                    786:     {
                    787: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    788: 	my $filename;
                    789: 	my $curtime=time;
                    790: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  791: 	    next if ($filename eq '.' || $filename eq '..');
                    792: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  793: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  794: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  795: 	}
                    796: 	closedir(LONIDS);
                    797:     }
                    798:     my $userloadpercent=0;
                    799:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    800:     if ($maxuserload) {
1.371     albertel  801: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  802:     }
1.372     albertel  803:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  804:     return $userloadpercent;
1.283     www       805: }
                    806: 
1.1       albertel  807: # ------------------------------ Find server with least workload from spare.tab
1.11      www       808: 
1.1       albertel  809: sub spareserver {
1.1083    raeburn   810:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  811:     my $spare_server;
1.370     albertel  812:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  813:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    814:                                                      :  $userloadpercent;
1.1083    raeburn   815:     my ($uint_dom,$remotesessions);
                    816:     if (($udom ne '') && (&domain($udom) ne '')) {
                    817:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    818:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    819:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    820:         $remotesessions = $udomdefaults{'remotesessions'};
                    821:     }
1.1123    raeburn   822:     my $spareshash = &this_host_spares($udom);
                    823:     if (ref($spareshash) eq 'HASH') {
                    824:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    825:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    826:                 if ($uint_dom) {
                    827:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    828:                                                  $try_server));
                    829:                 }
                    830: 	        ($spare_server, $lowest_load) =
                    831: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    832:             }
1.1083    raeburn   833:         }
1.784     albertel  834: 
1.1123    raeburn   835:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    836: 
                    837:         if (!$found_server) {
                    838:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    839: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    840:                     if ($uint_dom) {
                    841:                         next unless (&spare_can_host($udom,$uint_dom,
                    842:                                                      $remotesessions,$try_server));
                    843:                     }
                    844: 	            ($spare_server, $lowest_load) =
                    845: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    846:                 }
                    847: 	    }
                    848:         }
1.784     albertel  849:     }
                    850: 
                    851:     if (!$want_server_name) {
1.968     raeburn   852:         my $protocol = 'http';
                    853:         if ($protocol{$spare_server} eq 'https') {
                    854:             $protocol = $protocol{$spare_server};
                    855:         }
1.1001    raeburn   856:         if (defined($spare_server)) {
                    857:             my $hostname = &hostname($spare_server);
1.1083    raeburn   858:             if (defined($hostname)) {
1.1001    raeburn   859: 	        $spare_server = $protocol.'://'.$hostname;
                    860:             }
                    861:         }
1.784     albertel  862:     }
                    863:     return $spare_server;
                    864: }
                    865: 
                    866: sub compare_server_load {
                    867:     my ($try_server, $spare_server, $lowest_load) = @_;
                    868: 
                    869:     my $loadans     = &reply('load',    $try_server);
                    870:     my $userloadans = &reply('userload',$try_server);
                    871: 
                    872:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   873: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  874:     }
                    875: 
                    876:     my $load;
                    877:     if ($loadans =~ /\d/) {
                    878: 	if ($userloadans =~ /\d/) {
                    879: 	    #both are numbers, pick the bigger one
                    880: 	    $load = ($loadans > $userloadans) ? $loadans 
                    881: 		                              : $userloadans;
1.411     albertel  882: 	} else {
1.784     albertel  883: 	    $load = $loadans;
1.411     albertel  884: 	}
1.784     albertel  885:     } else {
                    886: 	$load = $userloadans;
                    887:     }
                    888: 
                    889:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    890: 	$spare_server = $try_server;
                    891: 	$lowest_load  = $load;
1.370     albertel  892:     }
1.784     albertel  893:     return ($spare_server,$lowest_load);
1.202     matthew   894: }
1.914     albertel  895: 
                    896: # --------------------------- ask offload servers if user already has a session
                    897: sub find_existing_session {
                    898:     my ($udom,$uname) = @_;
1.1123    raeburn   899:     my $spareshash = &this_host_spares($udom);
                    900:     if (ref($spareshash) eq 'HASH') {
                    901:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    902:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    903:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    904:             }
                    905:         }
                    906:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    907:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    908:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    909:             }
                    910:         }
1.914     albertel  911:     }
                    912:     return;
                    913: }
                    914: 
                    915: # -------------------------------- ask if server already has a session for user
                    916: sub has_user_session {
                    917:     my ($lonid,$udom,$uname) = @_;
                    918:     my $result = &reply(join(':','userhassession',
                    919: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    920:     return 1 if ($result eq 'ok');
                    921: 
                    922:     return 0;
                    923: }
                    924: 
1.1076    raeburn   925: # --------- determine least loaded server in a user's domain which allows login
                    926: 
                    927: sub choose_server {
1.1115    raeburn   928:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   929:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   930:     my %servers = &get_servers($udom);
1.1076    raeburn   931:     my $lowest_load = 30000;
1.1116    raeburn   932:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   933:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   934:         my $loginvia;
                    935:         if ($checkloginvia) {
                    936:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   937:             if ($loginvia) {
                    938:                 my ($server,$path) = split(/:/,$loginvia);
                    939:                 ($login_host, $lowest_load) =
                    940:                     &compare_server_load($server, $login_host, $lowest_load);
                    941:                 if ($login_host eq $server) {
                    942:                     $portal_path = $path;
                    943:                 }
                    944:             } else {
                    945:                 ($login_host, $lowest_load) =
                    946:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    947:                 if ($login_host eq $lonhost) {
                    948:                     $portal_path = '';
                    949:                 }
                    950:             }
                    951:         } else {
1.1076    raeburn   952:             ($login_host, $lowest_load) =
1.1116    raeburn   953:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   954:         }
                    955:     }
                    956:     if ($login_host ne '') {
1.1116    raeburn   957:         $hostname = &hostname($login_host);
1.1076    raeburn   958:     }
1.1116    raeburn   959:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   960: }
                    961: 
1.202     matthew   962: # --------------------------------------------- Try to change a user's password
                    963: 
                    964: sub changepass {
1.799     raeburn   965:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   966:     $currentpass = &escape($currentpass);
                    967:     $newpass     = &escape($newpass);
1.1030    raeburn   968:     my $lonhost = $perlvar{'lonHostID'};
                    969:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   970: 		       $server);
                    971:     if (! $answer) {
                    972: 	&logthis("No reply on password change request to $server ".
                    973: 		 "by $uname in domain $udom.");
                    974:     } elsif ($answer =~ "^ok") {
                    975:         &logthis("$uname in $udom successfully changed their password ".
                    976: 		 "on $server.");
                    977:     } elsif ($answer =~ "^pwchange_failure") {
                    978: 	&logthis("$uname in $udom was unable to change their password ".
                    979: 		 "on $server.  The action was blocked by either lcpasswd ".
                    980: 		 "or pwchange");
                    981:     } elsif ($answer =~ "^non_authorized") {
                    982:         &logthis("$uname in $udom did not get their password correct when ".
                    983: 		 "attempting to change it on $server.");
                    984:     } elsif ($answer =~ "^auth_mode_error") {
                    985:         &logthis("$uname in $udom attempted to change their password despite ".
                    986: 		 "not being locally or internally authenticated on $server.");
                    987:     } elsif ($answer =~ "^unknown_user") {
                    988:         &logthis("$uname in $udom attempted to change their password ".
                    989: 		 "on $server but were unable to because $server is not ".
                    990: 		 "their home server.");
                    991:     } elsif ($answer =~ "^refused") {
                    992: 	&logthis("$server refused to change $uname in $udom password because ".
                    993: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   994:     } elsif ($answer =~ "invalid_client") {
                    995:         &logthis("$server refused to change $uname in $udom password because ".
                    996:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   997:     }
                    998:     return $answer;
1.1       albertel  999: }
                   1000: 
1.169     harris41 1001: # ----------------------- Try to determine user's current authentication scheme
                   1002: 
                   1003: sub queryauthenticate {
                   1004:     my ($uname,$udom)=@_;
1.456     albertel 1005:     my $uhome=&homeserver($uname,$udom);
                   1006:     if (!$uhome) {
                   1007: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1008: 	return 'no_host';
                   1009:     }
                   1010:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1011:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1012: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1013:     }
1.456     albertel 1014:     return $answer;
1.169     harris41 1015: }
                   1016: 
1.1       albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1018: 
1.1       albertel 1019: sub authenticate {
1.1073    raeburn  1020:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1021:     $upass=&escape($upass);
                   1022:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1023:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1024:     my $newhome;
1.836     www      1025:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1026: # Maybe the machine was offline and only re-appeared again recently?
                   1027:         &reconlonc();
                   1028: # One more
1.952     raeburn  1029: 	$uhome=&homeserver($uname,$udom,1);
                   1030:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1031:             if (defined(&domain($udom,'primary'))) {
                   1032:                 $newhome=&domain($udom,'primary');
                   1033:             }
                   1034:             if ($newhome ne '') {
                   1035:                 $uhome = $newhome;
                   1036:             }
                   1037:         }
1.836     www      1038: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1039: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1040: 	    return 'no_host';
                   1041:         }
1.1       albertel 1042:     }
1.1073    raeburn  1043:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1044:     if ($answer eq 'authorized') {
1.952     raeburn  1045:         if ($newhome) {
                   1046:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1047:             return 'no_account_on_host'; 
                   1048:         } else {
                   1049:             &logthis("User $uname at $udom authorized by $uhome");
                   1050:             return $uhome;
                   1051:         }
1.471     albertel 1052:     }
                   1053:     if ($answer eq 'non_authorized') {
                   1054: 	&logthis("User $uname at $udom rejected by $uhome");
                   1055: 	return 'no_host'; 
1.9       www      1056:     }
1.471     albertel 1057:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1058:     return 'no_host';
                   1059: }
                   1060: 
1.1073    raeburn  1061: sub can_host_session {
1.1074    raeburn  1062:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1063:     my $canhost = 1;
1.1074    raeburn  1064:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1065:     if (ref($remotesessions) eq 'HASH') {
                   1066:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1067:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1068:                 $canhost = 0;
                   1069:             } else {
                   1070:                 $canhost = 1;
                   1071:             }
                   1072:         }
                   1073:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1074:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1075:                 $canhost = 1;
                   1076:             } else {
                   1077:                 $canhost = 0;
                   1078:             }
                   1079:         }
                   1080:         if ($canhost) {
                   1081:             if ($remotesessions->{'version'} ne '') {
                   1082:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1083:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1084:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1085:                         my $major = $1;
                   1086:                         my $minor = $2;
                   1087:                         if (($major < $reqmajor ) ||
                   1088:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1089:                             $canhost = 0;
                   1090:                         }
                   1091:                     } else {
                   1092:                         $canhost = 0;
                   1093:                     }
                   1094:                 }
                   1095:             }
                   1096:         }
                   1097:     }
                   1098:     if ($canhost) {
                   1099:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1100:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1101:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1102:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1103:                 if (($uint_dom ne '') && 
                   1104:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1105:                     $canhost = 0;
                   1106:                 } else {
                   1107:                     $canhost = 1;
                   1108:                 }
                   1109:             }
                   1110:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1111:                 if (($uint_dom ne '') && 
                   1112:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1113:                     $canhost = 1;
                   1114:                 } else {
                   1115:                     $canhost = 0;
                   1116:                 }
                   1117:             }
                   1118:         }
                   1119:     }
                   1120:     return $canhost;
                   1121: }
                   1122: 
1.1083    raeburn  1123: sub spare_can_host {
                   1124:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1125:     my $canhost=1;
                   1126:     my @intdoms;
                   1127:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1128:     if (ref($internet_names) eq 'ARRAY') {
                   1129:         @intdoms = @{$internet_names};
                   1130:     }
                   1131:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1132:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1133:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1134:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1135:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1136:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1137:                                      $remotesessions,
                   1138:                                      $defdomdefaults{'hostedsessions'});
                   1139:     }
                   1140:     return $canhost;
                   1141: }
                   1142: 
1.1123    raeburn  1143: sub this_host_spares {
                   1144:     my ($dom) = @_;
1.1126    raeburn  1145:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1146:     my @hosts = &current_machine_ids();
                   1147:     foreach my $lonhost (@hosts) {
                   1148:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1149:             $dom_in_use = $dom;
                   1150:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1151:             last;
                   1152:         }
                   1153:     }
1.1126    raeburn  1154:     if ($dom_in_use ne '') {
                   1155:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1156:     }
                   1157:     if (ref($result) ne 'HASH') {
                   1158:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1159:         $dom_in_use = &host_domain($lonhost_in_use);
                   1160:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1161:         if (ref($result) ne 'HASH') {
                   1162:             $result = \%spareid;
                   1163:         }
                   1164:     }
                   1165:     return $result;
                   1166: }
                   1167: 
                   1168: sub spares_for_offload  {
                   1169:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1170:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1171:     if (defined($cached)) {
                   1172:         return $result;
                   1173:     } else {
1.1126    raeburn  1174:         my $cachetime = 60*60*24;
                   1175:         my %domconfig =
                   1176:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1177:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1178:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1179:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1180:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1181:                 }
                   1182:             }
                   1183:         }
                   1184:     }
1.1126    raeburn  1185:     return;
1.1123    raeburn  1186: }
                   1187: 
1.1129    raeburn  1188: sub get_lonbalancer_config {
                   1189:     my ($servers) = @_;
                   1190:     my ($currbalancer,$currtargets);
                   1191:     if (ref($servers) eq 'HASH') {
                   1192:         foreach my $server (keys(%{$servers})) {
                   1193:             my %what = (
                   1194:                          spareid => 1,
                   1195:                          perlvar => 1,
                   1196:                        );
                   1197:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1198:             if ($result eq 'ok') {
                   1199:                 if (ref($returnhash) eq 'HASH') {
                   1200:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1201:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1202:                             $currbalancer = $server;
                   1203:                             $currtargets = {};
                   1204:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1205:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1206:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1207:                                 }
                   1208:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1209:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1210:                                 }
                   1211:                             }
                   1212:                             last;
                   1213:                         }
                   1214:                     }
                   1215:                 }
                   1216:             }
                   1217:         }
                   1218:     }
                   1219:     return ($currbalancer,$currtargets);
                   1220: }
                   1221: 
                   1222: sub check_loadbalancing {
                   1223:     my ($uname,$udom) = @_;
                   1224:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1225:         $offloadto,$otherserver);
                   1226:     my $lonhost = $perlvar{'lonHostID'};
                   1227:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1228:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1229:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1230:     my $serverhomedom = &host_domain($lonhost);
                   1231: 
                   1232:     my $cachetime = 60*60*24;
                   1233: 
                   1234:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1235:         $dom_in_use = $udom;
                   1236:         $homeintdom = 1;
                   1237:     } else {
                   1238:         $dom_in_use = $serverhomedom;
                   1239:     }
                   1240:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1241:     unless (defined($cached)) {
                   1242:         my %domconfig =
                   1243:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1244:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1245:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1246:         }
                   1247:     }
                   1248:     if (ref($result) eq 'HASH') {
                   1249:         my $currbalancer = $result->{'lonhost'};
                   1250:         my $currtargets = $result->{'targets'};
                   1251:         my $currrules = $result->{'rules'};
                   1252:         if ($currbalancer ne '') {
                   1253:             my @hosts = &current_machine_ids();
                   1254:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1255:                 $is_balancer = 1;
                   1256:             }
                   1257:         }
                   1258:         if ($is_balancer) {
                   1259:             if (ref($currrules) eq 'HASH') {
                   1260:                 if ($homeintdom) {
                   1261:                     if ($uname ne '') {
                   1262:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1263:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1264:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1265:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1266:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1267:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1268:                             }
                   1269:                         }
                   1270:                         if ($rule_in_effect eq '') {
                   1271:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1272:                             if ($userenv{'inststatus'} ne '') {
                   1273:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1274:                                 my ($othertitle,$usertypes,$types) =
                   1275:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1276:                                 if (ref($types) eq 'ARRAY') {
                   1277:                                     foreach my $type (@{$types}) {
                   1278:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1279:                                             if (exists($currrules->{$type})) {
                   1280:                                                 $rule_in_effect = $currrules->{$type};
                   1281:                                             }
                   1282:                                         }
                   1283:                                     }
                   1284:                                 }
                   1285:                             } else {
                   1286:                                 if (exists($currrules->{'default'})) {
                   1287:                                     $rule_in_effect = $currrules->{'default'};
                   1288:                                 }
                   1289:                             }
                   1290:                         }
                   1291:                     } else {
                   1292:                         if (exists($currrules->{'default'})) {
                   1293:                             $rule_in_effect = $currrules->{'default'};
                   1294:                         }
                   1295:                     }
                   1296:                 } else {
                   1297:                     if ($currrules->{'_LC_external'} ne '') {
                   1298:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1299:                     }
                   1300:                 }
                   1301:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1302:                                                        $uname,$udom);
                   1303:             }
                   1304:         }
                   1305:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1306:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1307:         unless (defined($cached)) {
                   1308:             my %domconfig =
                   1309:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1310:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1311:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1312:             }
                   1313:         }
                   1314:         if (ref($result) eq 'HASH') {
                   1315:             my $currbalancer = $result->{'lonhost'};
                   1316:             my $currtargets = $result->{'targets'};
                   1317:             my $currrules = $result->{'rules'};
                   1318: 
                   1319:             if ($currbalancer eq $lonhost) {
                   1320:                 $is_balancer = 1;
                   1321:                 if (ref($currrules) eq 'HASH') {
                   1322:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1323:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1324:                     }
                   1325:                 }
                   1326:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1327:                                                        $uname,$udom);
                   1328:             }
                   1329:         } else {
                   1330:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1331:                 $is_balancer = 1;
                   1332:                 $offloadto = &this_host_spares($dom_in_use);
                   1333:             }
                   1334:         }
                   1335:     } else {
                   1336:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1337:             $is_balancer = 1;
                   1338:             $offloadto = &this_host_spares($dom_in_use);
                   1339:         }
                   1340:     }
                   1341:     my $lowest_load = 30000;
                   1342:     if (ref($offloadto) eq 'HASH') {
                   1343:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1344:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1345:                 ($otherserver,$lowest_load) =
                   1346:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1347:             }
                   1348:         }
                   1349:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1350: 
                   1351:         if (!$found_server) {
                   1352:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1353:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1354:                     ($otherserver,$lowest_load) =
                   1355:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1356:                 }
                   1357:             }
                   1358:         }
                   1359:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1360:         if (@{$offloadto} == 1) {
                   1361:             $otherserver = $offloadto->[0];
                   1362:         } elsif (@{$offloadto} > 1) {
                   1363:             foreach my $try_server (@{$offloadto}) {
                   1364:                 ($otherserver,$lowest_load) =
                   1365:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1366:             }
                   1367:         }
                   1368:     }
                   1369:     return ($is_balancer,$otherserver);
                   1370: }
                   1371: 
                   1372: sub get_loadbalancer_targets {
                   1373:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1374:     my $offloadto;
                   1375:     if ($rule_in_effect eq '') {
                   1376:         $offloadto = $currtargets;
                   1377:     } else {
                   1378:         if ($rule_in_effect eq 'homeserver') {
                   1379:             my $homeserver = &homeserver($uname,$udom);
                   1380:             if ($homeserver ne 'no_host') {
                   1381:                 $offloadto = [$homeserver];
                   1382:             }
                   1383:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1384:             my %domconfig =
                   1385:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1386:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1387:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1388:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1389:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1390:                     }
                   1391:                 }
                   1392:             } else {
                   1393:                 my %servers = &dom_servers($udom);
                   1394:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1395:                 if (&hostname($remotebalancer) ne '') {
                   1396:                     $offloadto = [$remotebalancer];
                   1397:                 }
                   1398:             }
                   1399:         } elsif (&hostname($rule_in_effect) ne '') {
                   1400:             $offloadto = [$rule_in_effect];
                   1401:         }
                   1402:     }
                   1403:     return $offloadto;
                   1404: }
                   1405: 
1.1127    raeburn  1406: sub internet_dom_servers {
                   1407:     my ($dom) = @_;
                   1408:     my (%uniqservers,%servers);
                   1409:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1410:     my @machinedoms = &machine_domains($primaryserver);
                   1411:     foreach my $mdom (@machinedoms) {
                   1412:         my %currservers = %servers;
                   1413:         my %server = &get_servers($mdom);
                   1414:         %servers = (%currservers,%server);
                   1415:     }
                   1416:     my %by_hostname;
                   1417:     foreach my $id (keys(%servers)) {
                   1418:         push(@{$by_hostname{$servers{$id}}},$id);
                   1419:     }
                   1420:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1421:         if (@{$by_hostname{$hostname}} > 1) {
                   1422:             my $match = 0;
                   1423:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1424:                 if (&host_domain($id) eq $dom) {
                   1425:                     $uniqservers{$id} = $hostname;
                   1426:                     $match = 1;
                   1427:                 }
                   1428:             }
                   1429:             unless ($match) {
                   1430:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1431:             }
                   1432:         } else {
                   1433:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1434:         }
                   1435:     }
                   1436:     return %uniqservers;
                   1437: }
                   1438: 
1.1       albertel 1439: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1440: 
1.599     albertel 1441: my %homecache;
1.1       albertel 1442: sub homeserver {
1.230     stredwic 1443:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1444:     my $index="$uname:$udom";
1.426     albertel 1445: 
1.599     albertel 1446:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1447: 
                   1448:     my %servers = &get_servers($udom,'library');
                   1449:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1450:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1451: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1452: 
                   1453: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1454: 	if ($answer eq 'found') {
                   1455: 	    delete($badServerCache{$tryserver}); 
                   1456: 	    return $homecache{$index}=$tryserver;
                   1457: 	} elsif ($answer eq 'no_host') {
                   1458: 	    $badServerCache{$tryserver}=1;
                   1459: 	}
1.1       albertel 1460:     }    
                   1461:     return 'no_host';
1.70      www      1462: }
                   1463: 
                   1464: # ------------------------------------- Find the usernames behind a list of IDs
                   1465: 
                   1466: sub idget {
                   1467:     my ($udom,@ids)=@_;
                   1468:     my %returnhash=();
                   1469:     
1.841     albertel 1470:     my %servers = &get_servers($udom,'library');
                   1471:     foreach my $tryserver (keys(%servers)) {
                   1472: 	my $idlist=join('&',@ids);
                   1473: 	$idlist=~tr/A-Z/a-z/; 
                   1474: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1475: 	my @answer=();
                   1476: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1477: 	    @answer=split(/\&/,$reply);
                   1478: 	}                    ;
                   1479: 	my $i;
                   1480: 	for ($i=0;$i<=$#ids;$i++) {
                   1481: 	    if ($answer[$i]) {
                   1482: 		$returnhash{$ids[$i]}=$answer[$i];
                   1483: 	    } 
                   1484: 	}
                   1485:     } 
1.70      www      1486:     return %returnhash;
                   1487: }
                   1488: 
                   1489: # ------------------------------------- Find the IDs behind a list of usernames
                   1490: 
                   1491: sub idrget {
                   1492:     my ($udom,@unames)=@_;
                   1493:     my %returnhash=();
1.800     albertel 1494:     foreach my $uname (@unames) {
                   1495:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1496:     }
1.70      www      1497:     return %returnhash;
                   1498: }
                   1499: 
                   1500: # ------------------------------- Store away a list of names and associated IDs
                   1501: 
                   1502: sub idput {
                   1503:     my ($udom,%ids)=@_;
                   1504:     my %servers=();
1.800     albertel 1505:     foreach my $uname (keys(%ids)) {
                   1506: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1507:         my $uhom=&homeserver($uname,$udom);
1.70      www      1508:         if ($uhom ne 'no_host') {
1.800     albertel 1509:             my $id=&escape($ids{$uname});
1.70      www      1510:             $id=~tr/A-Z/a-z/;
1.800     albertel 1511:             my $esc_unam=&escape($uname);
1.70      www      1512: 	    if ($servers{$uhom}) {
1.800     albertel 1513: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1514:             } else {
1.800     albertel 1515:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1516:             }
                   1517:         }
1.191     harris41 1518:     }
1.800     albertel 1519:     foreach my $server (keys(%servers)) {
                   1520:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1521:     }
1.344     www      1522: }
                   1523: 
1.1023    raeburn  1524: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1525: sub dump_dom {
1.1023    raeburn  1526:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1527:     if (!$udom) {
                   1528:         $udom=$env{'user.domain'};
                   1529:     }
                   1530:     my %returnhash;
1.1023    raeburn  1531:     if ($udom) {
                   1532:         my $uname = &get_domainconfiguser($udom);
                   1533:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1534:     }
                   1535:     return %returnhash;
                   1536: }
                   1537: 
1.1023    raeburn  1538: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1539: 
                   1540: sub get_dom {
1.860     raeburn  1541:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1542:     my $items='';
                   1543:     foreach my $item (@$storearr) {
                   1544:         $items.=&escape($item).'&';
                   1545:     }
                   1546:     $items=~s/\&$//;
1.860     raeburn  1547:     if (!$udom) {
                   1548:         $udom=$env{'user.domain'};
                   1549:         if (defined(&domain($udom,'primary'))) {
                   1550:             $uhome=&domain($udom,'primary');
                   1551:         } else {
1.874     albertel 1552:             undef($uhome);
1.860     raeburn  1553:         }
                   1554:     } else {
                   1555:         if (!$uhome) {
                   1556:             if (defined(&domain($udom,'primary'))) {
                   1557:                 $uhome=&domain($udom,'primary');
                   1558:             }
                   1559:         }
                   1560:     }
                   1561:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1562:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1563:         my %returnhash;
1.875     albertel 1564:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1565:             return %returnhash;
                   1566:         }
1.806     raeburn  1567:         my @pairs=split(/\&/,$rep);
                   1568:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1569:             return @pairs;
                   1570:         }
                   1571:         my $i=0;
                   1572:         foreach my $item (@$storearr) {
                   1573:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1574:             $i++;
                   1575:         }
                   1576:         return %returnhash;
                   1577:     } else {
1.880     banghart 1578:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1579:     }
                   1580: }
                   1581: 
                   1582: # -------------------------------------------- put items in domain db files 
                   1583: 
                   1584: sub put_dom {
1.860     raeburn  1585:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1586:     if (!$udom) {
                   1587:         $udom=$env{'user.domain'};
                   1588:         if (defined(&domain($udom,'primary'))) {
                   1589:             $uhome=&domain($udom,'primary');
                   1590:         } else {
1.874     albertel 1591:             undef($uhome);
1.860     raeburn  1592:         }
                   1593:     } else {
                   1594:         if (!$uhome) {
                   1595:             if (defined(&domain($udom,'primary'))) {
                   1596:                 $uhome=&domain($udom,'primary');
                   1597:             }
                   1598:         }
                   1599:     } 
                   1600:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1601:         my $items='';
                   1602:         foreach my $item (keys(%$storehash)) {
                   1603:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1604:         }
                   1605:         $items=~s/\&$//;
                   1606:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1607:     } else {
1.860     raeburn  1608:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1609:     }
                   1610: }
                   1611: 
1.1023    raeburn  1612: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1613: sub newput_dom {
1.1023    raeburn  1614:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1615:     my $result;
                   1616:     if (!$udom) {
                   1617:         $udom=$env{'user.domain'};
                   1618:     }
1.1023    raeburn  1619:     if ($udom) {
                   1620:         my $uname = &get_domainconfiguser($udom);
                   1621:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1622:     }
                   1623:     return $result;
                   1624: }
                   1625: 
1.1023    raeburn  1626: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1627: sub del_dom {
1.1023    raeburn  1628:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1629:     if (ref($storearr) eq 'ARRAY') {
                   1630:         if (!$udom) {
                   1631:             $udom=$env{'user.domain'};
                   1632:         }
1.1023    raeburn  1633:         if ($udom) {
                   1634:             my $uname = &get_domainconfiguser($udom); 
                   1635:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1636:         }
                   1637:     }
                   1638: }
                   1639: 
1.1023    raeburn  1640: # ----------------------------------construct domainconfig user for a domain 
                   1641: sub get_domainconfiguser {
                   1642:     my ($udom) = @_;
                   1643:     return $udom.'-domainconfig';
                   1644: }
                   1645: 
1.837     raeburn  1646: sub retrieve_inst_usertypes {
                   1647:     my ($udom) = @_;
                   1648:     my (%returnhash,@order);
1.989     raeburn  1649:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1650:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1651:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1652:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1653:         @order = @{$domdefs{'inststatusorder'}};
                   1654:     } else {
                   1655:         if (defined(&domain($udom,'primary'))) {
                   1656:             my $uhome=&domain($udom,'primary');
                   1657:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1658:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1659:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1660:                 return (\%returnhash,\@order);
                   1661:             }
                   1662:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1663:             my @pairs=split(/\&/,$hashitems);
                   1664:             foreach my $item (@pairs) {
                   1665:                 my ($key,$value)=split(/=/,$item,2);
                   1666:                 $key = &unescape($key);
                   1667:                 next if ($key =~ /^error: 2 /);
                   1668:                 $returnhash{$key}=&thaw_unescape($value);
                   1669:             }
                   1670:             my @esc_order = split(/\&/,$orderitems);
                   1671:             foreach my $item (@esc_order) {
                   1672:                 push(@order,&unescape($item));
                   1673:             }
                   1674:         } else {
                   1675:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1676:         }
                   1677:     }
                   1678:     return (\%returnhash,\@order);
                   1679: }
                   1680: 
1.868     raeburn  1681: sub is_domainimage {
                   1682:     my ($url) = @_;
                   1683:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1684:         if (&domain($1) ne '') {
                   1685:             return '1';
                   1686:         }
                   1687:     }
                   1688:     return;
                   1689: }
                   1690: 
1.899     raeburn  1691: sub inst_directory_query {
                   1692:     my ($srch) = @_;
                   1693:     my $udom = $srch->{'srchdomain'};
                   1694:     my %results;
                   1695:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1696:     my $outcome;
1.899     raeburn  1697:     if ($homeserver ne '') {
1.904     albertel 1698: 	my $queryid=&reply("querysend:instdirsearch:".
                   1699: 			   &escape($srch->{'srchby'}).':'.
                   1700: 			   &escape($srch->{'srchterm'}).':'.
                   1701: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1702: 	my $host=&hostname($homeserver);
                   1703: 	if ($queryid !~/^\Q$host\E\_/) {
                   1704: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1705: 	    return;
                   1706: 	}
                   1707: 	my $response = &get_query_reply($queryid);
                   1708: 	my $maxtries = 5;
                   1709: 	my $tries = 1;
                   1710: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1711: 	    $response = &get_query_reply($queryid);
                   1712: 	    $tries ++;
                   1713: 	}
                   1714: 
                   1715:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1716:             if ($response eq 'unavailable') {
                   1717:                 $outcome = $response;
                   1718:             } else {
                   1719:                 $outcome = 'ok';
                   1720:                 my @matches = split(/\n/,$response);
                   1721:                 foreach my $match (@matches) {
                   1722:                     my ($key,$value) = split(/=/,$match);
                   1723:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1724:                 }
1.899     raeburn  1725:             }
                   1726:         }
                   1727:     }
1.909     raeburn  1728:     return ($outcome,%results);
1.899     raeburn  1729: }
                   1730: 
                   1731: sub usersearch {
                   1732:     my ($srch) = @_;
                   1733:     my $dom = $srch->{'srchdomain'};
                   1734:     my %results;
                   1735:     my %libserv = &all_library();
                   1736:     my $query = 'usersearch';
                   1737:     foreach my $tryserver (keys(%libserv)) {
                   1738:         if (&host_domain($tryserver) eq $dom) {
                   1739:             my $host=&hostname($tryserver);
                   1740:             my $queryid=
1.911     raeburn  1741:                 &reply("querysend:".&escape($query).':'.
                   1742:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1743:                        &escape($srch->{'srchtype'}).':'.
                   1744:                        &escape($srch->{'srchterm'}),$tryserver);
                   1745:             if ($queryid !~/^\Q$host\E\_/) {
                   1746:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1747:                 next;
1.899     raeburn  1748:             }
                   1749:             my $reply = &get_query_reply($queryid);
                   1750:             my $maxtries = 1;
                   1751:             my $tries = 1;
                   1752:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1753:                 $reply = &get_query_reply($queryid);
                   1754:                 $tries ++;
                   1755:             }
                   1756:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1757:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1758:             } else {
1.911     raeburn  1759:                 my @matches;
                   1760:                 if ($reply =~ /\n/) {
                   1761:                     @matches = split(/\n/,$reply);
                   1762:                 } else {
                   1763:                     @matches = split(/\&/,$reply);
                   1764:                 }
1.899     raeburn  1765:                 foreach my $match (@matches) {
                   1766:                     my ($uname,$udom,%userhash);
1.911     raeburn  1767:                     foreach my $entry (split(/:/,$match)) {
                   1768:                         my ($key,$value) =
                   1769:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1770:                         $userhash{$key} = $value;
                   1771:                         if ($key eq 'username') {
                   1772:                             $uname = $value;
                   1773:                         } elsif ($key eq 'domain') {
                   1774:                             $udom = $value;
1.911     raeburn  1775:                         }
1.899     raeburn  1776:                     }
                   1777:                     $results{$uname.':'.$udom} = \%userhash;
                   1778:                 }
                   1779:             }
                   1780:         }
                   1781:     }
                   1782:     return %results;
                   1783: }
                   1784: 
1.912     raeburn  1785: sub get_instuser {
                   1786:     my ($udom,$uname,$id) = @_;
                   1787:     my $homeserver = &domain($udom,'primary');
                   1788:     my ($outcome,%results);
                   1789:     if ($homeserver ne '') {
                   1790:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1791:                            &escape($id).':'.&escape($udom),$homeserver);
                   1792:         my $host=&hostname($homeserver);
                   1793:         if ($queryid !~/^\Q$host\E\_/) {
                   1794:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1795:             return;
                   1796:         }
                   1797:         my $response = &get_query_reply($queryid);
                   1798:         my $maxtries = 5;
                   1799:         my $tries = 1;
                   1800:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1801:             $response = &get_query_reply($queryid);
                   1802:             $tries ++;
                   1803:         }
                   1804:         if (!&error($response) && $response ne 'refused') {
                   1805:             if ($response eq 'unavailable') {
                   1806:                 $outcome = $response;
                   1807:             } else {
                   1808:                 $outcome = 'ok';
                   1809:                 my @matches = split(/\n/,$response);
                   1810:                 foreach my $match (@matches) {
                   1811:                     my ($key,$value) = split(/=/,$match);
                   1812:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1813:                 }
                   1814:             }
                   1815:         }
                   1816:     }
                   1817:     my %userinfo;
                   1818:     if (ref($results{$uname}) eq 'HASH') {
                   1819:         %userinfo = %{$results{$uname}};
                   1820:     } 
                   1821:     return ($outcome,%userinfo);
                   1822: }
                   1823: 
                   1824: sub inst_rulecheck {
1.923     raeburn  1825:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1826:     my %returnhash;
                   1827:     if ($udom ne '') {
                   1828:         if (ref($rules) eq 'ARRAY') {
                   1829:             @{$rules} = map {&escape($_);} (@{$rules});
                   1830:             my $rulestr = join(':',@{$rules});
                   1831:             my $homeserver=&domain($udom,'primary');
                   1832:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1833:                 my $response;
                   1834:                 if ($item eq 'username') {                
                   1835:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1836:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1837:                                               $homeserver));
1.923     raeburn  1838:                 } elsif ($item eq 'id') {
                   1839:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1840:                                               ':'.&escape($id).':'.$rulestr,
                   1841:                                               $homeserver));
1.945     raeburn  1842:                 } elsif ($item eq 'selfcreate') {
                   1843:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1844:                                                &escape($udom).':'.&escape($uname).
                   1845:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1846:                 }
1.912     raeburn  1847:                 if ($response ne 'refused') {
                   1848:                     my @pairs=split(/\&/,$response);
                   1849:                     foreach my $item (@pairs) {
                   1850:                         my ($key,$value)=split(/=/,$item,2);
                   1851:                         $key = &unescape($key);
                   1852:                         next if ($key =~ /^error: 2 /);
                   1853:                         $returnhash{$key}=&thaw_unescape($value);
                   1854:                     }
                   1855:                 }
                   1856:             }
                   1857:         }
                   1858:     }
                   1859:     return %returnhash;
                   1860: }
                   1861: 
                   1862: sub inst_userrules {
1.923     raeburn  1863:     my ($udom,$check) = @_;
1.912     raeburn  1864:     my (%ruleshash,@ruleorder);
                   1865:     if ($udom ne '') {
                   1866:         my $homeserver=&domain($udom,'primary');
                   1867:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1868:             my $response;
                   1869:             if ($check eq 'id') {
                   1870:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1871:                                  $homeserver);
1.943     raeburn  1872:             } elsif ($check eq 'email') {
                   1873:                 $response=&reply('instemailrules:'.&escape($udom),
                   1874:                                  $homeserver);
1.923     raeburn  1875:             } else {
                   1876:                 $response=&reply('instuserrules:'.&escape($udom),
                   1877:                                  $homeserver);
                   1878:             }
1.912     raeburn  1879:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1880:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1881:                 ($response ne 'no_such_host')) {
                   1882:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1883:                 my @pairs=split(/\&/,$hashitems);
                   1884:                 foreach my $item (@pairs) {
                   1885:                     my ($key,$value)=split(/=/,$item,2);
                   1886:                     $key = &unescape($key);
                   1887:                     next if ($key =~ /^error: 2 /);
                   1888:                     $ruleshash{$key}=&thaw_unescape($value);
                   1889:                 }
                   1890:                 my @esc_order = split(/\&/,$orderitems);
                   1891:                 foreach my $item (@esc_order) {
                   1892:                     push(@ruleorder,&unescape($item));
                   1893:                 }
                   1894:             }
                   1895:         }
                   1896:     }
                   1897:     return (\%ruleshash,\@ruleorder);
                   1898: }
                   1899: 
1.976     raeburn  1900: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1901: 
                   1902: sub get_domain_defaults {
                   1903:     my ($domain) = @_;
                   1904:     my $cachetime = 60*60*24;
                   1905:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1906:     if (defined($cached)) {
                   1907:         if (ref($result) eq 'HASH') {
                   1908:             return %{$result};
                   1909:         }
                   1910:     }
                   1911:     my %domdefaults;
                   1912:     my %domconfig =
1.989     raeburn  1913:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1914:                                   'requestcourses','inststatus',
1.1073    raeburn  1915:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1916:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1917:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1918:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1919:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1920:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1921:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1922:     } else {
                   1923:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1924:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1925:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1926:     }
1.976     raeburn  1927:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1928:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1929:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1930:         } else {
                   1931:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1932:         } 
                   1933:         my @usertools = ('aboutme','blog','portfolio');
                   1934:         foreach my $item (@usertools) {
                   1935:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1936:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1937:             }
                   1938:         }
                   1939:     }
1.985     raeburn  1940:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1941:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1942:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1943:         }
                   1944:     }
1.989     raeburn  1945:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1946:         foreach my $item ('inststatustypes','inststatusorder') {
                   1947:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1948:         }
                   1949:     }
1.1047    raeburn  1950:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1951:         foreach my $item ('canuse_pdfforms') {
                   1952:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1953:         }
                   1954:     }
1.1073    raeburn  1955:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1956:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1957:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1958:         }
                   1959:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1960:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1961:         }
                   1962:     }
1.943     raeburn  1963:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1964:                                   $cachetime);
                   1965:     return %domdefaults;
                   1966: }
                   1967: 
1.344     www      1968: # --------------------------------------------------- Assign a key to a student
                   1969: 
                   1970: sub assign_access_key {
1.364     www      1971: #
                   1972: # a valid key looks like uname:udom#comments
                   1973: # comments are being appended
                   1974: #
1.498     www      1975:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1976:     $kdom=
1.620     albertel 1977:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1978:     $knum=
1.620     albertel 1979:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1980:     $cdom=
1.620     albertel 1981:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1982:     $cnum=
1.620     albertel 1983:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1984:     $udom=$env{'user.name'} unless (defined($udom));
                   1985:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1986:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1987:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1988:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1989:                                                   # assigned to this person
                   1990:                                                   # - this should not happen,
1.345     www      1991:                                                   # unless something went wrong
                   1992:                                                   # the first time around
                   1993: # ready to assign
1.364     www      1994:         $logentry=$1.'; '.$logentry;
1.496     www      1995:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1996:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1997: # key now belongs to user
1.346     www      1998: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1999:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2000:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2001:                 return 'ok';
                   2002:             } else {
                   2003:                 return 
                   2004:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2005: 	    }
                   2006:         } else {
                   2007:             return 'error: Could not assign key, try again later.';
                   2008:         }
1.364     www      2009:     } elsif (!$existing{$ckey}) {
1.345     www      2010: # the key does not exist
                   2011: 	return 'error: The key does not exist';
                   2012:     } else {
                   2013: # the key is somebody else's
                   2014: 	return 'error: The key is already in use';
                   2015:     }
1.344     www      2016: }
                   2017: 
1.364     www      2018: # ------------------------------------------ put an additional comment on a key
                   2019: 
                   2020: sub comment_access_key {
                   2021: #
                   2022: # a valid key looks like uname:udom#comments
                   2023: # comments are being appended
                   2024: #
                   2025:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2026:     $cdom=
1.620     albertel 2027:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2028:     $cnum=
1.620     albertel 2029:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2030:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2031:     if ($existing{$ckey}) {
                   2032:         $existing{$ckey}.='; '.$logentry;
                   2033: # ready to assign
1.367     www      2034:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2035:                                                  $cdom,$cnum) eq 'ok') {
                   2036: 	    return 'ok';
                   2037:         } else {
                   2038: 	    return 'error: Count not store comment.';
                   2039:         }
                   2040:     } else {
                   2041: # the key does not exist
                   2042: 	return 'error: The key does not exist';
                   2043:     }
                   2044: }
                   2045: 
1.344     www      2046: # ------------------------------------------------------ Generate a set of keys
                   2047: 
                   2048: sub generate_access_keys {
1.364     www      2049:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2050:     $cdom=
1.620     albertel 2051:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2052:     $cnum=
1.620     albertel 2053:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2054:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2055:     unless (($cdom) && ($cnum)) { return 0; }
                   2056:     if ($number>10000) { return 0; }
                   2057:     sleep(2); # make sure don't get same seed twice
                   2058:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2059:     my $total=0;
                   2060:     for (my $i=1;$i<=$number;$i++) {
                   2061:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2062:                   sprintf("%lx",int(100000*rand)).'-'.
                   2063:                   sprintf("%lx",int(100000*rand));
                   2064:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2065:        $newkey=~s/0/h/g; # and also 0 and O
                   2066:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2067:        if ($existing{$newkey}) {
                   2068:            $i--;
                   2069:        } else {
1.364     www      2070: 	  if (&put('accesskeys',
                   2071:               { $newkey => '# generated '.localtime().
1.620     albertel 2072:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2073:                            '; '.$logentry },
                   2074: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2075:               $total++;
                   2076: 	  }
                   2077:        }
                   2078:     }
1.620     albertel 2079:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2080:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2081:     return $total;
                   2082: }
                   2083: 
                   2084: # ------------------------------------------------------- Validate an accesskey
                   2085: 
                   2086: sub validate_access_key {
                   2087:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2088:     $cdom=
1.620     albertel 2089:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2090:     $cnum=
1.620     albertel 2091:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2092:     $udom=$env{'user.domain'} unless (defined($udom));
                   2093:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2094:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2095:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2096: }
                   2097: 
                   2098: # ------------------------------------- Find the section of student in a course
1.652     albertel 2099: sub devalidate_getsection_cache {
                   2100:     my ($udom,$unam,$courseid)=@_;
                   2101:     my $hashid="$udom:$unam:$courseid";
                   2102:     &devalidate_cache_new('getsection',$hashid);
                   2103: }
1.298     matthew  2104: 
1.815     albertel 2105: sub courseid_to_courseurl {
                   2106:     my ($courseid) = @_;
                   2107:     #already url style courseid
                   2108:     return $courseid if ($courseid =~ m{^/});
                   2109: 
                   2110:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2111: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2112: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2113: 	return "/$cdom/$cnum";
                   2114:     }
                   2115: 
                   2116:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2117:     if (exists($courseinfo{'num'})) {
                   2118: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2119:     }
                   2120: 
                   2121:     return undef;
                   2122: }
                   2123: 
1.298     matthew  2124: sub getsection {
                   2125:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2126:     my $cachetime=1800;
1.551     albertel 2127: 
                   2128:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2129:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2130:     if (defined($cached)) { return $result; }
                   2131: 
1.298     matthew  2132:     my %Pending; 
                   2133:     my %Expired;
                   2134:     #
                   2135:     # Each role can either have not started yet (pending), be active, 
                   2136:     #    or have expired.
                   2137:     #
                   2138:     # If there is an active role, we are done.
                   2139:     #
                   2140:     # If there is more than one role which has not started yet, 
                   2141:     #     choose the one which will start sooner
                   2142:     # If there is one role which has not started yet, return it.
                   2143:     #
                   2144:     # If there is more than one expired role, choose the one which ended last.
                   2145:     # If there is a role which has expired, return it.
                   2146:     #
1.815     albertel 2147:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  2148:     my $extra = &freeze_escape({'skipcheck' => 1});
                   2149:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  2150:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2151:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2152:         my $section=$1;
                   2153:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2154:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2155:         my $now=time;
1.548     albertel 2156:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2157:             $Expired{$end}=$section;
                   2158:             next;
                   2159:         }
1.548     albertel 2160:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2161:             $Pending{$start}=$section;
                   2162:             next;
                   2163:         }
1.599     albertel 2164:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2165:     }
                   2166:     #
                   2167:     # Presumedly there will be few matching roles from the above
                   2168:     # loop and the sorting time will be negligible.
                   2169:     if (scalar(keys(%Pending))) {
                   2170:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2171:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2172:     } 
                   2173:     if (scalar(keys(%Expired))) {
                   2174:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2175:         my $time = pop(@sorted);
1.599     albertel 2176:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2177:     }
1.599     albertel 2178:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2179: }
1.70      www      2180: 
1.599     albertel 2181: sub save_cache {
                   2182:     &purge_remembered();
1.722     albertel 2183:     #&Apache::loncommon::validate_page();
1.620     albertel 2184:     undef(%env);
1.780     albertel 2185:     undef($env_loaded);
1.599     albertel 2186: }
1.452     albertel 2187: 
1.599     albertel 2188: my $to_remember=-1;
                   2189: my %remembered;
                   2190: my %accessed;
                   2191: my $kicks=0;
                   2192: my $hits=0;
1.849     albertel 2193: sub make_key {
                   2194:     my ($name,$id) = @_;
1.872     albertel 2195:     if (length($id) > 65 
                   2196: 	&& length(&escape($id)) > 200) {
                   2197: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2198:     }
1.849     albertel 2199:     return &escape($name.':'.$id);
                   2200: }
                   2201: 
1.599     albertel 2202: sub devalidate_cache_new {
                   2203:     my ($name,$id,$debug) = @_;
                   2204:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2205:     $id=&make_key($name,$id);
1.599     albertel 2206:     $memcache->delete($id);
                   2207:     delete($remembered{$id});
                   2208:     delete($accessed{$id});
                   2209: }
                   2210: 
                   2211: sub is_cached_new {
                   2212:     my ($name,$id,$debug) = @_;
1.849     albertel 2213:     $id=&make_key($name,$id);
1.599     albertel 2214:     if (exists($remembered{$id})) {
1.1133    foxr     2215: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2216: 	$accessed{$id}=[&gettimeofday()];
                   2217: 	$hits++;
                   2218: 	return ($remembered{$id},1);
                   2219:     }
                   2220:     my $value = $memcache->get($id);
                   2221:     if (!(defined($value))) {
                   2222: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2223: 	return (undef,undef);
1.416     albertel 2224:     }
1.599     albertel 2225:     if ($value eq '__undef__') {
                   2226: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2227: 	$value=undef;
                   2228:     }
                   2229:     &make_room($id,$value,$debug);
                   2230:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2231:     return ($value,1);
                   2232: }
                   2233: 
                   2234: sub do_cache_new {
                   2235:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2236:     $id=&make_key($name,$id);
1.599     albertel 2237:     my $setvalue=$value;
                   2238:     if (!defined($setvalue)) {
                   2239: 	$setvalue='__undef__';
                   2240:     }
1.623     albertel 2241:     if (!defined($time) ) {
                   2242: 	$time=600;
                   2243:     }
1.599     albertel 2244:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2245:     my $result = $memcache->set($id,$setvalue,$time);
                   2246:     if (! $result) {
1.872     albertel 2247: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2248: 	$memcache->disconnect_all();
1.872     albertel 2249:     }
1.600     albertel 2250:     # need to make a copy of $value
1.919     albertel 2251:     &make_room($id,$value,$debug);
1.599     albertel 2252:     return $value;
                   2253: }
                   2254: 
                   2255: sub make_room {
                   2256:     my ($id,$value,$debug)=@_;
1.919     albertel 2257: 
                   2258:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2259:                                     : $value;
1.599     albertel 2260:     if ($to_remember<0) { return; }
                   2261:     $accessed{$id}=[&gettimeofday()];
                   2262:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2263:     my $to_kick;
                   2264:     my $max_time=0;
                   2265:     foreach my $other (keys(%accessed)) {
                   2266: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2267: 	    $to_kick=$other;
                   2268: 	    $max_time=&tv_interval($accessed{$other});
                   2269: 	}
                   2270:     }
                   2271:     delete($remembered{$to_kick});
                   2272:     delete($accessed{$to_kick});
                   2273:     $kicks++;
                   2274:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2275:     return;
                   2276: }
                   2277: 
1.599     albertel 2278: sub purge_remembered {
1.604     albertel 2279:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2280:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2281:     undef(%remembered);
                   2282:     undef(%accessed);
1.428     albertel 2283: }
1.70      www      2284: # ------------------------------------- Read an entry from a user's environment
                   2285: 
                   2286: sub userenvironment {
                   2287:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2288:     my $items;
                   2289:     foreach my $item (@what) {
                   2290:         $items.=&escape($item).'&';
                   2291:     }
                   2292:     $items=~s/\&$//;
1.70      www      2293:     my %returnhash=();
1.1009    raeburn  2294:     my $uhome = &homeserver($unam,$udom);
                   2295:     unless ($uhome eq 'no_host') {
                   2296:         my @answer=split(/\&/, 
                   2297:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2298:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2299:             return %returnhash;
                   2300:         }
1.1009    raeburn  2301:         my $i;
                   2302:         for ($i=0;$i<=$#what;$i++) {
                   2303: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2304:         }
1.70      www      2305:     }
                   2306:     return %returnhash;
1.1       albertel 2307: }
                   2308: 
1.617     albertel 2309: # ---------------------------------------------------------- Get a studentphoto
                   2310: sub studentphoto {
                   2311:     my ($udom,$unam,$ext) = @_;
                   2312:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2313:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2314:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2315:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2316:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2317:             } else {
                   2318:                 my ($result,$perm_reqd)=
1.707     albertel 2319: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2320:                 if ($result eq 'ok') {
                   2321:                     if (!($perm_reqd eq 'yes')) {
                   2322:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2323:                     }
                   2324:                 }
                   2325:             }
                   2326:         }
                   2327:     } else {
                   2328:         my ($result,$perm_reqd) = 
1.707     albertel 2329: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2330:         if ($result eq 'ok') {
                   2331:             if (!($perm_reqd eq 'yes')) {
                   2332:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2333:             }
                   2334:         }
                   2335:     }
                   2336:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2337: }
                   2338: 
                   2339: sub retrievestudentphoto {
                   2340:     my ($udom,$unam,$ext,$type) = @_;
                   2341:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2342:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2343:     if ($ret eq 'ok') {
                   2344:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2345:         if ($type eq 'thumbnail') {
                   2346:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2347:         }
                   2348:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2349:         return $tokenurl;
                   2350:     } else {
                   2351:         if ($type eq 'thumbnail') {
                   2352:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2353:         } else { 
                   2354:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2355:         }
1.617     albertel 2356:     }
                   2357: }
                   2358: 
1.263     www      2359: # -------------------------------------------------------------------- New chat
                   2360: 
                   2361: sub chatsend {
1.724     raeburn  2362:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2363:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2364:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2365:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2366:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2367: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2368: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2369: }
                   2370: 
                   2371: # ------------------------------------------ Find current version of a resource
                   2372: 
                   2373: sub getversion {
                   2374:     my $fname=&clutter(shift);
                   2375:     unless ($fname=~/^\/res\//) { return -1; }
                   2376:     return &currentversion(&filelocation('',$fname));
                   2377: }
                   2378: 
                   2379: sub currentversion {
                   2380:     my $fname=shift;
                   2381:     my $author=$fname;
                   2382:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2383:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2384:     my $home=&homeserver($uname,$udom);
1.292     www      2385:     if ($home eq 'no_host') { 
                   2386:         return -1; 
                   2387:     }
1.1112    www      2388:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2389:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2390: 	return -1;
                   2391:     }
1.1112    www      2392:     return $answer;
1.263     www      2393: }
                   2394: 
1.1111    www      2395: #
                   2396: # Return special version number of resource if set by override, empty otherwise
                   2397: #
                   2398: sub usedversion {
                   2399:     my $fname=shift;
                   2400:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2401:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2402:     if ($urlversion) { return $urlversion; }
                   2403:     return '';
                   2404: }
                   2405: 
1.1       albertel 2406: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2407: 
1.1       albertel 2408: sub subscribe {
                   2409:     my $fname=shift;
1.761     raeburn  2410:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2411:     $fname=~s/[\n\r]//g;
1.1       albertel 2412:     my $author=$fname;
                   2413:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2414:     my ($udom,$uname)=split(/\//,$author);
                   2415:     my $home=homeserver($uname,$udom);
1.335     albertel 2416:     if ($home eq 'no_host') {
                   2417:         return 'not_found';
1.1       albertel 2418:     }
                   2419:     my $answer=reply("sub:$fname",$home);
1.64      www      2420:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2421: 	$answer.=' by '.$home;
                   2422:     }
1.1       albertel 2423:     return $answer;
                   2424: }
                   2425:     
1.8       www      2426: # -------------------------------------------------------------- Replicate file
                   2427: 
                   2428: sub repcopy {
                   2429:     my $filename=shift;
1.23      www      2430:     $filename=~s/\/+/\//g;
1.607     raeburn  2431:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2432:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2433:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2434: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2435: 	return &repcopy_userfile($filename);
                   2436:     }
1.532     albertel 2437:     $filename=~s/[\n\r]//g;
1.8       www      2438:     my $transname="$filename.in.transfer";
1.828     www      2439: # FIXME: this should flock
1.607     raeburn  2440:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2441:     my $remoteurl=subscribe($filename);
1.64      www      2442:     if ($remoteurl =~ /^con_lost by/) {
                   2443: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2444:            return 'unavailable';
1.8       www      2445:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2446: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2447: 	   return 'not_found';
1.64      www      2448:     } elsif ($remoteurl =~ /^rejected by/) {
                   2449: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2450:            return 'forbidden';
1.20      www      2451:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2452:            return 'ok';
1.8       www      2453:     } else {
1.290     www      2454:         my $author=$filename;
                   2455:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2456:         my ($udom,$uname)=split(/\//,$author);
                   2457:         my $home=homeserver($uname,$udom);
                   2458:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2459:            my @parts=split(/\//,$filename);
                   2460:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2461:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2462:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2463: 	       return 'bad_request';
1.8       www      2464:            }
                   2465:            my $count;
                   2466:            for ($count=5;$count<$#parts;$count++) {
                   2467:                $path.="/$parts[$count]";
                   2468:                if ((-e $path)!=1) {
                   2469: 		   mkdir($path,0777);
                   2470:                }
                   2471:            }
                   2472:            my $ua=new LWP::UserAgent;
                   2473:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2474:            my $response=$ua->request($request,$transname);
                   2475:            if ($response->is_error()) {
                   2476: 	       unlink($transname);
                   2477:                my $message=$response->status_line;
1.672     albertel 2478:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2479:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2480:                return 'unavailable';
1.8       www      2481:            } else {
1.16      www      2482: 	       if ($remoteurl!~/\.meta$/) {
                   2483:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2484:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2485:                   if ($mresponse->is_error()) {
                   2486: 		      unlink($filename.'.meta');
                   2487:                       &logthis(
1.672     albertel 2488:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2489:                   }
                   2490: 	       }
1.8       www      2491:                rename($transname,$filename);
1.607     raeburn  2492:                return 'ok';
1.8       www      2493:            }
1.290     www      2494:        }
1.8       www      2495:     }
1.330     www      2496: }
                   2497: 
                   2498: # ------------------------------------------------ Get server side include body
                   2499: sub ssi_body {
1.381     albertel 2500:     my ($filelink,%form)=@_;
1.606     matthew  2501:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2502:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2503:     }
1.953     www      2504:     my $output='';
                   2505:     my $response;
1.980     raeburn  2506:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2507:        ($output,$response)=&externalssi($filelink);
1.953     www      2508:     } else {
1.1004    droeschl 2509:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2510:        $filelink .= 'inhibitmenu=yes';
1.953     www      2511:        ($output,$response)=&ssi($filelink,%form);
                   2512:     }
1.778     albertel 2513:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2514:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2515:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2516:     if (wantarray) {
                   2517:         return ($output, $response);
                   2518:     } else {
                   2519:         return $output;
                   2520:     }
1.8       www      2521: }
                   2522: 
1.15      www      2523: # --------------------------------------------------------- Server Side Include
                   2524: 
1.782     albertel 2525: sub absolute_url {
                   2526:     my ($host_name) = @_;
                   2527:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2528:     if ($host_name eq '') {
                   2529: 	$host_name = $ENV{'SERVER_NAME'};
                   2530:     }
                   2531:     return $protocol.$host_name;
                   2532: }
                   2533: 
1.942     foxr     2534: #
                   2535: #   Server side include.
                   2536: # Parameters:
                   2537: #  fn     Possibly encrypted resource name/id.
                   2538: #  form   Hash that describes how the rendering should be done
                   2539: #         and other things.
1.944     foxr     2540: # Returns:
1.950     raeburn  2541: #   Scalar context: The content of the response.
                   2542: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2543: #     
1.15      www      2544: sub ssi {
                   2545: 
1.944     foxr     2546:     my ($fn,%form)=@_;
1.15      www      2547:     my $ua=new LWP::UserAgent;
1.23      www      2548:     my $request;
1.711     albertel 2549: 
                   2550:     $form{'no_update_last_known'}=1;
1.895     albertel 2551:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2552:     if (%form) {
1.782     albertel 2553:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2554:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2555:     } else {
1.782     albertel 2556:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2557:     }
                   2558: 
1.15      www      2559:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2560:     my $response=$ua->request($request);
                   2561: 
1.944     foxr     2562:     if (wantarray) {
                   2563: 	return ($response->content, $response);
                   2564:     } else {
                   2565: 	return $response->content;
1.942     foxr     2566:     }
1.324     www      2567: }
                   2568: 
                   2569: sub externalssi {
                   2570:     my ($url)=@_;
                   2571:     my $ua=new LWP::UserAgent;
                   2572:     my $request=new HTTP::Request('GET',$url);
                   2573:     my $response=$ua->request($request);
1.954     raeburn  2574:     if (wantarray) {
                   2575:         return ($response->content, $response);
                   2576:     } else {
                   2577:         return $response->content;
                   2578:     }
1.15      www      2579: }
1.254     www      2580: 
1.492     albertel 2581: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2582: 
                   2583: sub allowuploaded {
                   2584:     my ($srcurl,$url)=@_;
                   2585:     $url=&clutter(&declutter($url));
                   2586:     my $dir=$url;
                   2587:     $dir=~s/\/[^\/]+$//;
                   2588:     my %httpref=();
                   2589:     my $httpurl=&hreflocation('',$url);
                   2590:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2591:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2592: }
1.477     raeburn  2593: 
1.478     albertel 2594: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2595: # input: action, courseID, current domain, intended
1.637     raeburn  2596: #        path to file, source of file, instruction to parse file for objects,
                   2597: #        ref to hash for embedded objects,
                   2598: #        ref to hash for codebase of java objects.
1.1095    raeburn  2599: #        reference to scalar to accommodate mime type determined
                   2600: #          from File::MMagic if $parser = parse.
1.637     raeburn  2601: #
1.485     raeburn  2602: # output: url to file (if action was uploaddoc), 
                   2603: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2604: #
1.478     albertel 2605: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2606: # course.
1.477     raeburn  2607: #
1.478     albertel 2608: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2609: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2610: #          course's home server.
1.477     raeburn  2611: #
1.478     albertel 2612: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2613: #          be copied from $source (current location) to 
                   2614: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2615: #         and will then be copied to
                   2616: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2617: #         course's home server.
1.485     raeburn  2618: #
1.481     raeburn  2619: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2620: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2621: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2622: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2623: #         in course's home server.
1.637     raeburn  2624: #
1.477     raeburn  2625: 
                   2626: sub process_coursefile {
1.1095    raeburn  2627:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2628:         $mimetype)=@_;
1.477     raeburn  2629:     my $fetchresult;
1.638     albertel 2630:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2631:     if ($action eq 'propagate') {
1.638     albertel 2632:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2633: 			     $home);
1.481     raeburn  2634:     } else {
1.477     raeburn  2635:         my $fpath = '';
                   2636:         my $fname = $file;
1.478     albertel 2637:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2638:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2639:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2640:         if ($action eq 'copy') {
                   2641:             if ($source eq '') {
                   2642:                 $fetchresult = 'no source file';
                   2643:                 return $fetchresult;
                   2644:             } else {
                   2645:                 my $destination = $filepath.'/'.$fname;
                   2646:                 rename($source,$destination);
                   2647:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2648:                                  $home);
1.481     raeburn  2649:             }
                   2650:         } elsif ($action eq 'uploaddoc') {
                   2651:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2652:             print $fh $env{'form.'.$source};
1.481     raeburn  2653:             close($fh);
1.637     raeburn  2654:             if ($parser eq 'parse') {
1.1024    raeburn  2655:                 my $mm = new File::MMagic;
1.1095    raeburn  2656:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2657:                 if ($type eq 'text/html') {
1.1024    raeburn  2658:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2659:                     unless ($parse_result eq 'ok') {
                   2660:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2661:                     }
1.637     raeburn  2662:                 }
1.1095    raeburn  2663:                 if (ref($mimetype)) {
                   2664:                     $$mimetype = $type;
                   2665:                 } 
1.637     raeburn  2666:             }
1.477     raeburn  2667:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2668:                                  $home);
1.481     raeburn  2669:             if ($fetchresult eq 'ok') {
                   2670:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2671:             } else {
                   2672:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2673:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2674:                 return '/adm/notfound.html';
                   2675:             }
1.477     raeburn  2676:         }
                   2677:     }
1.485     raeburn  2678:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2679:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2680:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2681:     }
                   2682:     return $fetchresult;
                   2683: }
                   2684: 
1.637     raeburn  2685: sub build_filepath {
                   2686:     my ($fpath) = @_;
                   2687:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2688:     unless ($fpath eq '') {
                   2689:         my @parts=split('/',$fpath);
                   2690:         foreach my $part (@parts) {
                   2691:             $filepath.= '/'.$part;
                   2692:             if ((-e $filepath)!=1) {
                   2693:                 mkdir($filepath,0777);
                   2694:             }
                   2695:         }
                   2696:     }
                   2697:     return $filepath;
                   2698: }
                   2699: 
                   2700: sub store_edited_file {
1.638     albertel 2701:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2702:     my $file = $primary_url;
                   2703:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2704:     my $fpath = '';
                   2705:     my $fname = $file;
                   2706:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2707:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2708:     my $filepath = &build_filepath($fpath);
                   2709:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2710:     print $fh $content;
                   2711:     close($fh);
1.638     albertel 2712:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2713:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2714: 			  $home);
1.637     raeburn  2715:     if ($$fetchresult eq 'ok') {
                   2716:         return '/uploaded/'.$fpath.'/'.$fname;
                   2717:     } else {
1.638     albertel 2718:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2719: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2720:         return '/adm/notfound.html';
                   2721:     }
                   2722: }
                   2723: 
1.531     albertel 2724: sub clean_filename {
1.831     albertel 2725:     my ($fname,$args)=@_;
1.315     www      2726: # Replace Windows backslashes by forward slashes
1.257     www      2727:     $fname=~s/\\/\//g;
1.831     albertel 2728:     if (!$args->{'keep_path'}) {
                   2729:         # Get rid of everything but the actual filename
                   2730: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2731:     }
1.315     www      2732: # Replace spaces by underscores
                   2733:     $fname=~s/\s+/\_/g;
                   2734: # Replace all other weird characters by nothing
1.831     albertel 2735:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2736: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2737: # numbers
                   2738:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2739:     return $fname;
                   2740: }
1.1051    raeburn  2741: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2742: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2743: # image with the same aspect ratio as the original, but with dimensions which do 
                   2744: # not exceed $resizewidth and $resizeheight.
                   2745:  
1.984     neumanie 2746: sub resizeImage {
1.1051    raeburn  2747:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2748:     my $ima = Image::Magick->new;
                   2749:     my $resized;
                   2750:     if (-e $img_path) {
                   2751:         $ima->Read($img_path);
                   2752:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2753:             my $width = $ima->Get('width');
                   2754:             my $height = $ima->Get('height');
                   2755:             if ($width > $resizewidth) {
                   2756: 	        my $factor = $width/$resizewidth;
                   2757:                 my $newheight = $height/$factor;
                   2758:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2759:                 $resized = 1;
                   2760:             }
                   2761:         }
                   2762:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2763:             my $width = $ima->Get('width');
                   2764:             my $height = $ima->Get('height');
                   2765:             if ($height > $resizeheight) {
                   2766:                 my $factor = $height/$resizeheight;
                   2767:                 my $newwidth = $width/$factor;
                   2768:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2769:                 $resized = 1;
                   2770:             }
                   2771:         }
                   2772:         if ($resized) {
                   2773:             $ima->Write($img_path);
                   2774:         }
                   2775:     }
                   2776:     return;
1.977     amueller 2777: }
                   2778: 
1.608     albertel 2779: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2780: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2781: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2782: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2783: #                                    canceloverwrite, or ''. 
                   2784: #                   if 'coursedoc': upload to the current course
                   2785: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2786: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2787: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2788: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2789: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2790: #        $allfiles - reference to hash for embedded objects
                   2791: #        $codebase - reference to hash for codebase of java objects
                   2792: #        $desuname - username for permanent storage of uploaded file
                   2793: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2794: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2795: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2796: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2797: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2798: #        $mimetype - reference to scalar to accommodate mime type determined
                   2799: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2800: # 
1.686     albertel 2801: # output: url of file in userspace, or error: <message> 
                   2802: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2803: 
1.531     albertel 2804: sub userfileupload {
1.1090    raeburn  2805:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2806:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2807:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2808:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2809:     $fname=&clean_filename($fname);
1.1090    raeburn  2810:     # See if there is anything left
1.257     www      2811:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2812:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2813:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2814:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2815:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2816:         my $now = time;
1.1090    raeburn  2817:         my $filepath;
1.1095    raeburn  2818:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2819:              $filepath = 'tmp/helprequests/'.$now;
                   2820:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2821:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2822:                          '_'.$env{'user.domain'}.'/pending';
                   2823:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2824:             my ($docuname,$docudom);
                   2825:             if ($destudom) {
                   2826:                 $docudom = $destudom;
                   2827:             } else {
                   2828:                 $docudom = $env{'user.domain'};
                   2829:             }
                   2830:             if ($destuname) {
                   2831:                 $docuname = $destuname;
                   2832:             } else {
                   2833:                 $docuname = $env{'user.name'};
                   2834:             }
                   2835:             if (exists($env{'form.group'})) {
                   2836:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2837:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2838:             }
                   2839:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2840:             if ($context eq 'canceloverwrite') {
                   2841:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2842:                 if (-e  $tempfile) {
                   2843:                     my @info = stat($tempfile);
                   2844:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2845:                         unlink($tempfile);
                   2846:                     }
                   2847:                 }
                   2848:                 return;
1.523     raeburn  2849:             }
                   2850:         }
1.1090    raeburn  2851:         # Create the directory if not present
1.741     raeburn  2852:         my @parts=split(/\//,$filepath);
                   2853:         my $fullpath = $perlvar{'lonDaemons'};
                   2854:         for (my $i=0;$i<@parts;$i++) {
                   2855:             $fullpath .= '/'.$parts[$i];
                   2856:             if ((-e $fullpath)!=1) {
                   2857:                 mkdir($fullpath,0777);
                   2858:             }
                   2859:         }
                   2860:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2861:         print $fh $env{'form.'.$formname};
                   2862:         close($fh);
1.1090    raeburn  2863:         if ($context eq 'existingfile') {
                   2864:             my @info = stat($fullpath.'/'.$fname);
                   2865:             return ($fullpath.'/'.$fname,$info[9]);
                   2866:         } else {
                   2867:             return $fullpath.'/'.$fname;
                   2868:         }
1.523     raeburn  2869:     }
1.995     raeburn  2870:     if ($subdir eq 'scantron') {
                   2871:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2872:     } else {
1.995     raeburn  2873:         $fname="$subdir/$fname";
                   2874:     }
1.1090    raeburn  2875:     if ($context eq 'coursedoc') {
1.638     albertel 2876: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2877: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2878:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2879:             return &finishuserfileupload($docuname,$docudom,
                   2880: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2881: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2882:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2883:         } else {
1.620     albertel 2884:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2885:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2886: 				       $fname,$formname,$parser,
1.1095    raeburn  2887: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2888:         }
1.719     banghart 2889:     } elsif (defined($destuname)) {
                   2890:         my $docuname=$destuname;
                   2891:         my $docudom=$destudom;
1.860     raeburn  2892: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2893: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2894:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2895:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2896:     } else {
1.638     albertel 2897:         my $docuname=$env{'user.name'};
                   2898:         my $docudom=$env{'user.domain'};
1.714     raeburn  2899:         if (exists($env{'form.group'})) {
                   2900:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2901:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2902:         }
1.860     raeburn  2903: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2904: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2905:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2906:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2907:     }
1.271     www      2908: }
                   2909: 
                   2910: sub finishuserfileupload {
1.860     raeburn  2911:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2912:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2913:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2914:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2915:   
1.860     raeburn  2916:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2917:     $file=$fname;
                   2918:     if ($fname=~m|/|) {
                   2919:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2920: 	$path.=$fnamepath.'/';
                   2921:     }
1.259     www      2922:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2923:     my $count;
                   2924:     for ($count=4;$count<=$#parts;$count++) {
                   2925:         $filepath.="/$parts[$count]";
                   2926:         if ((-e $filepath)!=1) {
                   2927: 	    mkdir($filepath,0777);
                   2928:         }
                   2929:     }
1.984     neumanie 2930: 
1.258     www      2931: # Save the file
                   2932:     {
1.701     albertel 2933: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2934: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2935: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2936: 	    return '/adm/notfound.html';
                   2937: 	}
1.1090    raeburn  2938:         if ($context eq 'overwrite') {
1.1117    foxr     2939:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2940:             my $target = $filepath.'/'.$file;
                   2941:             if (-e $source) {
                   2942:                 my @info = stat($source);
                   2943:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2944:                     unless (&File::Copy::move($source,$target)) {
                   2945:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2946:                         return "Moving from $source failed";
                   2947:                     }
                   2948:                 } else {
                   2949:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2950:                 }
                   2951:             } else {
                   2952:                 return "Temporary file: $source missing";
                   2953:             }
                   2954:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2955: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2956: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2957: 	    return '/adm/notfound.html';
                   2958: 	}
1.570     albertel 2959: 	close(FH);
1.1051    raeburn  2960:         if ($resizewidth && $resizeheight) {
                   2961:             my $mm = new File::MMagic;
                   2962:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2963:             if ($mime_type =~ m{^image/}) {
                   2964: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2965:             }  
1.977     amueller 2966: 	}
1.258     www      2967:     }
1.637     raeburn  2968:     if ($parser eq 'parse') {
1.1024    raeburn  2969:         my $mm = new File::MMagic;
1.1095    raeburn  2970:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2971:         if ($type eq 'text/html') {
1.1024    raeburn  2972:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2973:                                                        $allfiles,$codebase);
                   2974:             unless ($parse_result eq 'ok') {
                   2975:                 &logthis('Failed to parse '.$filepath.$file.
                   2976: 	   	         ' for embedded media: '.$parse_result); 
                   2977:             }
1.637     raeburn  2978:         }
1.1095    raeburn  2979:         if (ref($mimetype)) {
                   2980:             $$mimetype = $type;
                   2981:         }
1.637     raeburn  2982:     }
1.860     raeburn  2983:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2984:         my $input = $filepath.'/'.$file;
                   2985:         my $output = $filepath.'/'.'tn-'.$file;
                   2986:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2987:         system("convert -sample $thumbsize $input $output");
                   2988:         if (-e $filepath.'/'.'tn-'.$file) {
                   2989:             $fetchthumb  = 1; 
                   2990:         }
                   2991:     }
1.858     raeburn  2992:  
1.259     www      2993: # Notify homeserver to grep it
                   2994: #
1.984     neumanie 2995:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2996:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2997:     if ($fetchresult eq 'ok') {
1.860     raeburn  2998:         if ($fetchthumb) {
                   2999:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3000:             if ($thumbresult ne 'ok') {
                   3001:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3002:                          $docuhome.': '.$thumbresult);
                   3003:             }
                   3004:         }
1.259     www      3005: #
1.258     www      3006: # Return the URL to it
1.494     albertel 3007:         return '/uploaded/'.$path.$file;
1.263     www      3008:     } else {
1.494     albertel 3009:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3010: 		 ': '.$fetchresult);
1.263     www      3011:         return '/adm/notfound.html';
1.858     raeburn  3012:     }
1.493     albertel 3013: }
                   3014: 
1.637     raeburn  3015: sub extract_embedded_items {
1.961     raeburn  3016:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3017:     my @state = ();
                   3018:     my %javafiles = (
                   3019:                       codebase => '',
                   3020:                       code => '',
                   3021:                       archive => ''
                   3022:                     );
                   3023:     my %mediafiles = (
                   3024:                       src => '',
                   3025:                       movie => '',
                   3026:                      );
1.648     raeburn  3027:     my $p;
                   3028:     if ($content) {
                   3029:         $p = HTML::LCParser->new($content);
                   3030:     } else {
1.961     raeburn  3031:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3032:     }
1.641     albertel 3033:     while (my $t=$p->get_token()) {
1.640     albertel 3034: 	if ($t->[0] eq 'S') {
                   3035: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3036: 	    push(@state, $tagname);
1.648     raeburn  3037:             if (lc($tagname) eq 'allow') {
                   3038:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3039:             }
1.640     albertel 3040: 	    if (lc($tagname) eq 'img') {
                   3041: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3042: 	    }
1.886     albertel 3043: 	    if (lc($tagname) eq 'a') {
                   3044: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3045: 	    }
1.645     raeburn  3046:             if (lc($tagname) eq 'script') {
                   3047:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3048:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3049:                 } else {
                   3050:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   3051:                 }
                   3052:             }
                   3053:             if (lc($tagname) eq 'link') {
                   3054:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3055:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3056:                 }
                   3057:             }
1.640     albertel 3058: 	    if (lc($tagname) eq 'object' ||
                   3059: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3060: 		foreach my $item (keys(%javafiles)) {
                   3061: 		    $javafiles{$item} = '';
                   3062: 		}
                   3063: 	    }
                   3064: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3065: 		my $name = lc($attr->{'name'});
                   3066: 		foreach my $item (keys(%javafiles)) {
                   3067: 		    if ($name eq $item) {
                   3068: 			$javafiles{$item} = $attr->{'value'};
                   3069: 			last;
                   3070: 		    }
                   3071: 		}
                   3072: 		foreach my $item (keys(%mediafiles)) {
                   3073: 		    if ($name eq $item) {
                   3074: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   3075: 			last;
                   3076: 		    }
                   3077: 		}
                   3078: 	    }
                   3079: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3080: 		foreach my $item (keys(%javafiles)) {
                   3081: 		    if ($attr->{$item}) {
                   3082: 			$javafiles{$item} = $attr->{$item};
                   3083: 			last;
                   3084: 		    }
                   3085: 		}
                   3086: 		foreach my $item (keys(%mediafiles)) {
                   3087: 		    if ($attr->{$item}) {
                   3088: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3089: 			last;
                   3090: 		    }
                   3091: 		}
                   3092: 	    }
                   3093: 	} elsif ($t->[0] eq 'E') {
                   3094: 	    my ($tagname) = ($t->[1]);
                   3095: 	    if ($javafiles{'codebase'} ne '') {
                   3096: 		$javafiles{'codebase'} .= '/';
                   3097: 	    }  
                   3098: 	    if (lc($tagname) eq 'applet' ||
                   3099: 		lc($tagname) eq 'object' ||
                   3100: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3101: 		) {
                   3102: 		foreach my $item (keys(%javafiles)) {
                   3103: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3104: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3105: 			&add_filetype($allfiles,$file,$item);
                   3106: 		    }
                   3107: 		}
                   3108: 	    } 
                   3109: 	    pop @state;
                   3110: 	}
                   3111:     }
1.637     raeburn  3112:     return 'ok';
                   3113: }
                   3114: 
1.639     albertel 3115: sub add_filetype {
                   3116:     my ($allfiles,$file,$type)=@_;
                   3117:     if (exists($allfiles->{$file})) {
                   3118: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3119: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3120: 	}
                   3121:     } else {
                   3122: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3123:     }
                   3124: }
                   3125: 
1.493     albertel 3126: sub removeuploadedurl {
1.984     neumanie 3127:     my ($url)=@_;	
                   3128:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3129:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3130: }
                   3131: 
                   3132: sub removeuserfile {
                   3133:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3134:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3135:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3136:     if ($result eq 'ok') {	
1.798     raeburn  3137:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3138:             my $metafile = $fname.'.meta';
                   3139:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3140: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3141:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3142:             my $sqlresult = 
1.823     albertel 3143:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3144:                                         'portfolio_metadata',$group,
                   3145:                                         'delete');
1.798     raeburn  3146:         }
                   3147:     }
                   3148:     return $result;
1.257     www      3149: }
1.15      www      3150: 
1.530     albertel 3151: sub mkdiruserfile {
                   3152:     my ($docuname,$docudom,$dir)=@_;
                   3153:     my $home=&homeserver($docuname,$docudom);
                   3154:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3155: }
                   3156: 
1.531     albertel 3157: sub renameuserfile {
                   3158:     my ($docuname,$docudom,$old,$new)=@_;
                   3159:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3160:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3161:                         &escape("$old").':'.&escape("$new"),$home);
                   3162:     if ($result eq 'ok') {
                   3163:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3164:             my $oldmeta = $old.'.meta';
                   3165:             my $newmeta = $new.'.meta';
                   3166:             my $metaresult = 
                   3167:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3168: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3169:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3170:             my $sqlresult = 
1.823     albertel 3171:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3172:                                         'portfolio_metadata',$group,
                   3173:                                         'delete');
1.798     raeburn  3174:         }
                   3175:     }
                   3176:     return $result;
1.531     albertel 3177: }
                   3178: 
1.14      www      3179: # ------------------------------------------------------------------------- Log
                   3180: 
                   3181: sub log {
                   3182:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3183:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3184: }
                   3185: 
                   3186: # ------------------------------------------------------------------ Course Log
1.352     www      3187: #
                   3188: # This routine flushes several buffers of non-mission-critical nature
                   3189: #
1.157     www      3190: 
                   3191: sub flushcourselogs {
1.352     www      3192:     &logthis('Flushing log buffers');
                   3193: #
                   3194: # course logs
                   3195: # This is a log of all transactions in a course, which can be used
                   3196: # for data mining purposes
                   3197: #
                   3198: # It also collects the courseid database, which lists last transaction
                   3199: # times and course titles for all courseids
                   3200: #
                   3201:     my %courseidbuffer=();
1.921     raeburn  3202:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3203:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3204: 		          &escape($courselogs{$crsid}),
                   3205: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3206: 	    delete $courselogs{$crsid};
                   3207:         } else {
                   3208:             &logthis('Failed to flush log buffer for '.$crsid);
                   3209:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3210:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3211:                         " exceeded maximum size, deleting.</font>");
                   3212:                delete $courselogs{$crsid};
                   3213:             }
1.352     www      3214:         }
1.920     raeburn  3215:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3216:             'description' => $coursedescrbuf{$crsid},
                   3217:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3218:             'type'        => $coursetypebuf{$crsid},
                   3219:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3220:         };
1.191     harris41 3221:     }
1.352     www      3222: #
                   3223: # Write course id database (reverse lookup) to homeserver of courses 
                   3224: # Is used in pickcourse
                   3225: #
1.840     albertel 3226:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3227:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3228:                                     $courseidbuffer{$crs_home},
                   3229:                                     $crs_home,'timeonly');
1.352     www      3230:     }
                   3231: #
                   3232: # File accesses
                   3233: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3234: #
1.449     matthew  3235:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3236:         if ($entry =~ /___count$/) {
                   3237:             my ($dom,$name);
1.807     albertel 3238:             ($dom,$name,undef)=
1.811     albertel 3239: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3240:             if (! defined($dom) || $dom eq '' || 
                   3241:                 ! defined($name) || $name eq '') {
1.620     albertel 3242:                 my $cid = $env{'request.course.id'};
                   3243:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3244:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3245:             }
1.450     matthew  3246:             my $value = $accesshash{$entry};
                   3247:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3248:             my %temphash=($url => $value);
1.449     matthew  3249:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3250:             if ($result eq 'ok') {
                   3251:                 delete $accesshash{$entry};
                   3252:             } elsif ($result eq 'unknown_cmd') {
                   3253:                 # Target server has old code running on it.
1.450     matthew  3254:                 my %temphash=($entry => $value);
1.449     matthew  3255:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3256:                     delete $accesshash{$entry};
                   3257:                 }
                   3258:             }
                   3259:         } else {
1.811     albertel 3260:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3261:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3262:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3263:                 delete $accesshash{$entry};
                   3264:             }
1.185     www      3265:         }
1.191     harris41 3266:     }
1.352     www      3267: #
                   3268: # Roles
                   3269: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3270: #
1.800     albertel 3271:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3272:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3273: 	    split(/\:/,$entry);
                   3274:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3275:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3276:                 $rudom,$runame) eq 'ok') {
                   3277: 	    delete $userrolehash{$entry};
                   3278:         }
                   3279:     }
1.662     raeburn  3280: #
                   3281: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3282: #
                   3283:     my %domrolebuffer = ();
1.1000    raeburn  3284:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3285:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3286:         if ($domrolebuffer{$rudom}) {
                   3287:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3288:                       '='.&escape($domainrolehash{$entry});
                   3289:         } else {
                   3290:             $domrolebuffer{$rudom}.=&escape($entry).
                   3291:                       '='.&escape($domainrolehash{$entry});
                   3292:         }
                   3293:         delete $domainrolehash{$entry};
                   3294:     }
                   3295:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3296: 	my %servers = &get_servers($dom,'library');
                   3297: 	foreach my $tryserver (keys(%servers)) {
                   3298: 	    unless (&reply('domroleput:'.$dom.':'.
                   3299: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3300: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3301: 	    }
1.662     raeburn  3302:         }
                   3303:     }
1.186     www      3304:     $dumpcount++;
1.157     www      3305: }
                   3306: 
                   3307: sub courselog {
                   3308:     my $what=shift;
1.158     www      3309:     $what=time.':'.$what;
1.620     albertel 3310:     unless ($env{'request.course.id'}) { return ''; }
                   3311:     $coursedombuf{$env{'request.course.id'}}=
                   3312:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3313:     $coursenumbuf{$env{'request.course.id'}}=
                   3314:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3315:     $coursehombuf{$env{'request.course.id'}}=
                   3316:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3317:     $coursedescrbuf{$env{'request.course.id'}}=
                   3318:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3319:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3320:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3321:     $courseownerbuf{$env{'request.course.id'}}=
                   3322:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3323:     $coursetypebuf{$env{'request.course.id'}}=
                   3324:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3325:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3326: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3327:     } else {
1.620     albertel 3328: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3329:     }
1.620     albertel 3330:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3331: 	&flushcourselogs();
                   3332:     }
1.158     www      3333: }
                   3334: 
                   3335: sub courseacclog {
                   3336:     my $fnsymb=shift;
1.620     albertel 3337:     unless ($env{'request.course.id'}) { return ''; }
                   3338:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3339:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3340:         $what.=':POST';
1.583     matthew  3341:         # FIXME: Probably ought to escape things....
1.800     albertel 3342: 	foreach my $key (keys(%env)) {
                   3343:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3344:                 my $formitem = $1;
                   3345:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3346:                     $what.=':'.$formitem.'='.$env{$key};
                   3347:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3348:                     $what.=':'.$formitem.'='.$env{$key};
                   3349:                 }
1.158     www      3350:             }
1.191     harris41 3351:         }
1.583     matthew  3352:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3353:         # FIXME: We should not be depending on a form parameter that someone
                   3354:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3355:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3356:             $what.= ':POST';
                   3357:             # FIXME: Probably ought to escape things....
                   3358:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3359:                                  'crsdiscuss') {
1.620     albertel 3360:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3361:             }
                   3362:         }
1.158     www      3363:     }
                   3364:     &courselog($what);
1.149     www      3365: }
                   3366: 
1.185     www      3367: sub countacc {
                   3368:     my $url=&declutter(shift);
1.458     matthew  3369:     return if (! defined($url) || $url eq '');
1.620     albertel 3370:     unless ($env{'request.course.id'}) { return ''; }
                   3371:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3372:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3373:     $accesshash{$key}++;
1.185     www      3374: }
1.349     www      3375: 
1.361     www      3376: sub linklog {
                   3377:     my ($from,$to)=@_;
                   3378:     $from=&declutter($from);
                   3379:     $to=&declutter($to);
                   3380:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3381:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3382: }
                   3383:   
1.349     www      3384: sub userrolelog {
                   3385:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3386:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3387:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3388:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3389:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3390:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3391:        $userrolehash
                   3392:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3393:                     =$tend.':'.$tstart;
1.662     raeburn  3394:     }
1.898     albertel 3395:     if (($env{'request.role'} =~ /dc\./) &&
                   3396: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3397: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3398: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3399:          ($trole=~/^co/))) {
1.898     albertel 3400:        $userrolehash
                   3401:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3402:                     =$tend.':'.$tstart;
                   3403:     }
1.662     raeburn  3404:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3405:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3406:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3407:         ($trole=~/^sc/)) {
                   3408:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3409:        $domainrolehash
                   3410:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3411:                     = $tend.':'.$tstart;
                   3412:     }
1.351     www      3413: }
                   3414: 
1.957     raeburn  3415: sub courserolelog {
                   3416:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3417:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3418:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3419:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3420:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3421:         ($trole eq 'co')) {
1.957     raeburn  3422:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3423:             my $cdom = $1;
                   3424:             my $cnum = $2;
                   3425:             my $sec = $3;
                   3426:             my $namespace = 'rolelog';
                   3427:             my %storehash = (
                   3428:                                role    => $trole,
                   3429:                                start   => $tstart,
                   3430:                                end     => $tend,
                   3431:                                selfenroll => $selfenroll,
                   3432:                                context    => $context,
                   3433:                             );
                   3434:             if ($trole eq 'gr') {
                   3435:                 $namespace = 'groupslog';
                   3436:                 $storehash{'group'} = $sec;
                   3437:             } else {
                   3438:                 $storehash{'section'} = $sec;
                   3439:             }
                   3440:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3441:             if (($trole ne 'st') || ($sec ne '')) {
                   3442:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3443:             }
1.957     raeburn  3444:         }
                   3445:     }
                   3446:     return;
                   3447: }
                   3448: 
1.351     www      3449: sub get_course_adv_roles {
1.948     raeburn  3450:     my ($cid,$codes) = @_;
1.620     albertel 3451:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3452:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3453:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3454:     my %nothide=();
1.800     albertel 3455:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3456:         if ($user !~ /:/) {
                   3457: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3458:         } else {
                   3459:             $nothide{$user}=1;
                   3460:         }
1.470     www      3461:     }
1.351     www      3462:     my %returnhash=();
                   3463:     my %dumphash=
                   3464:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3465:     my $now=time;
1.997     raeburn  3466:     my %privileged;
1.1000    raeburn  3467:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3468: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3469:         if (($tstart) && ($tstart<0)) { next; }
                   3470:         if (($tend) && ($tend<$now)) { next; }
                   3471:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3472:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3473: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3474:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3475:             my %dompersonnel =
1.998     raeburn  3476:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3477:             $privileged{$domain} = {};
                   3478:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3479:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3480:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3481:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3482:                         $privileged{$udom}{$uname} = 1;
                   3483:                     }
                   3484:                 }
                   3485:             }
                   3486:         }
                   3487:         if ((exists($privileged{$domain}{$username})) && 
                   3488:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3489: 	if ($role eq 'cr') { next; }
1.948     raeburn  3490:         if ($codes) {
                   3491:             if ($section) { $role .= ':'.$section; }
                   3492:             if ($returnhash{$role}) {
                   3493:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3494:             } else {
                   3495:                 $returnhash{$role}=$username.':'.$domain;
                   3496:             }
1.351     www      3497:         } else {
1.988     raeburn  3498:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3499:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3500:             if ($returnhash{$key}) {
                   3501: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3502:             } else {
                   3503:                 $returnhash{$key}=$username.':'.$domain;
                   3504:             }
1.351     www      3505:         }
1.948     raeburn  3506:     }
1.400     www      3507:     return %returnhash;
                   3508: }
                   3509: 
                   3510: sub get_my_roles {
1.937     raeburn  3511:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3512:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3513:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3514:     my (%dumphash,%nothide);
1.1086    raeburn  3515:     if ($context eq 'userroles') {
                   3516:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3517:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3518:     } else {
                   3519:         %dumphash=
1.400     www      3520:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3521:         if ($hidepriv) {
                   3522:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3523:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3524:                 if ($user !~ /:/) {
                   3525:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3526:                 } else {
                   3527:                     $nothide{$user} = 1;
                   3528:                 }
                   3529:             }
                   3530:         }
1.858     raeburn  3531:     }
1.400     www      3532:     my %returnhash=();
                   3533:     my $now=time;
1.999     raeburn  3534:     my %privileged;
1.800     albertel 3535:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3536:         my ($role,$tend,$tstart);
                   3537:         if ($context eq 'userroles') {
                   3538: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3539:         } else {
                   3540:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3541:         }
1.400     www      3542:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3543:         my $status = 'active';
1.939     raeburn  3544:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3545:             $status = 'previous';
                   3546:         } 
                   3547:         if (($tstart) && ($now<$tstart)) {
                   3548:             $status = 'future';
                   3549:         }
                   3550:         if (ref($types) eq 'ARRAY') {
                   3551:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3552:                 next;
                   3553:             } 
                   3554:         } else {
                   3555:             if ($status ne 'active') {
                   3556:                 next;
                   3557:             }
                   3558:         }
1.867     raeburn  3559:         my ($rolecode,$username,$domain,$section,$area);
                   3560:         if ($context eq 'userroles') {
                   3561:             ($area,$rolecode) = split(/_/,$entry);
                   3562:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3563:         } else {
                   3564:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3565:         }
1.832     raeburn  3566:         if (ref($roledoms) eq 'ARRAY') {
                   3567:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3568:                 next;
                   3569:             }
                   3570:         }
                   3571:         if (ref($roles) eq 'ARRAY') {
                   3572:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3573:                 if ($role =~ /^cr\//) {
                   3574:                     if (!grep(/^cr$/,@{$roles})) {
                   3575:                         next;
                   3576:                     }
1.1104    raeburn  3577:                 } elsif ($role =~ /^gr\//) {
                   3578:                     if (!grep(/^gr$/,@{$roles})) {
                   3579:                         next;
                   3580:                     }
1.922     raeburn  3581:                 } else {
                   3582:                     next;
                   3583:                 }
1.832     raeburn  3584:             }
1.867     raeburn  3585:         }
1.937     raeburn  3586:         if ($hidepriv) {
1.999     raeburn  3587:             if ($context eq 'userroles') {
                   3588:                 if ((&privileged($username,$domain)) &&
                   3589:                     (!$nothide{$username.':'.$domain})) {
                   3590:                     next;
                   3591:                 }
                   3592:             } else {
                   3593:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3594:                     my %dompersonnel =
                   3595:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3596:                     $privileged{$domain} = {};
                   3597:                     if (keys(%dompersonnel)) {
                   3598:                         foreach my $server (keys(%dompersonnel)) {
                   3599:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3600:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3601:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3602:                                     $privileged{$udom}{$uname} = $trole;
                   3603:                                 }
                   3604:                             }
                   3605:                         }
                   3606:                     }
                   3607:                 }
                   3608:                 if (exists($privileged{$domain}{$username})) {
                   3609:                     if (!$nothide{$username.':'.$domain}) {
                   3610:                         next;
                   3611:                     }
                   3612:                 }
1.937     raeburn  3613:             }
                   3614:         }
1.933     raeburn  3615:         if ($withsec) {
                   3616:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3617:                 $tstart.':'.$tend;
                   3618:         } else {
                   3619:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3620:         }
1.832     raeburn  3621:     }
1.373     www      3622:     return %returnhash;
1.399     www      3623: }
                   3624: 
                   3625: # ----------------------------------------------------- Frontpage Announcements
                   3626: #
                   3627: #
                   3628: 
                   3629: sub postannounce {
                   3630:     my ($server,$text)=@_;
1.844     albertel 3631:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3632:     unless ($text=~/\w/) { $text=''; }
                   3633:     return &reply('setannounce:'.&escape($text),$server);
                   3634: }
                   3635: 
                   3636: sub getannounce {
1.448     albertel 3637: 
                   3638:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3639: 	my $announcement='';
1.800     albertel 3640: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3641: 	close($fh);
1.399     www      3642: 	if ($announcement=~/\w/) { 
                   3643: 	    return 
                   3644:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3645:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3646: 	} else {
                   3647: 	    return '';
                   3648: 	}
                   3649:     } else {
                   3650: 	return '';
                   3651:     }
1.351     www      3652: }
1.353     www      3653: 
                   3654: # ---------------------------------------------------------- Course ID routines
                   3655: # Deal with domain's nohist_courseid.db files
                   3656: #
                   3657: 
                   3658: sub courseidput {
1.921     raeburn  3659:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3660:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3661:     my $outcome;
                   3662:     if ($caller eq 'timeonly') {
                   3663:         my $cids = '';
                   3664:         foreach my $item (keys(%$storehash)) {
                   3665:             $cids.=&escape($item).'&';
                   3666:         }
                   3667:         $cids=~s/\&$//;
                   3668:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3669:                           $coursehome);       
                   3670:     } else {
                   3671:         my $items = '';
                   3672:         foreach my $item (keys(%$storehash)) {
                   3673:             $items.= &escape($item).'='.
                   3674:                      &freeze_escape($$storehash{$item}).'&';
                   3675:         }
                   3676:         $items=~s/\&$//;
                   3677:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3678:                           $coursehome);
1.918     raeburn  3679:     }
                   3680:     if ($outcome eq 'unknown_cmd') {
                   3681:         my $what;
                   3682:         foreach my $cid (keys(%$storehash)) {
                   3683:             $what .= &escape($cid).'=';
1.921     raeburn  3684:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3685:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3686:             }
                   3687:             $what =~ s/\:$/&/;
                   3688:         }
                   3689:         $what =~ s/\&$//;  
                   3690:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3691:     } else {
                   3692:         return $outcome;
                   3693:     }
1.353     www      3694: }
                   3695: 
                   3696: sub courseiddump {
1.921     raeburn  3697:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3698:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3699:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3700:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3701:     my $as_hash = 1;
                   3702:     my %returnhash;
                   3703:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3704:     my %libserv = &all_library();
                   3705:     foreach my $tryserver (keys(%libserv)) {
                   3706:         if ( (  $hostidflag == 1 
                   3707: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3708: 	     || (!defined($hostidflag)) ) {
                   3709: 
1.918     raeburn  3710: 	    if (($domfilter eq '') ||
                   3711: 		(&host_domain($tryserver) eq $domfilter)) {
                   3712:                 my $rep = 
                   3713:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3714:                          $sincefilter.':'.&escape($descfilter).':'.
                   3715:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3716:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3717:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3718:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3719:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3720:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3721:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3722:                          &escape($creationcontext).':'.$domcloner,
                   3723:                          $tryserver);
1.918     raeburn  3724:                 my @pairs=split(/\&/,$rep);
                   3725:                 foreach my $item (@pairs) {
                   3726:                     my ($key,$value)=split(/\=/,$item,2);
                   3727:                     $key = &unescape($key);
                   3728:                     next if ($key =~ /^error: 2 /);
                   3729:                     my $result = &thaw_unescape($value);
                   3730:                     if (ref($result) eq 'HASH') {
                   3731:                         $returnhash{$key}=$result;
                   3732:                     } else {
1.921     raeburn  3733:                         my @responses = split(/:/,$value);
                   3734:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3735:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3736:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3737:                         }
1.1008    raeburn  3738:                     }
1.353     www      3739:                 }
                   3740:             }
                   3741:         }
                   3742:     }
                   3743:     return %returnhash;
                   3744: }
                   3745: 
1.1055    raeburn  3746: sub courselastaccess {
                   3747:     my ($cdom,$cnum,$hostidref) = @_;
                   3748:     my %returnhash;
                   3749:     if ($cdom && $cnum) {
                   3750:         my $chome = &homeserver($cnum,$cdom);
                   3751:         if ($chome ne 'no_host') {
                   3752:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3753:             &extract_lastaccess(\%returnhash,$rep);
                   3754:         }
                   3755:     } else {
                   3756:         if (!$cdom) { $cdom=''; }
                   3757:         my %libserv = &all_library();
                   3758:         foreach my $tryserver (keys(%libserv)) {
                   3759:             if (ref($hostidref) eq 'ARRAY') {
                   3760:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3761:             } 
                   3762:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3763:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3764:                 &extract_lastaccess(\%returnhash,$rep);
                   3765:             }
                   3766:         }
                   3767:     }
                   3768:     return %returnhash;
                   3769: }
                   3770: 
                   3771: sub extract_lastaccess {
                   3772:     my ($returnhash,$rep) = @_;
                   3773:     if (ref($returnhash) eq 'HASH') {
                   3774:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3775:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3776:                  $rep eq '') {
                   3777:             my @pairs=split(/\&/,$rep);
                   3778:             foreach my $item (@pairs) {
                   3779:                 my ($key,$value)=split(/\=/,$item,2);
                   3780:                 $key = &unescape($key);
                   3781:                 next if ($key =~ /^error: 2 /);
                   3782:                 $returnhash->{$key} = &thaw_unescape($value);
                   3783:             }
                   3784:         }
                   3785:     }
                   3786:     return;
                   3787: }
                   3788: 
1.658     raeburn  3789: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3790: 
                   3791: sub dcmailput {
1.685     raeburn  3792:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3793:     my $status = &Apache::lonnet::critical(
1.740     www      3794:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3795:        &escape($message),$server);
1.662     raeburn  3796:     return $status;
                   3797: }
                   3798: 
1.658     raeburn  3799: sub dcmaildump {
                   3800:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3801:     my %returnhash=();
1.846     albertel 3802: 
                   3803:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3804:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3805:                                                          &escape($enddate).':';
                   3806: 	my @esc_senders=map { &escape($_)} @$senders;
                   3807: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3808: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3809:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3810:             if (($key) && ($value)) {
                   3811:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3812:             }
                   3813:         }
                   3814:     }
                   3815:     return %returnhash;
                   3816: }
1.662     raeburn  3817: # ---------------------------------------------------------- Domain roles
                   3818: 
                   3819: sub get_domain_roles {
                   3820:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3821:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3822:         $startdate = '.';
                   3823:     }
1.1018    raeburn  3824:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3825:         $enddate = '.';
                   3826:     }
1.922     raeburn  3827:     my $rolelist;
                   3828:     if (ref($roles) eq 'ARRAY') {
                   3829:         $rolelist = join(':',@{$roles});
                   3830:     }
1.662     raeburn  3831:     my %personnel = ();
1.841     albertel 3832: 
                   3833:     my %servers = &get_servers($dom,'library');
                   3834:     foreach my $tryserver (keys(%servers)) {
                   3835: 	%{$personnel{$tryserver}}=();
                   3836: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3837: 					    &escape($startdate).':'.
                   3838: 					    &escape($enddate).':'.
                   3839: 					    &escape($rolelist), $tryserver))) {
                   3840: 	    my ($key,$value) = split(/\=/,$line,2);
                   3841: 	    if (($key) && ($value)) {
                   3842: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3843: 	    }
                   3844: 	}
1.662     raeburn  3845:     }
                   3846:     return %personnel;
                   3847: }
1.658     raeburn  3848: 
1.1057    www      3849: # ----------------------------------------------------------- Interval timing 
1.149     www      3850: 
1.504     albertel 3851: sub get_first_access {
                   3852:     my ($type,$argsymb)=@_;
1.790     albertel 3853:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3854:     if ($argsymb) { $symb=$argsymb; }
                   3855:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3856:     if ($type eq 'course') {
                   3857: 	$res='course';
                   3858:     } elsif ($type eq 'map') {
1.588     albertel 3859: 	$res=&symbread($map);
                   3860:     } else {
                   3861: 	$res=$symb;
                   3862:     }
                   3863:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3864:     return $times{"$courseid\0$res"};
1.504     albertel 3865: }
                   3866: 
                   3867: sub set_first_access {
                   3868:     my ($type)=@_;
1.790     albertel 3869:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3870:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3871:     if ($type eq 'course') {
                   3872: 	$res='course';
                   3873:     } elsif ($type eq 'map') {
1.588     albertel 3874: 	$res=&symbread($map);
                   3875:     } else {
                   3876: 	$res=$symb;
                   3877:     }
                   3878:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3879:     if (!$firstaccess) {
1.588     albertel 3880: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3881:     }
                   3882:     return 'already_set';
1.504     albertel 3883: }
                   3884: 
1.110     www      3885: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3886: 
                   3887: sub expirespread {
                   3888:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3889:     my $cid=$env{'request.course.id'}; 
1.110     www      3890:     if ($cid) {
                   3891:        my $now=time;
                   3892:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3893:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3894:                             $env{'course.'.$cid.'.num'}.
1.110     www      3895: 	        	    ':nohist_expirationdates:'.
                   3896:                             &escape($key).'='.$now,
1.620     albertel 3897:                             $env{'course.'.$cid.'.home'})
1.110     www      3898:     }
                   3899:     return 'ok';
1.14      www      3900: }
                   3901: 
1.109     www      3902: # ----------------------------------------------------- Devalidate Spreadsheets
                   3903: 
                   3904: sub devalidate {
1.325     www      3905:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3906:     my $cid=$env{'request.course.id'}; 
1.109     www      3907:     if ($cid) {
1.391     matthew  3908:         # delete the stored spreadsheets for
                   3909:         # - the student level sheet of this user in course's homespace
                   3910:         # - the assessment level sheet for this resource 
                   3911:         #   for this user in user's homespace
1.553     albertel 3912: 	# - current conditional state info
1.325     www      3913: 	my $key=$uname.':'.$udom.':';
1.109     www      3914:         my $status=
1.299     matthew  3915: 	    &del('nohist_calculatedsheets',
1.391     matthew  3916: 		 [$key.'studentcalc:'],
1.620     albertel 3917: 		 $env{'course.'.$cid.'.domain'},
                   3918: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3919: 		.' '.
                   3920: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3921: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3922:         unless ($status eq 'ok ok') {
                   3923:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3924:                     $uname.' at '.$udom.' for '.
1.109     www      3925: 		    $symb.': '.$status);
1.133     albertel 3926:         }
1.553     albertel 3927: 	&delenv('user.state.'.$cid);
1.109     www      3928:     }
                   3929: }
                   3930: 
1.265     albertel 3931: sub get_scalar {
                   3932:     my ($string,$end) = @_;
                   3933:     my $value;
                   3934:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3935: 	$value = $1;
                   3936:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3937: 	$value = $1;
                   3938:     }
                   3939:     return &unescape($value);
                   3940: }
                   3941: 
                   3942: sub array2str {
                   3943:   my (@array) = @_;
                   3944:   my $result=&arrayref2str(\@array);
                   3945:   $result=~s/^__ARRAY_REF__//;
                   3946:   $result=~s/__END_ARRAY_REF__$//;
                   3947:   return $result;
                   3948: }
                   3949: 
1.204     albertel 3950: sub arrayref2str {
                   3951:   my ($arrayref) = @_;
1.265     albertel 3952:   my $result='__ARRAY_REF__';
1.204     albertel 3953:   foreach my $elem (@$arrayref) {
1.265     albertel 3954:     if(ref($elem) eq 'ARRAY') {
                   3955:       $result.=&arrayref2str($elem).'&';
                   3956:     } elsif(ref($elem) eq 'HASH') {
                   3957:       $result.=&hashref2str($elem).'&';
                   3958:     } elsif(ref($elem)) {
                   3959:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3960:     } else {
                   3961:       $result.=&escape($elem).'&';
                   3962:     }
                   3963:   }
                   3964:   $result=~s/\&$//;
1.265     albertel 3965:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3966:   return $result;
                   3967: }
                   3968: 
1.168     albertel 3969: sub hash2str {
1.204     albertel 3970:   my (%hash) = @_;
                   3971:   my $result=&hashref2str(\%hash);
1.265     albertel 3972:   $result=~s/^__HASH_REF__//;
                   3973:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3974:   return $result;
                   3975: }
                   3976: 
                   3977: sub hashref2str {
                   3978:   my ($hashref)=@_;
1.265     albertel 3979:   my $result='__HASH_REF__';
1.800     albertel 3980:   foreach my $key (sort(keys(%$hashref))) {
                   3981:     if (ref($key) eq 'ARRAY') {
                   3982:       $result.=&arrayref2str($key).'=';
                   3983:     } elsif (ref($key) eq 'HASH') {
                   3984:       $result.=&hashref2str($key).'=';
                   3985:     } elsif (ref($key)) {
1.265     albertel 3986:       $result.='=';
1.800     albertel 3987:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3988:     } else {
1.1132    raeburn  3989: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3990:     }
                   3991: 
1.800     albertel 3992:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3993:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3994:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3995:       $result.=&hashref2str($hashref->{$key}).'&';
                   3996:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3997:        $result.='&';
1.800     albertel 3998:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3999:     } else {
1.800     albertel 4000:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4001:     }
                   4002:   }
1.168     albertel 4003:   $result=~s/\&$//;
1.265     albertel 4004:   $result .= '__END_HASH_REF__';
1.168     albertel 4005:   return $result;
                   4006: }
                   4007: 
                   4008: sub str2hash {
1.265     albertel 4009:     my ($string)=@_;
                   4010:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4011:     return %$hash;
                   4012: }
                   4013: 
                   4014: sub str2hashref {
1.168     albertel 4015:   my ($string) = @_;
1.265     albertel 4016: 
                   4017:   my %hash;
                   4018: 
                   4019:   if($string !~ /^__HASH_REF__/) {
                   4020:       if (! ($string eq '' || !defined($string))) {
                   4021: 	  $hash{'error'}='Not hash reference';
                   4022:       }
                   4023:       return (\%hash, $string);
                   4024:   }
                   4025: 
                   4026:   $string =~ s/^__HASH_REF__//;
                   4027: 
                   4028:   while($string !~ /^__END_HASH_REF__/) {
                   4029:       #key
                   4030:       my $key='';
                   4031:       if($string =~ /^__HASH_REF__/) {
                   4032:           ($key, $string)=&str2hashref($string);
                   4033:           if(defined($key->{'error'})) {
                   4034:               $hash{'error'}='Bad data';
                   4035:               return (\%hash, $string);
                   4036:           }
                   4037:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4038:           ($key, $string)=&str2arrayref($string);
                   4039:           if($key->[0] eq 'Array reference error') {
                   4040:               $hash{'error'}='Bad data';
                   4041:               return (\%hash, $string);
                   4042:           }
                   4043:       } else {
                   4044:           $string =~ s/^(.*?)=//;
1.267     albertel 4045: 	  $key=&unescape($1);
1.265     albertel 4046:       }
                   4047:       $string =~ s/^=//;
                   4048: 
                   4049:       #value
                   4050:       my $value='';
                   4051:       if($string =~ /^__HASH_REF__/) {
                   4052:           ($value, $string)=&str2hashref($string);
                   4053:           if(defined($value->{'error'})) {
                   4054:               $hash{'error'}='Bad data';
                   4055:               return (\%hash, $string);
                   4056:           }
                   4057:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4058:           ($value, $string)=&str2arrayref($string);
                   4059:           if($value->[0] eq 'Array reference error') {
                   4060:               $hash{'error'}='Bad data';
                   4061:               return (\%hash, $string);
                   4062:           }
                   4063:       } else {
                   4064: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4065:       }
                   4066:       $string =~ s/^&//;
                   4067: 
                   4068:       $hash{$key}=$value;
1.204     albertel 4069:   }
1.265     albertel 4070: 
                   4071:   $string =~ s/^__END_HASH_REF__//;
                   4072: 
                   4073:   return (\%hash, $string);
1.204     albertel 4074: }
                   4075: 
                   4076: sub str2array {
1.265     albertel 4077:     my ($string)=@_;
                   4078:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4079:     return @$array;
                   4080: }
                   4081: 
                   4082: sub str2arrayref {
1.204     albertel 4083:   my ($string) = @_;
1.265     albertel 4084:   my @array;
                   4085: 
                   4086:   if($string !~ /^__ARRAY_REF__/) {
                   4087:       if (! ($string eq '' || !defined($string))) {
                   4088: 	  $array[0]='Array reference error';
                   4089:       }
                   4090:       return (\@array, $string);
                   4091:   }
                   4092: 
                   4093:   $string =~ s/^__ARRAY_REF__//;
                   4094: 
                   4095:   while($string !~ /^__END_ARRAY_REF__/) {
                   4096:       my $value='';
                   4097:       if($string =~ /^__HASH_REF__/) {
                   4098:           ($value, $string)=&str2hashref($string);
                   4099:           if(defined($value->{'error'})) {
                   4100:               $array[0] ='Array reference error';
                   4101:               return (\@array, $string);
                   4102:           }
                   4103:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4104:           ($value, $string)=&str2arrayref($string);
                   4105:           if($value->[0] eq 'Array reference error') {
                   4106:               $array[0] ='Array reference error';
                   4107:               return (\@array, $string);
                   4108:           }
                   4109:       } else {
                   4110: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4111:       }
                   4112:       $string =~ s/^&//;
                   4113: 
                   4114:       push(@array, $value);
1.191     harris41 4115:   }
1.265     albertel 4116: 
                   4117:   $string =~ s/^__END_ARRAY_REF__//;
                   4118: 
                   4119:   return (\@array, $string);
1.168     albertel 4120: }
                   4121: 
1.167     albertel 4122: # -------------------------------------------------------------------Temp Store
                   4123: 
1.168     albertel 4124: sub tmpreset {
                   4125:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4126:   if (!$symb) {
                   4127:     $symb=&symbread();
1.620     albertel 4128:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4129:   }
                   4130:   $symb=escape($symb);
                   4131: 
1.620     albertel 4132:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4133:   $namespace=~s/\//\_/g;
                   4134:   $namespace=~s/\W//g;
                   4135: 
1.620     albertel 4136:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4137:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4138:   if ($domain eq 'public' && $stuname eq 'public') {
                   4139:       $stuname=$ENV{'REMOTE_ADDR'};
                   4140:   }
1.1117    foxr     4141:   my $path=LONCAPA::tempdir();
1.168     albertel 4142:   my %hash;
                   4143:   if (tie(%hash,'GDBM_File',
                   4144: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4145: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4146:     foreach my $key (keys(%hash)) {
1.180     albertel 4147:       if ($key=~ /:$symb/) {
1.168     albertel 4148: 	delete($hash{$key});
                   4149:       }
                   4150:     }
                   4151:   }
                   4152: }
                   4153: 
1.167     albertel 4154: sub tmpstore {
1.168     albertel 4155:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4156: 
                   4157:   if (!$symb) {
                   4158:     $symb=&symbread();
1.620     albertel 4159:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4160:   }
                   4161:   $symb=escape($symb);
                   4162: 
                   4163:   if (!$namespace) {
                   4164:     # I don't think we would ever want to store this for a course.
                   4165:     # it seems this will only be used if we don't have a course.
1.620     albertel 4166:     #$namespace=$env{'request.course.id'};
1.168     albertel 4167:     #if (!$namespace) {
1.620     albertel 4168:       $namespace=$env{'request.state'};
1.168     albertel 4169:     #}
                   4170:   }
                   4171:   $namespace=~s/\//\_/g;
                   4172:   $namespace=~s/\W//g;
1.620     albertel 4173:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4174:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4175:   if ($domain eq 'public' && $stuname eq 'public') {
                   4176:       $stuname=$ENV{'REMOTE_ADDR'};
                   4177:   }
1.168     albertel 4178:   my $now=time;
                   4179:   my %hash;
1.1117    foxr     4180:   my $path=LONCAPA::tempdir();
1.168     albertel 4181:   if (tie(%hash,'GDBM_File',
                   4182: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4183: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4184:     $hash{"version:$symb"}++;
                   4185:     my $version=$hash{"version:$symb"};
                   4186:     my $allkeys=''; 
                   4187:     foreach my $key (keys(%$storehash)) {
                   4188:       $allkeys.=$key.':';
1.591     albertel 4189:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4190:     }
                   4191:     $hash{"$version:$symb:timestamp"}=$now;
                   4192:     $allkeys.='timestamp';
                   4193:     $hash{"$version:keys:$symb"}=$allkeys;
                   4194:     if (untie(%hash)) {
                   4195:       return 'ok';
                   4196:     } else {
                   4197:       return "error:$!";
                   4198:     }
                   4199:   } else {
                   4200:     return "error:$!";
                   4201:   }
                   4202: }
1.167     albertel 4203: 
1.168     albertel 4204: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4205: 
1.168     albertel 4206: sub tmprestore {
                   4207:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4208: 
1.168     albertel 4209:   if (!$symb) {
                   4210:     $symb=&symbread();
1.620     albertel 4211:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4212:   }
                   4213:   $symb=escape($symb);
                   4214: 
1.620     albertel 4215:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4216: 
1.620     albertel 4217:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4218:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4219:   if ($domain eq 'public' && $stuname eq 'public') {
                   4220:       $stuname=$ENV{'REMOTE_ADDR'};
                   4221:   }
1.168     albertel 4222:   my %returnhash;
                   4223:   $namespace=~s/\//\_/g;
                   4224:   $namespace=~s/\W//g;
                   4225:   my %hash;
1.1117    foxr     4226:   my $path=LONCAPA::tempdir();
1.168     albertel 4227:   if (tie(%hash,'GDBM_File',
                   4228: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4229: 	  &GDBM_READER(),0640)) {
1.168     albertel 4230:     my $version=$hash{"version:$symb"};
                   4231:     $returnhash{'version'}=$version;
                   4232:     my $scope;
                   4233:     for ($scope=1;$scope<=$version;$scope++) {
                   4234:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4235:       my @keys=split(/:/,$vkeys);
                   4236:       my $key;
                   4237:       $returnhash{"$scope:keys"}=$vkeys;
                   4238:       foreach $key (@keys) {
1.591     albertel 4239: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4240: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4241:       }
                   4242:     }
1.168     albertel 4243:     if (!(untie(%hash))) {
                   4244:       return "error:$!";
                   4245:     }
                   4246:   } else {
                   4247:     return "error:$!";
                   4248:   }
                   4249:   return %returnhash;
1.167     albertel 4250: }
                   4251: 
1.9       www      4252: # ----------------------------------------------------------------------- Store
                   4253: 
                   4254: sub store {
1.124     www      4255:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4256:     my $home='';
                   4257: 
1.168     albertel 4258:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4259: 
1.213     www      4260:     $symb=&symbclean($symb);
1.122     albertel 4261:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4262: 
1.620     albertel 4263:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4264:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4265: 
                   4266:     &devalidate($symb,$stuname,$domain);
1.109     www      4267: 
                   4268:     $symb=escape($symb);
1.187     www      4269:     if (!$namespace) { 
1.620     albertel 4270:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4271:           return ''; 
                   4272:        } 
                   4273:     }
1.620     albertel 4274:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4275: 
                   4276:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4277:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4278: 
1.12      www      4279:     my $namevalue='';
1.800     albertel 4280:     foreach my $key (keys(%$storehash)) {
                   4281:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4282:     }
1.12      www      4283:     $namevalue=~s/\&$//;
1.187     www      4284:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4285:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4286: }
                   4287: 
1.47      www      4288: # -------------------------------------------------------------- Critical Store
                   4289: 
                   4290: sub cstore {
1.124     www      4291:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4292:     my $home='';
                   4293: 
1.168     albertel 4294:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4295: 
1.213     www      4296:     $symb=&symbclean($symb);
1.122     albertel 4297:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4298: 
1.620     albertel 4299:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4300:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4301: 
                   4302:     &devalidate($symb,$stuname,$domain);
1.109     www      4303: 
                   4304:     $symb=escape($symb);
1.187     www      4305:     if (!$namespace) { 
1.620     albertel 4306:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4307:           return ''; 
                   4308:        } 
                   4309:     }
1.620     albertel 4310:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4311: 
                   4312:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4313:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4314: 
1.47      www      4315:     my $namevalue='';
1.800     albertel 4316:     foreach my $key (keys(%$storehash)) {
                   4317:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4318:     }
1.47      www      4319:     $namevalue=~s/\&$//;
1.187     www      4320:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4321:     return critical
                   4322:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4323: }
                   4324: 
1.9       www      4325: # --------------------------------------------------------------------- Restore
                   4326: 
                   4327: sub restore {
1.124     www      4328:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4329:     my $home='';
                   4330: 
1.168     albertel 4331:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4332: 
1.122     albertel 4333:     if (!$symb) {
                   4334:       unless ($symb=escape(&symbread())) { return ''; }
                   4335:     } else {
1.213     www      4336:       $symb=&escape(&symbclean($symb));
1.122     albertel 4337:     }
1.188     www      4338:     if (!$namespace) { 
1.620     albertel 4339:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4340:           return ''; 
                   4341:        } 
                   4342:     }
1.620     albertel 4343:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4344:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4345:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4346:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4347: 
1.12      www      4348:     my %returnhash=();
1.800     albertel 4349:     foreach my $line (split(/\&/,$answer)) {
                   4350: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4351:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4352:     }
1.75      www      4353:     my $version;
                   4354:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4355:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4356:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4357:        }
1.75      www      4358:     }
1.13      www      4359:     return %returnhash;
1.34      www      4360: }
                   4361: 
                   4362: # ---------------------------------------------------------- Course Description
1.1118    foxr     4363: #
                   4364: #  
1.34      www      4365: 
                   4366: sub coursedescription {
1.731     albertel 4367:     my ($courseid,$args)=@_;
1.34      www      4368:     $courseid=~s/^\///;
1.49      www      4369:     $courseid=~s/\_/\//g;
1.34      www      4370:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4371:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4372:     my $normalid=$cdomain.'_'.$cnum;
                   4373:     # need to always cache even if we get errors otherwise we keep 
                   4374:     # trying and trying and trying to get the course description.
                   4375:     my %envhash=();
                   4376:     my %returnhash=();
1.731     albertel 4377:     
                   4378:     my $expiretime=600;
                   4379:     if ($env{'request.course.id'} eq $normalid) {
                   4380: 	$expiretime=120;
                   4381:     }
                   4382: 
                   4383:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4384:     if (!$args->{'freshen_cache'}
                   4385: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4386: 	foreach my $key (keys(%env)) {
                   4387: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4388: 	    my ($setting) = $1;
                   4389: 	    $returnhash{$setting} = $env{$key};
                   4390: 	}
                   4391: 	return %returnhash;
                   4392:     }
                   4393: 
1.1118    foxr     4394:     # get the data again
                   4395: 
1.731     albertel 4396:     if (!$args->{'one_time'}) {
                   4397: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4398:     }
1.811     albertel 4399: 
1.34      www      4400:     if ($chome ne 'no_host') {
1.302     albertel 4401:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4402:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4403: 	   my $username = $env{'user.name'}; # Defult username
                   4404: 	   if(defined $args->{'user'}) {
                   4405: 	       $username = $args->{'user'};
                   4406: 	   }
1.129     albertel 4407:            $returnhash{'home'}= $chome;
                   4408: 	   $returnhash{'domain'} = $cdomain;
                   4409: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4410:            if (!defined($returnhash{'type'})) {
                   4411:                $returnhash{'type'} = 'Course';
                   4412:            }
1.130     albertel 4413:            while (my ($name,$value) = each %returnhash) {
1.53      www      4414:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4415:            }
1.270     www      4416:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4417:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4418: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4419:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4420:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4421:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4422:        }
                   4423:     }
1.731     albertel 4424:     if (!$args->{'one_time'}) {
1.949     raeburn  4425: 	&appenv(\%envhash);
1.731     albertel 4426:     }
1.302     albertel 4427:     return %returnhash;
1.461     www      4428: }
                   4429: 
1.1080    raeburn  4430: sub update_released_required {
                   4431:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4432:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4433:         $cid = $env{'request.course.id'};
                   4434:         $cdom = $env{'course.'.$cid.'.domain'};
                   4435:         $cnum = $env{'course.'.$cid.'.num'};
                   4436:         $chome = $env{'course.'.$cid.'.home'};
                   4437:     }
                   4438:     if ($needsrelease) {
                   4439:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4440:         my $needsupdate;
                   4441:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4442:             $needsupdate = 1;
                   4443:         } else {
                   4444:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4445:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4446:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4447:                 $needsupdate = 1;
                   4448:             }
                   4449:         }
                   4450:         if ($needsupdate) {
                   4451:             my %needshash = (
                   4452:                              'internal.releaserequired' => $needsrelease,
                   4453:                             );
                   4454:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4455:             if ($putresult eq 'ok') {
                   4456:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4457:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4458:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4459:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4460:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4461:                 }
                   4462:             }
                   4463:         }
                   4464:     }
                   4465:     return;
                   4466: }
                   4467: 
1.461     www      4468: # -------------------------------------------------See if a user is privileged
                   4469: 
                   4470: sub privileged {
                   4471:     my ($username,$domain)=@_;
                   4472:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4473: 			&homeserver($username,$domain));
1.1033    raeburn  4474:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4475:         ($rolesdump =~ /^error:/)) {
                   4476:         return 0;
                   4477:     }
1.461     www      4478:     my $now=time;
                   4479:     if ($rolesdump ne '') {
1.800     albertel 4480:         foreach my $entry (split(/&/,$rolesdump)) {
                   4481: 	    if ($entry!~/^rolesdef_/) {
                   4482: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4483: 		$area=~s/\_\w\w$//;
                   4484: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4485: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4486: 		    my $active=1;
                   4487: 		    if ($tend) {
                   4488: 			if ($tend<$now) { $active=0; }
                   4489: 		    }
                   4490: 		    if ($tstart) {
                   4491: 			if ($tstart>$now) { $active=0; }
                   4492: 		    }
                   4493: 		    if ($active) { return 1; }
                   4494: 		}
                   4495: 	    }
                   4496: 	}
                   4497:     }
                   4498:     return 0;
1.9       www      4499: }
1.1       albertel 4500: 
1.103     harris41 4501: # -------------------------------------------------------- Get user privileges
1.11      www      4502: 
                   4503: sub rolesinit {
                   4504:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4505:     my $now=time;
                   4506:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4507:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4508:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4509:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4510:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4511:         return \%userroles;
                   4512:     }
1.11      www      4513:     my %allroles=();
1.678     raeburn  4514:     my %allgroups=();   
1.11      www      4515: 
                   4516:     if ($rolesdump ne '') {
1.800     albertel 4517:         foreach my $entry (split(/&/,$rolesdump)) {
                   4518: 	  if ($entry!~/^rolesdef_/) {
                   4519:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4520: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4521:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4522: 	    if ($role=~/^cr/) { 
1.807     albertel 4523: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4524: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4525: 		    ($tend,$tstart)=split('_',$trest);
                   4526: 		} else {
                   4527: 		    $trole=$role;
                   4528: 		}
1.678     raeburn  4529:             } elsif ($role =~ m|^gr/|) {
                   4530:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4531:                 next if ($tstart eq '-1');
1.678     raeburn  4532:                 ($trole,$group_privs) = split(/\//,$trole);
                   4533:                 $group_privs = &unescape($group_privs);
1.587     albertel 4534: 	    } else {
                   4535: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4536: 	    }
1.743     albertel 4537: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4538: 					 $username);
                   4539: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4540:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4541:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4542:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4543: 		my $spec=$trole.'.'.$area;
                   4544: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4545: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4546:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4547:                 } elsif ($trole eq 'gr') {
                   4548:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4549: 		} else {
1.567     raeburn  4550:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4551: 		}
1.12      www      4552:             }
1.662     raeburn  4553:           }
1.191     harris41 4554:         }
1.743     albertel 4555:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4556:         $userroles{'user.adv'}    = $adv;
                   4557: 	$userroles{'user.author'} = $author;
1.620     albertel 4558:         $env{'user.adv'}=$adv;
1.11      www      4559:     }
1.743     albertel 4560:     return \%userroles;  
1.11      www      4561: }
                   4562: 
1.567     raeburn  4563: sub set_arearole {
                   4564:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4565: # log the associated role with the area
                   4566:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4567:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4568: }
                   4569: 
                   4570: sub custom_roleprivs {
                   4571:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4572:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4573:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4574:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4575:         my ($rdummy,$roledef)=
                   4576:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4577:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4578:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4579:             if (defined($syspriv)) {
1.1043    raeburn  4580:                 if ($trest =~ /^$match_community$/) {
                   4581:                     $syspriv =~ s/bre\&S//; 
                   4582:                 }
1.567     raeburn  4583:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4584:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4585:             }
                   4586:             if ($tdomain ne '') {
                   4587:                 if (defined($dompriv)) {
                   4588:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4589:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4590:                 }
                   4591:                 if (($trest ne '') && (defined($coursepriv))) {
                   4592:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4593:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4594:                 }
                   4595:             }
                   4596:         }
                   4597:     }
                   4598: }
                   4599: 
1.678     raeburn  4600: sub group_roleprivs {
                   4601:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4602:     my $access = 1;
                   4603:     my $now = time;
                   4604:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4605:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4606:     if ($access) {
1.811     albertel 4607:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4608:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4609:     }
                   4610: }
1.567     raeburn  4611: 
                   4612: sub standard_roleprivs {
                   4613:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4614:     if (defined($pr{$trole.':s'})) {
                   4615:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4616:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4617:     }
                   4618:     if ($tdomain ne '') {
                   4619:         if (defined($pr{$trole.':d'})) {
                   4620:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4621:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4622:         }
                   4623:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4624:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4625:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4626:         }
                   4627:     }
                   4628: }
                   4629: 
                   4630: sub set_userprivs {
1.1064    raeburn  4631:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4632:     my $author=0;
                   4633:     my $adv=0;
1.678     raeburn  4634:     my %grouproles = ();
                   4635:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4636:         my @groupkeys; 
1.1000    raeburn  4637:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4638:             push(@groupkeys,$role);
                   4639:         }
                   4640:         if (ref($groups_roles) eq 'HASH') {
                   4641:             foreach my $key (keys(%{$groups_roles})) {
                   4642:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4643:                     push(@groupkeys,$key);
                   4644:                 }
                   4645:             }
                   4646:         }
                   4647:         if (@groupkeys > 0) {
                   4648:             foreach my $role (@groupkeys) {
                   4649:                 my ($trole,$area,$sec,$extendedarea);
                   4650:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4651:                     $trole = $1;
                   4652:                     $area = $2;
                   4653:                     $sec = $3;
                   4654:                     $extendedarea = $area.$sec;
                   4655:                     if (exists($$allgroups{$area})) {
                   4656:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4657:                             my $spec = $trole.'.'.$extendedarea;
                   4658:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4659:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4660:                         }
1.678     raeburn  4661:                     }
                   4662:                 }
                   4663:             }
                   4664:         }
                   4665:     }
1.800     albertel 4666:     foreach my $group (keys(%grouproles)) {
                   4667:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4668:     }
1.800     albertel 4669:     foreach my $role (keys(%{$allroles})) {
                   4670:         my %thesepriv;
1.941     raeburn  4671:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4672:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4673:             if ($item ne '') {
                   4674:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4675:                 if ($restrictions eq '') {
                   4676:                     $thesepriv{$privilege}='F';
                   4677:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4678:                     $thesepriv{$privilege}.=$restrictions;
                   4679:                 }
                   4680:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4681:             }
                   4682:         }
                   4683:         my $thesestr='';
1.1104    raeburn  4684:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4685: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4686: 	}
                   4687:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4688:     }
                   4689:     return ($author,$adv);
                   4690: }
                   4691: 
1.994     raeburn  4692: sub role_status {
1.1104    raeburn  4693:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4694:     my @pwhere = ();
                   4695:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4696:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4697:         unless (!defined($$role) || $$role eq '') {
                   4698:             $$where=join('.',@pwhere);
                   4699:             $$trolecode=$$role.'.'.$$where;
                   4700:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4701:             $$tstatus='is';
1.1104    raeburn  4702:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4703:                 $$tstatus='future';
1.1034    raeburn  4704:                 if ($$tstart<$now) {
                   4705:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4706:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4707:                             my (%allroles,%allgroups,$group_privs,
                   4708:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4709:                             my %userroles = (
                   4710:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4711:                             );
1.1064    raeburn  4712:                             @rolecodes = ('cm'); 
1.1002    raeburn  4713:                             my $spec=$$role.'.'.$$where;
                   4714:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4715:                             if ($$role =~ /^cr\//) {
                   4716:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4717:                                 push(@rolecodes,'cr');
1.1002    raeburn  4718:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4719:                                 push(@rolecodes,$$role);
1.1002    raeburn  4720:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4721:                                                     $env{'user.name'});
1.1064    raeburn  4722:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4723:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4724:                                 $group_privs = &unescape($group_privs);
                   4725:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4726:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  4727:                                 &get_groups_roles($tdomain,$trest,
                   4728:                                                   \%course_roles,\@rolecodes,
                   4729:                                                   \%groups_roles);
1.1002    raeburn  4730:                             } else {
1.1064    raeburn  4731:                                 push(@rolecodes,$$role);
1.1002    raeburn  4732:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4733:                             }
1.1064    raeburn  4734:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4735:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4736:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4737:                         }
                   4738:                     }
1.1034    raeburn  4739:                     $$tstatus = 'is';
1.1002    raeburn  4740:                 }
1.994     raeburn  4741:             }
                   4742:             if ($$tend) {
1.1104    raeburn  4743:                 if ($$tend<$update) {
1.994     raeburn  4744:                     $$tstatus='expired';
                   4745:                 } elsif ($$tend<$now) {
                   4746:                     $$tstatus='will_not';
                   4747:                 }
                   4748:             }
                   4749:         }
                   4750:     }
                   4751: }
                   4752: 
1.1104    raeburn  4753: sub get_groups_roles {
                   4754:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4755:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4756:                   (ref($rolecodes) eq 'ARRAY') && 
                   4757:                   (ref($groups_roles) eq 'HASH')); 
                   4758:     if (keys(%{$cdom_courseroles}) > 0) {
                   4759:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4760:         if ($cdom ne '' && $cnum ne '') {
                   4761:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4762:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4763:                     my $crsrole = $1;
                   4764:                     my $crssec = $2;
                   4765:                     if ($crsrole =~ /^cr/) {
                   4766:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4767:                             push(@{$rolecodes},'cr');
                   4768:                         }
                   4769:                     } else {
                   4770:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4771:                             push(@{$rolecodes},$crsrole);
                   4772:                         }
                   4773:                     }
                   4774:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4775:                     if ($crssec ne '') {
                   4776:                         $rolekey .= "/$crssec";
                   4777:                     }
                   4778:                     $rolekey .= './';
                   4779:                     $groups_roles->{$rolekey} = $rolecodes;
                   4780:                 }
                   4781:             }
                   4782:         }
                   4783:     }
                   4784:     return;
                   4785: }
                   4786: 
                   4787: sub delete_env_groupprivs {
                   4788:     my ($where,$courseroles,$possroles) = @_;
                   4789:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4790:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4791:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4792:         %{$courseroles->{$udom}} =
                   4793:             &get_my_roles('','','userroles',['active'],
                   4794:                           $possroles,[$udom],1);
                   4795:     }
                   4796:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4797:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4798:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4799:             my $area = '/'.$cdom.'/'.$cnum;
                   4800:             my $privkey = "user.priv.$crsrole.$area";
                   4801:             if ($crssec ne '') {
                   4802:                 $privkey .= '/'.$crssec;
                   4803:             }
                   4804:             $privkey .= ".$area/$group";
                   4805:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4806:         }
                   4807:     }
                   4808:     return;
                   4809: }
                   4810: 
1.994     raeburn  4811: sub check_adhoc_privs {
1.1104    raeburn  4812:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4813:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4814:     if ($env{$cckey}) {
                   4815:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4816:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4817:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4818:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4819:         }
                   4820:     } else {
1.1088    raeburn  4821:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4822:     }
                   4823: }
                   4824: 
                   4825: sub set_adhoc_privileges {
                   4826: # role can be cc or ca
1.1088    raeburn  4827:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4828:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4829:     my $spec = $role.'.'.$area;
                   4830:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4831:                                   $env{'user.name'});
                   4832:     my %ccrole = ();
                   4833:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4834:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4835:     &appenv(\%userroles,[$role,'cm']);
                   4836:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4837:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4838:         &appenv( {'request.role'        => $spec,
                   4839:                   'request.role.domain' => $dcdom,
                   4840:                   'request.course.sec'  => ''
                   4841:                  }
                   4842:                );
                   4843:         my $tadv=0;
                   4844:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4845:         &appenv({'request.role.adv'    => $tadv});
                   4846:     }
1.994     raeburn  4847: }
                   4848: 
1.12      www      4849: # --------------------------------------------------------------- get interface
                   4850: 
                   4851: sub get {
1.131     albertel 4852:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4853:    my $items='';
1.800     albertel 4854:    foreach my $item (@$storearr) {
                   4855:        $items.=&escape($item).'&';
1.191     harris41 4856:    }
1.12      www      4857:    $items=~s/\&$//;
1.620     albertel 4858:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4859:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4860:    my $uhome=&homeserver($uname,$udomain);
                   4861: 
1.133     albertel 4862:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4863:    my @pairs=split(/\&/,$rep);
1.273     albertel 4864:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4865:      return @pairs;
                   4866:    }
1.15      www      4867:    my %returnhash=();
1.42      www      4868:    my $i=0;
1.800     albertel 4869:    foreach my $item (@$storearr) {
                   4870:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4871:       $i++;
1.191     harris41 4872:    }
1.15      www      4873:    return %returnhash;
1.27      www      4874: }
                   4875: 
                   4876: # --------------------------------------------------------------- del interface
                   4877: 
                   4878: sub del {
1.133     albertel 4879:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4880:    my $items='';
1.800     albertel 4881:    foreach my $item (@$storearr) {
                   4882:        $items.=&escape($item).'&';
1.191     harris41 4883:    }
1.984     neumanie 4884: 
1.27      www      4885:    $items=~s/\&$//;
1.620     albertel 4886:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4887:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4888:    my $uhome=&homeserver($uname,$udomain);
                   4889:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4890: }
                   4891: 
                   4892: # -------------------------------------------------------------- dump interface
                   4893: 
                   4894: sub dump {
1.1086    raeburn  4895:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4896:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4897:     if (!$uname) { $uname=$env{'user.name'}; }
                   4898:     my $uhome=&homeserver($uname,$udomain);
                   4899:     if ($regexp) {
                   4900: 	$regexp=&escape($regexp);
                   4901:     } else {
                   4902: 	$regexp='.';
                   4903:     }
1.1086    raeburn  4904:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4905:     my @pairs=split(/\&/,$rep);
                   4906:     my %returnhash=();
1.1098    foxr     4907:     if (!($rep =~ /^error/ )) {
                   4908: 	foreach my $item (@pairs) {
                   4909: 	    my ($key,$value)=split(/=/,$item,2);
                   4910: 	    $key = &unescape($key);
                   4911: 	    next if ($key =~ /^error: 2 /);
                   4912: 	    $returnhash{$key}=&thaw_unescape($value);
                   4913: 	}
1.755     albertel 4914:     }
                   4915:     return %returnhash;
1.407     www      4916: }
                   4917: 
1.1098    foxr     4918: 
1.717     albertel 4919: # --------------------------------------------------------- dumpstore interface
                   4920: 
                   4921: sub dumpstore {
                   4922:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4923:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4924:    if (!$uname) { $uname=$env{'user.name'}; }
                   4925:    my $uhome=&homeserver($uname,$udomain);
                   4926:    if ($regexp) {
                   4927:        $regexp=&escape($regexp);
                   4928:    } else {
                   4929:        $regexp='.';
                   4930:    }
                   4931:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4932:    my @pairs=split(/\&/,$rep);
                   4933:    my %returnhash=();
                   4934:    foreach my $item (@pairs) {
                   4935:        my ($key,$value)=split(/=/,$item,2);
                   4936:        next if ($key =~ /^error: 2 /);
                   4937:        $returnhash{$key}=&thaw_unescape($value);
                   4938:    }
                   4939:    return %returnhash;
1.717     albertel 4940: }
                   4941: 
1.407     www      4942: # -------------------------------------------------------------- keys interface
                   4943: 
                   4944: sub getkeys {
                   4945:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4946:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4947:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4948:    my $uhome=&homeserver($uname,$udomain);
                   4949:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4950:    my @keyarray=();
1.800     albertel 4951:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4952:       next if ($key =~ /^error: 2 /);
1.800     albertel 4953:       push(@keyarray,&unescape($key));
1.407     www      4954:    }
                   4955:    return @keyarray;
1.318     matthew  4956: }
                   4957: 
1.319     matthew  4958: # --------------------------------------------------------------- currentdump
                   4959: sub currentdump {
1.328     matthew  4960:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4961:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4962:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4963:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4964:    my $uhome = &homeserver($sname,$sdom);
                   4965:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4966:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4967:    #
1.318     matthew  4968:    my %returnhash=();
1.319     matthew  4969:    #
                   4970:    if ($rep eq "unknown_cmd") { 
                   4971:        # an old lond will not know currentdump
                   4972:        # Do a dump and make it look like a currentdump
1.822     albertel 4973:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4974:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4975:        my %hash = @tmp;
                   4976:        @tmp=();
1.424     matthew  4977:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4978:    } else {
                   4979:        my @pairs=split(/\&/,$rep);
1.800     albertel 4980:        foreach my $pair (@pairs) {
                   4981:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4982:            my ($symb,$param) = split(/:/,$key);
                   4983:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4984:                                                         &thaw_unescape($value);
1.319     matthew  4985:        }
1.191     harris41 4986:    }
1.12      www      4987:    return %returnhash;
1.424     matthew  4988: }
                   4989: 
                   4990: sub convert_dump_to_currentdump{
                   4991:     my %hash = %{shift()};
                   4992:     my %returnhash;
                   4993:     # Code ripped from lond, essentially.  The only difference
                   4994:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4995:     # we might run in to problems with parameter names =~ /^v\./
                   4996:     while (my ($key,$value) = each(%hash)) {
                   4997:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4998: 	$symb  = &unescape($symb);
                   4999: 	$param = &unescape($param);
1.424     matthew  5000:         next if ($v eq 'version' || $symb eq 'keys');
                   5001:         next if (exists($returnhash{$symb}) &&
                   5002:                  exists($returnhash{$symb}->{$param}) &&
                   5003:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5004:         $returnhash{$symb}->{$param}=$value;
                   5005:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5006:     }
                   5007:     #
                   5008:     # Remove all of the keys in the hashes which keep track of
                   5009:     # the version of the parameter.
                   5010:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5011:         # use a foreach because we are going to delete from the hash.
                   5012:         foreach my $key (keys(%$param_hash)) {
                   5013:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5014:         }
                   5015:     }
                   5016:     return \%returnhash;
1.12      www      5017: }
                   5018: 
1.627     albertel 5019: # ------------------------------------------------------ critical inc interface
                   5020: 
                   5021: sub cinc {
                   5022:     return &inc(@_,'critical');
                   5023: }
                   5024: 
1.449     matthew  5025: # --------------------------------------------------------------- inc interface
                   5026: 
                   5027: sub inc {
1.627     albertel 5028:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5029:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5030:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5031:     my $uhome=&homeserver($uname,$udomain);
                   5032:     my $items='';
                   5033:     if (! ref($store)) {
                   5034:         # got a single value, so use that instead
                   5035:         $items = &escape($store).'=&';
                   5036:     } elsif (ref($store) eq 'SCALAR') {
                   5037:         $items = &escape($$store).'=&';        
                   5038:     } elsif (ref($store) eq 'ARRAY') {
                   5039:         $items = join('=&',map {&escape($_);} @{$store});
                   5040:     } elsif (ref($store) eq 'HASH') {
                   5041:         while (my($key,$value) = each(%{$store})) {
                   5042:             $items.= &escape($key).'='.&escape($value).'&';
                   5043:         }
                   5044:     }
                   5045:     $items=~s/\&$//;
1.627     albertel 5046:     if ($critical) {
                   5047: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5048:     } else {
                   5049: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5050:     }
1.449     matthew  5051: }
                   5052: 
1.12      www      5053: # --------------------------------------------------------------- put interface
                   5054: 
                   5055: sub put {
1.134     albertel 5056:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5058:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5059:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5060:    my $items='';
1.800     albertel 5061:    foreach my $item (keys(%$storehash)) {
                   5062:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5063:    }
1.12      www      5064:    $items=~s/\&$//;
1.134     albertel 5065:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5066: }
                   5067: 
1.631     albertel 5068: # ------------------------------------------------------------ newput interface
                   5069: 
                   5070: sub newput {
                   5071:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5072:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5073:    if (!$uname) { $uname=$env{'user.name'}; }
                   5074:    my $uhome=&homeserver($uname,$udomain);
                   5075:    my $items='';
                   5076:    foreach my $key (keys(%$storehash)) {
                   5077:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5078:    }
                   5079:    $items=~s/\&$//;
                   5080:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5081: }
                   5082: 
                   5083: # ---------------------------------------------------------  putstore interface
                   5084: 
1.524     raeburn  5085: sub putstore {
1.715     albertel 5086:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5087:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5088:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5089:    my $uhome=&homeserver($uname,$udomain);
                   5090:    my $items='';
1.715     albertel 5091:    foreach my $key (keys(%$storehash)) {
                   5092:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5093:    }
1.715     albertel 5094:    $items=~s/\&$//;
1.716     albertel 5095:    my $esc_symb=&escape($symb);
                   5096:    my $esc_v=&escape($version);
1.715     albertel 5097:    my $reply =
1.716     albertel 5098:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5099: 	      $uhome);
                   5100:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5101:        # gfall back to way things use to be done
1.715     albertel 5102:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5103: 			    $uname);
1.524     raeburn  5104:    }
1.715     albertel 5105:    return $reply;
                   5106: }
                   5107: 
                   5108: sub old_putstore {
1.716     albertel 5109:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5110:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5111:     if (!$uname) { $uname=$env{'user.name'}; }
                   5112:     my $uhome=&homeserver($uname,$udomain);
                   5113:     my %newstorehash;
1.800     albertel 5114:     foreach my $item (keys(%$storehash)) {
                   5115: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5116: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5117:     }
                   5118:     my $items='';
                   5119:     my %allitems = ();
1.800     albertel 5120:     foreach my $item (keys(%newstorehash)) {
                   5121: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5122: 	    my $key = $1.':keys:'.$2;
                   5123: 	    $allitems{$key} .= $3.':';
                   5124: 	}
1.800     albertel 5125: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5126:     }
1.800     albertel 5127:     foreach my $item (keys(%allitems)) {
                   5128: 	$allitems{$item} =~ s/\:$//;
                   5129: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5130:     }
                   5131:     $items=~s/\&$//;
                   5132:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5133: }
                   5134: 
1.47      www      5135: # ------------------------------------------------------ critical put interface
                   5136: 
                   5137: sub cput {
1.134     albertel 5138:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5139:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5140:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5141:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5142:    my $items='';
1.800     albertel 5143:    foreach my $item (keys(%$storehash)) {
                   5144:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5145:    }
1.47      www      5146:    $items=~s/\&$//;
1.134     albertel 5147:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5148: }
                   5149: 
                   5150: # -------------------------------------------------------------- eget interface
                   5151: 
                   5152: sub eget {
1.133     albertel 5153:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5154:    my $items='';
1.800     albertel 5155:    foreach my $item (@$storearr) {
                   5156:        $items.=&escape($item).'&';
1.191     harris41 5157:    }
1.12      www      5158:    $items=~s/\&$//;
1.620     albertel 5159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5160:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5161:    my $uhome=&homeserver($uname,$udomain);
                   5162:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5163:    my @pairs=split(/\&/,$rep);
                   5164:    my %returnhash=();
1.42      www      5165:    my $i=0;
1.800     albertel 5166:    foreach my $item (@$storearr) {
                   5167:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5168:       $i++;
1.191     harris41 5169:    }
1.12      www      5170:    return %returnhash;
                   5171: }
                   5172: 
1.667     albertel 5173: # ------------------------------------------------------------ tmpput interface
                   5174: sub tmpput {
1.802     raeburn  5175:     my ($storehash,$server,$context)=@_;
1.667     albertel 5176:     my $items='';
1.800     albertel 5177:     foreach my $item (keys(%$storehash)) {
                   5178: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5179:     }
                   5180:     $items=~s/\&$//;
1.802     raeburn  5181:     if (defined($context)) {
                   5182:         $items .= ':'.&escape($context);
                   5183:     }
1.667     albertel 5184:     return &reply("tmpput:$items",$server);
                   5185: }
                   5186: 
                   5187: # ------------------------------------------------------------ tmpget interface
                   5188: sub tmpget {
1.688     albertel 5189:     my ($token,$server)=@_;
                   5190:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5191:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5192:     my %returnhash;
                   5193:     foreach my $item (split(/\&/,$rep)) {
                   5194: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5195:         next if ($key =~ /^error: 2 /);
1.667     albertel 5196: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5197:     }
                   5198:     return %returnhash;
                   5199: }
                   5200: 
1.1113    raeburn  5201: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5202: sub tmpdel {
                   5203:     my ($token,$server)=@_;
                   5204:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5205:     return &reply("tmpdel:$token",$server);
                   5206: }
                   5207: 
1.765     albertel 5208: # -------------------------------------------------- portfolio access checking
                   5209: 
                   5210: sub portfolio_access {
1.766     albertel 5211:     my ($requrl) = @_;
1.765     albertel 5212:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5213:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5214:     if ($result) {
                   5215:         my %setters;
                   5216:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5217:             my ($startblock,$endblock) =
                   5218:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5219:             if ($startblock && $endblock) {
                   5220:                 return 'B';
                   5221:             }
                   5222:         } else {
                   5223:             my ($startblock,$endblock) =
                   5224:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5225:             if ($startblock && $endblock) {
                   5226:                 return 'B';
                   5227:             }
                   5228:         }
                   5229:     }
1.765     albertel 5230:     if ($result eq 'ok') {
1.766     albertel 5231:        return 'F';
1.765     albertel 5232:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5233:        return 'A';
1.765     albertel 5234:     }
1.766     albertel 5235:     return '';
1.765     albertel 5236: }
                   5237: 
                   5238: sub get_portfolio_access {
1.767     albertel 5239:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5240: 
                   5241:     if (!ref($access_hash)) {
                   5242: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5243: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5244: 						   $file_name);
                   5245: 	$access_hash = $access_controls{$file_name};
                   5246:     }
                   5247: 
1.765     albertel 5248:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5249:     my $now = time;
                   5250:     if (ref($access_hash) eq 'HASH') {
                   5251:         foreach my $key (keys(%{$access_hash})) {
                   5252:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5253:             if ($start > $now) {
                   5254:                 next;
                   5255:             }
                   5256:             if ($end && $end<$now) {
                   5257:                 next;
                   5258:             }
                   5259:             if ($scope eq 'public') {
                   5260:                 $public = $key;
                   5261:                 last;
                   5262:             } elsif ($scope eq 'guest') {
                   5263:                 $guest = $key;
                   5264:             } elsif ($scope eq 'domains') {
                   5265:                 push(@domains,$key);
                   5266:             } elsif ($scope eq 'users') {
                   5267:                 push(@users,$key);
                   5268:             } elsif ($scope eq 'course') {
                   5269:                 push(@courses,$key);
                   5270:             } elsif ($scope eq 'group') {
                   5271:                 push(@groups,$key);
                   5272:             }
                   5273:         }
                   5274:         if ($public) {
                   5275:             return 'ok';
                   5276:         }
                   5277:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5278:             if ($guest) {
                   5279:                 return $guest;
                   5280:             }
                   5281:         } else {
                   5282:             if (@domains > 0) {
                   5283:                 foreach my $domkey (@domains) {
                   5284:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5285:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5286:                             return 'ok';
                   5287:                         }
                   5288:                     }
                   5289:                 }
                   5290:             }
                   5291:             if (@users > 0) {
                   5292:                 foreach my $userkey (@users) {
1.865     raeburn  5293:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5294:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5295:                             if (ref($item) eq 'HASH') {
                   5296:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5297:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5298:                                     return 'ok';
                   5299:                                 }
                   5300:                             }
                   5301:                         }
                   5302:                     } 
1.765     albertel 5303:                 }
                   5304:             }
                   5305:             my %roleshash;
                   5306:             my @courses_and_groups = @courses;
                   5307:             push(@courses_and_groups,@groups); 
                   5308:             if (@courses_and_groups > 0) {
                   5309:                 my (%allgroups,%allroles); 
                   5310:                 my ($start,$end,$role,$sec,$group);
                   5311:                 foreach my $envkey (%env) {
1.1060    raeburn  5312:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5313:                         my $cid = $2.'_'.$3; 
                   5314:                         if ($1 eq 'gr') {
                   5315:                             $group = $4;
                   5316:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5317:                         } else {
                   5318:                             if ($4 eq '') {
                   5319:                                 $sec = 'none';
                   5320:                             } else {
                   5321:                                 $sec = $4;
                   5322:                             }
                   5323:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5324:                         }
1.811     albertel 5325:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5326:                         my $cid = $2.'_'.$3;
                   5327:                         if ($4 eq '') {
                   5328:                             $sec = 'none';
                   5329:                         } else {
                   5330:                             $sec = $4;
                   5331:                         }
                   5332:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5333:                     }
                   5334:                 }
                   5335:                 if (keys(%allroles) == 0) {
                   5336:                     return;
                   5337:                 }
                   5338:                 foreach my $key (@courses_and_groups) {
                   5339:                     my %content = %{$$access_hash{$key}};
                   5340:                     my $cnum = $content{'number'};
                   5341:                     my $cdom = $content{'domain'};
                   5342:                     my $cid = $cdom.'_'.$cnum;
                   5343:                     if (!exists($allroles{$cid})) {
                   5344:                         next;
                   5345:                     }    
                   5346:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5347:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5348:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5349:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5350:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5351:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5352:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5353:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5354:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5355:                                         if (grep/^all$/,@sections) {
                   5356:                                             return 'ok';
                   5357:                                         } else {
                   5358:                                             if (grep/^$sec$/,@sections) {
                   5359:                                                 return 'ok';
                   5360:                                             }
                   5361:                                         }
                   5362:                                     }
                   5363:                                 }
                   5364:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5365:                                     if (grep/^none$/,@groups) {
                   5366:                                         return 'ok';
                   5367:                                     }
                   5368:                                 } else {
                   5369:                                     if (grep/^all$/,@groups) {
                   5370:                                         return 'ok';
                   5371:                                     } 
                   5372:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5373:                                         if (grep/^$group$/,@groups) {
                   5374:                                             return 'ok';
                   5375:                                         }
                   5376:                                     }
                   5377:                                 } 
                   5378:                             }
                   5379:                         }
                   5380:                     }
                   5381:                 }
                   5382:             }
                   5383:             if ($guest) {
                   5384:                 return $guest;
                   5385:             }
                   5386:         }
                   5387:     }
                   5388:     return;
                   5389: }
                   5390: 
                   5391: sub course_group_datechecker {
                   5392:     my ($dates,$now,$status) = @_;
                   5393:     my ($start,$end) = split(/\./,$dates);
                   5394:     if (!$start && !$end) {
                   5395:         return 'ok';
                   5396:     }
                   5397:     if (grep/^active$/,@{$status}) {
                   5398:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5399:             return 'ok';
                   5400:         }
                   5401:     }
                   5402:     if (grep/^previous$/,@{$status}) {
                   5403:         if ($end > $now ) {
                   5404:             return 'ok';
                   5405:         }
                   5406:     }
                   5407:     if (grep/^future$/,@{$status}) {
                   5408:         if ($start > $now) {
                   5409:             return 'ok';
                   5410:         }
                   5411:     }
                   5412:     return; 
                   5413: }
                   5414: 
                   5415: sub parse_portfolio_url {
                   5416:     my ($url) = @_;
                   5417: 
                   5418:     my ($type,$udom,$unum,$group,$file_name);
                   5419:     
1.823     albertel 5420:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5421: 	$type = 1;
                   5422:         $udom = $1;
                   5423:         $unum = $2;
                   5424:         $file_name = $3;
1.823     albertel 5425:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5426: 	$type = 2;
                   5427:         $udom = $1;
                   5428:         $unum = $2;
                   5429:         $group = $3;
                   5430:         $file_name = $3.'/'.$4;
                   5431:     }
                   5432:     if (wantarray) {
                   5433: 	return ($type,$udom,$unum,$file_name,$group);
                   5434:     }
                   5435:     return $type;
                   5436: }
                   5437: 
                   5438: sub is_portfolio_url {
                   5439:     my ($url) = @_;
                   5440:     return scalar(&parse_portfolio_url($url));
                   5441: }
                   5442: 
1.798     raeburn  5443: sub is_portfolio_file {
                   5444:     my ($file) = @_;
1.820     raeburn  5445:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5446:         return 1;
                   5447:     }
                   5448:     return;
                   5449: }
                   5450: 
1.976     raeburn  5451: sub usertools_access {
1.1084    raeburn  5452:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5453:     my ($access,%tools);
                   5454:     if ($context eq '') {
                   5455:         $context = 'tools';
                   5456:     }
                   5457:     if ($context eq 'requestcourses') {
                   5458:         %tools = (
                   5459:                       official   => 1,
                   5460:                       unofficial => 1,
1.1006    raeburn  5461:                       community  => 1,
1.985     raeburn  5462:                  );
                   5463:     } else {
                   5464:         %tools = (
                   5465:                       aboutme   => 1,
                   5466:                       blog      => 1,
                   5467:                       portfolio => 1,
                   5468:                  );
                   5469:     }
1.976     raeburn  5470:     return if (!defined($tools{$tool}));
                   5471: 
                   5472:     if ((!defined($udom)) || (!defined($uname))) {
                   5473:         $udom = $env{'user.domain'};
                   5474:         $uname = $env{'user.name'};
                   5475:     }
                   5476: 
1.978     raeburn  5477:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5478:         if ($action ne 'reload') {
1.985     raeburn  5479:             if ($context eq 'requestcourses') {
                   5480:                 return $env{'environment.canrequest.'.$tool};
                   5481:             } else {
                   5482:                 return $env{'environment.availabletools.'.$tool};
                   5483:             }
                   5484:         }
1.976     raeburn  5485:     }
                   5486: 
                   5487:     my ($toolstatus,$inststatus);
                   5488: 
1.985     raeburn  5489:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5490:          ($action ne 'reload')) {
                   5491:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5492:         $inststatus = $env{'environment.inststatus'};
                   5493:     } else {
1.1084    raeburn  5494:         if (ref($userenvref) eq 'HASH') {
                   5495:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5496:             $inststatus = $userenvref->{'inststatus'};
                   5497:         } else {
                   5498:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5499:             $toolstatus = $userenv{$context.'.'.$tool};
                   5500:             $inststatus = $userenv{'inststatus'};
                   5501:         }
1.976     raeburn  5502:     }
                   5503: 
                   5504:     if ($toolstatus ne '') {
                   5505:         if ($toolstatus) {
                   5506:             $access = 1;
                   5507:         } else {
                   5508:             $access = 0;
                   5509:         }
                   5510:         return $access;
                   5511:     }
                   5512: 
1.1084    raeburn  5513:     my ($is_adv,%domdef);
                   5514:     if (ref($is_advref) eq 'HASH') {
                   5515:         $is_adv = $is_advref->{'is_adv'};
                   5516:     } else {
                   5517:         $is_adv = &is_advanced_user($udom,$uname);
                   5518:     }
                   5519:     if (ref($domdefref) eq 'HASH') {
                   5520:         %domdef = %{$domdefref};
                   5521:     } else {
                   5522:         %domdef = &get_domain_defaults($udom);
                   5523:     }
1.976     raeburn  5524:     if (ref($domdef{$tool}) eq 'HASH') {
                   5525:         if ($is_adv) {
                   5526:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5527:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5528:                     $access = 1;
                   5529:                 } else {
                   5530:                     $access = 0;
                   5531:                 }
                   5532:                 return $access;
                   5533:             }
                   5534:         }
                   5535:         if ($inststatus ne '') {
                   5536:             my ($hasaccess,$hasnoaccess);
                   5537:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5538:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5539:                     if ($domdef{$tool}{$affiliation}) {
                   5540:                         $hasaccess = 1;
                   5541:                     } else {
                   5542:                         $hasnoaccess = 1;
                   5543:                     }
                   5544:                 }
                   5545:             }
                   5546:             if ($hasaccess || $hasnoaccess) {
                   5547:                 if ($hasaccess) {
                   5548:                     $access = 1;
                   5549:                 } elsif ($hasnoaccess) {
                   5550:                     $access = 0; 
                   5551:                 }
                   5552:                 return $access;
                   5553:             }
                   5554:         } else {
                   5555:             if ($domdef{$tool}{'default'} ne '') {
                   5556:                 if ($domdef{$tool}{'default'}) {
                   5557:                     $access = 1;
                   5558:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5559:                     $access = 0;
                   5560:                 }
                   5561:                 return $access;
                   5562:             }
                   5563:         }
                   5564:     } else {
1.985     raeburn  5565:         if ($context eq 'tools') {
                   5566:             $access = 1;
                   5567:         } else {
                   5568:             $access = 0;
                   5569:         }
1.976     raeburn  5570:         return $access;
                   5571:     }
                   5572: }
                   5573: 
1.1050    raeburn  5574: sub is_course_owner {
                   5575:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5576:     if (($udom eq '') || ($uname eq '')) {
                   5577:         $udom = $env{'user.domain'};
                   5578:         $uname = $env{'user.name'};
                   5579:     }
                   5580:     unless (($udom eq '') || ($uname eq '')) {
                   5581:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5582:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5583:                 return 1;
                   5584:             } else {
                   5585:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5586:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5587:                     return 1;
                   5588:                 }
                   5589:             }
                   5590:         }
                   5591:     }
                   5592:     return;
                   5593: }
                   5594: 
1.976     raeburn  5595: sub is_advanced_user {
                   5596:     my ($udom,$uname) = @_;
1.1085    raeburn  5597:     if ($udom ne '' && $uname ne '') {
                   5598:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5599:             if (wantarray) {
                   5600:                 return ($env{'user.adv'},$env{'user.author'});
                   5601:             } else {
                   5602:                 return $env{'user.adv'};
                   5603:             }
1.1085    raeburn  5604:         }
                   5605:     }
1.976     raeburn  5606:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5607:     my %allroles;
1.1128    raeburn  5608:     my ($is_adv,$is_author);
1.976     raeburn  5609:     foreach my $role (keys(%roleshash)) {
                   5610:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5611:         my $area = '/'.$tdomain.'/'.$trest;
                   5612:         if ($sec ne '') {
                   5613:             $area .= '/'.$sec;
                   5614:         }
                   5615:         if (($area ne '') && ($trole ne '')) {
                   5616:             my $spec=$trole.'.'.$area;
                   5617:             if ($trole =~ /^cr\//) {
                   5618:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5619:             } elsif ($trole ne 'gr') {
                   5620:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5621:             }
1.1128    raeburn  5622:             if ($trole eq 'au') {
                   5623:                 $is_author = 1;
                   5624:             }
1.976     raeburn  5625:         }
                   5626:     }
                   5627:     foreach my $role (keys(%allroles)) {
                   5628:         last if ($is_adv);
                   5629:         foreach my $item (split(/:/,$allroles{$role})) {
                   5630:             if ($item ne '') {
                   5631:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5632:                 if ($privilege eq 'adv') {
                   5633:                     $is_adv = 1;
                   5634:                     last;
                   5635:                 }
                   5636:             }
                   5637:         }
                   5638:     }
1.1128    raeburn  5639:     if (wantarray) {
                   5640:         return ($is_adv,$is_author);
                   5641:     }
1.976     raeburn  5642:     return $is_adv;
                   5643: }
1.798     raeburn  5644: 
1.1035    raeburn  5645: sub check_can_request {
1.1036    raeburn  5646:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5647:     my $canreq = 0;
                   5648:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5649:     my @options = ('approval','validate','autolimit');
                   5650:     my $optregex = join('|',@options);
                   5651:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5652:         foreach my $type (@{$types}) {
                   5653:             if (&usertools_access($env{'user.name'},
                   5654:                                   $env{'user.domain'},
                   5655:                                   $type,undef,'requestcourses')) {
                   5656:                 $canreq ++;
1.1036    raeburn  5657:                 if (ref($request_domains) eq 'HASH') {
                   5658:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5659:                 }
1.1035    raeburn  5660:                 if ($dom eq $env{'user.domain'}) {
                   5661:                     $can_request->{$type} = 1;
                   5662:                 }
                   5663:             }
                   5664:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5665:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5666:                 if (@curr > 0) {
1.1036    raeburn  5667:                     foreach my $item (@curr) {
                   5668:                         if (ref($request_domains) eq 'HASH') {
                   5669:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5670:                             if ($otherdom ne '') {
                   5671:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5672:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5673:                                         push(@{$request_domains->{$type}},$otherdom);
                   5674:                                     }
                   5675:                                 } else {
                   5676:                                     push(@{$request_domains->{$type}},$otherdom);
                   5677:                                 }
                   5678:                             }
                   5679:                         }
                   5680:                     }
                   5681:                     unless($dom eq $env{'user.domain'}) {
                   5682:                         $canreq ++;
1.1035    raeburn  5683:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5684:                             $can_request->{$type} = 1;
                   5685:                         }
                   5686:                     }
                   5687:                 }
                   5688:             }
                   5689:         }
                   5690:     }
                   5691:     return $canreq;
                   5692: }
                   5693: 
1.341     www      5694: # ---------------------------------------------- Custom access rule evaluation
                   5695: 
                   5696: sub customaccess {
                   5697:     my ($priv,$uri)=@_;
1.807     albertel 5698:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5699:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5700:     $udom = &LONCAPA::clean_domain($udom);
                   5701:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5702:     my $access=0;
1.800     albertel 5703:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5704: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5705: 	if ($type eq 'user') {
                   5706: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5707: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5708: 		if ($tdom) {
                   5709: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5710: 		}
1.896     albertel 5711: 		if ($tuname) {
                   5712: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5713: 		}
                   5714: 		$access=($effect eq 'allow');
                   5715: 		last;
                   5716: 	    }
                   5717: 	} else {
                   5718: 	    if ($role) {
                   5719: 		if ($role ne $urole) { next; }
                   5720: 	    }
                   5721: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5722: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5723: 		if ($tdom) {
                   5724: 		    if ($tdom ne $udom) { next; }
                   5725: 		}
                   5726: 		if ($tcrs) {
                   5727: 		    if ($tcrs ne $ucrs) { next; }
                   5728: 		}
                   5729: 		if ($tsec) {
                   5730: 		    if ($tsec ne $usec) { next; }
                   5731: 		}
                   5732: 		$access=($effect eq 'allow');
                   5733: 		last;
                   5734: 	    }
                   5735: 	    if ($realm eq '' && $role eq '') {
                   5736: 		$access=($effect eq 'allow');
                   5737: 	    }
1.402     bowersj2 5738: 	}
1.341     www      5739:     }
                   5740:     return $access;
                   5741: }
                   5742: 
1.103     harris41 5743: # ------------------------------------------------- Check for a user privilege
1.12      www      5744: 
                   5745: sub allowed {
1.810     raeburn  5746:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5747:     my $ver_orguri=$uri;
1.439     www      5748:     $uri=&deversion($uri);
1.152     www      5749:     my $orguri=$uri;
1.52      www      5750:     $uri=&declutter($uri);
1.809     raeburn  5751: 
1.810     raeburn  5752:     if ($priv eq 'evb') {
                   5753: # Evade communication block restrictions for specified role in a course
                   5754:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5755:             return $1;
                   5756:         } else {
                   5757:             return;
                   5758:         }
                   5759:     }
                   5760: 
1.620     albertel 5761:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5762: # Free bre access to adm and meta resources
1.775     albertel 5763:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5764: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5765: 	&& ($priv eq 'bre')) {
1.14      www      5766: 	return 'F';
1.159     www      5767:     }
                   5768: 
1.545     banghart 5769: # Free bre access to user's own portfolio contents
1.714     raeburn  5770:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5771:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5772: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5773:         my %setters;
                   5774:         my ($startblock,$endblock) = 
                   5775:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5776:         if ($startblock && $endblock) {
                   5777:             return 'B';
                   5778:         } else {
                   5779:             return 'F';
                   5780:         }
1.545     banghart 5781:     }
                   5782: 
1.762     raeburn  5783: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5784:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5785:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5786:         if (exists($env{'request.course.id'})) {
                   5787:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5788:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5789:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5790:                 my $courseprivid=$env{'request.course.id'};
                   5791:                 $courseprivid=~s/\_/\//;
                   5792:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5793:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5794:                     return $1; 
1.762     raeburn  5795:                 } else {
                   5796:                     if ($env{'request.course.sec'}) {
                   5797:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5798:                     }
                   5799:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5800:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5801:                         return $2;
                   5802:                     }
1.714     raeburn  5803:                 }
                   5804:             }
                   5805:         }
                   5806:     }
                   5807: 
1.159     www      5808: # Free bre to public access
                   5809: 
                   5810:     if ($priv eq 'bre') {
1.238     www      5811:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5812: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5813:            return 'F'; 
                   5814:         }
1.238     www      5815:         if ($copyright eq 'priv') {
                   5816:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5817: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5818: 		return '';
                   5819:             }
                   5820:         }
                   5821:         if ($copyright eq 'domain') {
                   5822:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5823: 	    unless (($env{'user.domain'} eq $1) ||
                   5824:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5825: 		return '';
                   5826:             }
1.262     matthew  5827:         }
1.620     albertel 5828:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5829:             # Library role, so allow browsing of resources in this domain.
                   5830:             return 'F';
1.238     www      5831:         }
1.341     www      5832:         if ($copyright eq 'custom') {
                   5833: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5834:         }
1.14      www      5835:     }
1.264     matthew  5836:     # Domain coordinator is trying to create a course
1.620     albertel 5837:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5838:         # uri is the requested domain in this case.
                   5839:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5840:         # a role of dc for the domain in question.
1.620     albertel 5841:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5842:     }
1.29      www      5843: 
1.52      www      5844:     my $thisallowed='';
                   5845:     my $statecond=0;
                   5846:     my $courseprivid='';
                   5847: 
1.1039    raeburn  5848:     my $ownaccess;
1.1043    raeburn  5849:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5850:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5851:         if ($uri eq '') {
                   5852:             $ownaccess = 1;
                   5853:         } else {
                   5854:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5855:                 my $udom = $env{'user.domain'};
                   5856:                 my $uname = $env{'user.name'};
                   5857:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5858:                     $ownaccess = 1;
1.1040    raeburn  5859:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5860:                     unless ($uri =~ m{\.\./}) {
                   5861:                         $ownaccess = 1;
                   5862:                     }
                   5863:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5864:                     my $now = time;
                   5865:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5866:                         my $adom = $1;
                   5867:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5868:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5869:                                 my ($start,$end) = split('.',$env{$key});
                   5870:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5871:                                     $ownaccess = 1;
                   5872:                                     last;
                   5873:                                 }
                   5874:                             }
                   5875:                         }
                   5876:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5877:                         my $adom = $1;
                   5878:                         my $aname = $2;
1.1042    raeburn  5879:                         foreach my $role ('ca','aa') { 
                   5880:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5881:                                 my ($start,$end) =
                   5882:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5883:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5884:                                     $ownaccess = 1;
                   5885:                                     last;
                   5886:                                 }
1.1039    raeburn  5887:                             }
                   5888:                         }
                   5889:                     }
                   5890:                 }
                   5891:             }
                   5892:         }
                   5893:     }
                   5894: 
1.52      www      5895: # Course
                   5896: 
1.620     albertel 5897:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5898:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5899:             $thisallowed.=$1;
                   5900:         }
1.52      www      5901:     }
1.29      www      5902: 
1.52      www      5903: # Domain
                   5904: 
1.620     albertel 5905:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5906:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5907:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5908:             $thisallowed.=$1;
                   5909:         }
1.12      www      5910:     }
1.52      www      5911: 
                   5912: # Course: uri itself is a course
1.66      www      5913:     my $courseuri=$uri;
                   5914:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5915:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5916: 
1.620     albertel 5917:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5918:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5919:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5920:             $thisallowed.=$1;
                   5921:         }
1.12      www      5922:     }
1.29      www      5923: 
1.665     albertel 5924: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5925: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5926:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5927: 	$thisallowed='';
1.671     raeburn  5928:         my ($match)=&is_on_map($uri);
                   5929:         if ($match) {
                   5930:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5931:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5932:                 $thisallowed.=$1;
                   5933:             }
                   5934:         } else {
1.705     albertel 5935:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5936:             if ($refuri) {
                   5937:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5938:                     $thisallowed='F';
1.671     raeburn  5939:                 } else {
                   5940:                     $refuri=&declutter($refuri);
                   5941:                     my ($match) = &is_on_map($refuri);
                   5942:                     if ($match) {
                   5943:                         $thisallowed='F';
                   5944:                     }
1.669     raeburn  5945:                 }
1.671     raeburn  5946:             }
                   5947:         }
1.314     www      5948:     }
1.492     albertel 5949: 
1.766     albertel 5950:     if ($priv eq 'bre'
                   5951: 	&& $thisallowed ne 'F' 
                   5952: 	&& $thisallowed ne '2'
                   5953: 	&& &is_portfolio_url($uri)) {
                   5954: 	$thisallowed = &portfolio_access($uri);
                   5955:     }
                   5956:     
1.52      www      5957: # Full access at system, domain or course-wide level? Exit.
1.29      www      5958:     if ($thisallowed=~/F/) {
                   5959: 	return 'F';
                   5960:     }
                   5961: 
1.52      www      5962: # If this is generating or modifying users, exit with special codes
1.29      www      5963: 
1.643     www      5964:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5965: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5966: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5967: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5968: 	    unless ($auname) { return $thisallowed; }
                   5969: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5970: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5971: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5972: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5973: 	}
1.52      www      5974: 	return $thisallowed;
                   5975:     }
                   5976: #
1.103     harris41 5977: # Gathered so far: system, domain and course wide privileges
1.52      www      5978: #
                   5979: # Course: See if uri or referer is an individual resource that is part of 
                   5980: # the course
                   5981: 
1.620     albertel 5982:     if ($env{'request.course.id'}) {
1.232     www      5983: 
1.620     albertel 5984:        $courseprivid=$env{'request.course.id'};
                   5985:        if ($env{'request.course.sec'}) {
                   5986:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5987:        }
                   5988:        $courseprivid=~s/\_/\//;
                   5989:        my $checkreferer=1;
1.232     www      5990:        my ($match,$cond)=&is_on_map($uri);
                   5991:        if ($match) {
                   5992:            $statecond=$cond;
1.620     albertel 5993:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5994:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5995:                $thisallowed.=$1;
                   5996:                $checkreferer=0;
                   5997:            }
1.29      www      5998:        }
1.83      www      5999:        
1.148     www      6000:        if ($checkreferer) {
1.620     albertel 6001: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6002:             unless ($refuri) {
1.800     albertel 6003:                 foreach my $key (keys(%env)) {
                   6004: 		    if ($key=~/^httpref\..*\*/) {
                   6005: 			my $pattern=$key;
1.156     www      6006:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6007:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6008:                         $pattern=~s/\//\\\//g;
1.152     www      6009:                         if ($orguri=~/$pattern/) {
1.800     albertel 6010: 			    $refuri=$env{$key};
1.148     www      6011:                         }
                   6012:                     }
1.191     harris41 6013:                 }
1.148     www      6014:             }
1.232     www      6015: 
1.148     www      6016:          if ($refuri) { 
1.152     www      6017: 	  $refuri=&declutter($refuri);
1.232     www      6018:           my ($match,$cond)=&is_on_map($refuri);
                   6019:             if ($match) {
                   6020:               my $refstatecond=$cond;
1.620     albertel 6021:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6022:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6023:                   $thisallowed.=$1;
1.53      www      6024:                   $uri=$refuri;
                   6025:                   $statecond=$refstatecond;
1.52      www      6026:               }
                   6027:           }
1.148     www      6028:         }
1.29      www      6029:        }
1.52      www      6030:    }
1.29      www      6031: 
1.52      www      6032: #
1.103     harris41 6033: # Gathered now: all privileges that could apply, and condition number
1.52      www      6034: # 
                   6035: #
                   6036: # Full or no access?
                   6037: #
1.29      www      6038: 
1.52      www      6039:     if ($thisallowed=~/F/) {
                   6040: 	return 'F';
                   6041:     }
1.29      www      6042: 
1.52      www      6043:     unless ($thisallowed) {
                   6044:         return '';
                   6045:     }
1.29      www      6046: 
1.52      www      6047: # Restrictions exist, deal with them
                   6048: #
                   6049: #   C:according to course preferences
                   6050: #   R:according to resource settings
                   6051: #   L:unless locked
                   6052: #   X:according to user session state
                   6053: #
                   6054: 
                   6055: # Possibly locked functionality, check all courses
1.54      www      6056: # Locks might take effect only after 10 minutes cache expiration for other
                   6057: # courses, and 2 minutes for current course
1.52      www      6058: 
                   6059:     my $envkey;
                   6060:     if ($thisallowed=~/L/) {
1.1000    raeburn  6061:         foreach $envkey (keys(%env)) {
1.54      www      6062:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6063:                my $courseid=$2;
                   6064:                my $roleid=$1.'.'.$2;
1.92      www      6065:                $courseid=~s/^\///;
1.54      www      6066:                my $expiretime=600;
1.620     albertel 6067:                if ($env{'request.role'} eq $roleid) {
1.54      www      6068: 		  $expiretime=120;
                   6069:                }
                   6070: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6071:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6072:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6073: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6074:                }
1.620     albertel 6075:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6076:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6077: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6078:                        &log($env{'user.domain'},$env{'user.name'},
                   6079:                             $env{'user.home'},
1.57      www      6080:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6081:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6082:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6083: 		       return '';
                   6084:                    }
                   6085:                }
1.620     albertel 6086:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6087:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6088: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6089:                        &log($env{'user.domain'},$env{'user.name'},
                   6090:                             $env{'user.home'},
1.57      www      6091:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6092:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6093:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6094: 		       return '';
                   6095:                    }
                   6096:                }
                   6097: 	   }
1.29      www      6098:        }
1.52      www      6099:     }
                   6100:    
                   6101: #
                   6102: # Rest of the restrictions depend on selected course
                   6103: #
                   6104: 
1.620     albertel 6105:     unless ($env{'request.course.id'}) {
1.766     albertel 6106: 	if ($thisallowed eq 'A') {
                   6107: 	    return 'A';
1.814     raeburn  6108:         } elsif ($thisallowed eq 'B') {
                   6109:             return 'B';
1.766     albertel 6110: 	} else {
                   6111: 	    return '1';
                   6112: 	}
1.52      www      6113:     }
1.29      www      6114: 
1.52      www      6115: #
                   6116: # Now user is definitely in a course
                   6117: #
1.53      www      6118: 
                   6119: 
                   6120: # Course preferences
                   6121: 
                   6122:    if ($thisallowed=~/C/) {
1.620     albertel 6123:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6124:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6125:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6126: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6127: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6128: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6129: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6130: 			$env{'request.course.id'});
                   6131: 	   }
1.237     www      6132:            return '';
                   6133:        }
                   6134: 
1.620     albertel 6135:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6136: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6137: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6138: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6139: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6140: 			$env{'request.course.id'});
                   6141: 	   }
1.54      www      6142:            return '';
                   6143:        }
1.53      www      6144:    }
                   6145: 
                   6146: # Resource preferences
                   6147: 
                   6148:    if ($thisallowed=~/R/) {
1.620     albertel 6149:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6150:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6151: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6152: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6153: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6154: 	   }
                   6155: 	   return '';
1.54      www      6156:        }
1.53      www      6157:    }
1.30      www      6158: 
1.246     www      6159: # Restricted by state or randomout?
1.30      www      6160: 
1.52      www      6161:    if ($thisallowed=~/X/) {
1.620     albertel 6162:       if ($env{'acc.randomout'}) {
1.579     albertel 6163: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6164:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6165:             return ''; 
                   6166:          }
1.247     www      6167:       }
                   6168:       if (&condval($statecond)) {
1.52      www      6169: 	 return '2';
                   6170:       } else {
                   6171:          return '';
                   6172:       }
                   6173:    }
1.30      www      6174: 
1.766     albertel 6175:     if ($thisallowed eq 'A') {
                   6176: 	return 'A';
1.814     raeburn  6177:     } elsif ($thisallowed eq 'B') {
                   6178:         return 'B';
1.766     albertel 6179:     }
1.52      www      6180:    return 'F';
1.232     www      6181: }
1.1133    foxr     6182: #
                   6183: #   Removes the versino from a URI and
                   6184: #   splits it in to its filename and path to the filename.
                   6185: #   Seems like File::Basename could have done this more clearly.
                   6186: #   Parameters:
                   6187: #      $uri   - input URI
                   6188: #   Returns:
                   6189: #     Two element list consisting of 
                   6190: #     $pathname  - the URI up to and excluding the trailing /
                   6191: #     $filename  - The part of the URI following the last /
                   6192: #  NOTE:
                   6193: #    Another realization of this is simply:
                   6194: #    use File::Basename;
                   6195: #    ...
                   6196: #    $uri = shift;
                   6197: #    $filename = basename($uri);
                   6198: #    $path     = dirname($uri);
                   6199: #    return ($filename, $path);
                   6200: #
                   6201: #     The implementation below is probably faster however.
                   6202: #
1.710     albertel 6203: sub split_uri_for_cond {
                   6204:     my $uri=&deversion(&declutter(shift));
                   6205:     my @uriparts=split(/\//,$uri);
                   6206:     my $filename=pop(@uriparts);
                   6207:     my $pathname=join('/',@uriparts);
                   6208:     return ($pathname,$filename);
                   6209: }
1.232     www      6210: # --------------------------------------------------- Is a resource on the map?
                   6211: 
                   6212: sub is_on_map {
1.710     albertel 6213:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6214:     #Trying to find the conditional for the file
1.620     albertel 6215:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6216: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6217:     if ($match) {
1.289     bowersj2 6218: 	return (1,$1);
                   6219:     } else {
1.434     www      6220: 	return (0,0);
1.289     bowersj2 6221:     }
1.12      www      6222: }
                   6223: 
1.427     www      6224: # --------------------------------------------------------- Get symb from alias
                   6225: 
                   6226: sub get_symb_from_alias {
                   6227:     my $symb=shift;
                   6228:     my ($map,$resid,$url)=&decode_symb($symb);
                   6229: # Already is a symb
                   6230:     if ($url) { return $symb; }
                   6231: # Must be an alias
                   6232:     my $aliassymb='';
                   6233:     my %bighash;
1.620     albertel 6234:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6235:                             &GDBM_READER(),0640)) {
                   6236:         my $rid=$bighash{'mapalias_'.$symb};
                   6237: 	if ($rid) {
                   6238: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6239: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6240: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6241: 	}
                   6242:         untie %bighash;
                   6243:     }
                   6244:     return $aliassymb;
                   6245: }
                   6246: 
1.12      www      6247: # ----------------------------------------------------------------- Define Role
                   6248: 
                   6249: sub definerole {
                   6250:   if (allowed('mcr','/')) {
                   6251:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6252:     foreach my $role (split(':',$sysrole)) {
                   6253: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6254:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6255:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6256: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6257:                return "refused:s:$crole&$cqual"; 
                   6258:             }
                   6259:         }
1.191     harris41 6260:     }
1.800     albertel 6261:     foreach my $role (split(':',$domrole)) {
                   6262: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6263:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6264:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6265: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6266:                return "refused:d:$crole&$cqual"; 
                   6267:             }
                   6268:         }
1.191     harris41 6269:     }
1.800     albertel 6270:     foreach my $role (split(':',$courole)) {
                   6271: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6272:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6273:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6274: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6275:                return "refused:c:$crole&$cqual"; 
                   6276:             }
                   6277:         }
1.191     harris41 6278:     }
1.620     albertel 6279:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6280:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6281: 	        "rolesdef_$rolename=".
                   6282:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6283:     return reply($command,$env{'user.home'});
1.12      www      6284:   } else {
                   6285:     return 'refused';
                   6286:   }
1.105     harris41 6287: }
                   6288: 
                   6289: # ---------------- Make a metadata query against the network of library servers
                   6290: 
                   6291: sub metadata_query {
1.244     matthew  6292:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6293:     my %rhash;
1.845     albertel 6294:     my %libserv = &all_library();
1.244     matthew  6295:     my @server_list = (defined($server_array) ? @$server_array
                   6296:                                               : keys(%libserv) );
                   6297:     for my $server (@server_list) {
1.118     harris41 6298: 	unless ($custom or $customshow) {
                   6299: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6300: 	    $rhash{$server}=$reply;
                   6301: 	}
                   6302: 	else {
                   6303: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6304: 			     &escape($custom).':'.&escape($customshow),
                   6305: 			     $server);
                   6306: 	    $rhash{$server}=$reply;
                   6307: 	}
1.112     harris41 6308:     }
1.118     harris41 6309:     return \%rhash;
1.240     www      6310: }
                   6311: 
                   6312: # ----------------------------------------- Send log queries and wait for reply
                   6313: 
                   6314: sub log_query {
                   6315:     my ($uname,$udom,$query,%filters)=@_;
                   6316:     my $uhome=&homeserver($uname,$udom);
                   6317:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6318:     my $uhost=&hostname($uhome);
1.800     albertel 6319:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6320:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6321:                        $uhome);
1.479     albertel 6322:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6323:     return get_query_reply($queryid);
                   6324: }
                   6325: 
1.818     raeburn  6326: # -------------------------- Update MySQL table for portfolio file
                   6327: 
                   6328: sub update_portfolio_table {
1.821     raeburn  6329:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6330:     if ($group ne '') {
                   6331:         $file_name =~s /^\Q$group\E//;
                   6332:     }
1.818     raeburn  6333:     my $homeserver = &homeserver($uname,$udom);
                   6334:     my $queryid=
1.821     raeburn  6335:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6336:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6337:     my $reply = &get_query_reply($queryid);
                   6338:     return $reply;
                   6339: }
                   6340: 
1.899     raeburn  6341: # -------------------------- Update MySQL allusers table
                   6342: 
                   6343: sub update_allusers_table {
                   6344:     my ($uname,$udom,$names) = @_;
                   6345:     my $homeserver = &homeserver($uname,$udom);
                   6346:     my $queryid=
                   6347:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6348:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6349:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6350:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6351:                'generation='.&escape($names->{'generation'}).'%%'.
                   6352:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6353:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6354:     return;
1.899     raeburn  6355: }
                   6356: 
1.508     raeburn  6357: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6358: 
                   6359: sub fetch_enrollment_query {
1.511     raeburn  6360:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6361:     my $homeserver;
1.547     raeburn  6362:     my $maxtries = 1;
1.508     raeburn  6363:     if ($context eq 'automated') {
                   6364:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6365:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6366:     } else {
                   6367:         $homeserver = &homeserver($cnum,$dom);
                   6368:     }
1.838     albertel 6369:     my $host=&hostname($homeserver);
1.506     raeburn  6370:     my $cmd = '';
1.1000    raeburn  6371:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6372:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6373:     }
                   6374:     $cmd =~ s/%%$//;
                   6375:     $cmd = &escape($cmd);
                   6376:     my $query = 'fetchenrollment';
1.620     albertel 6377:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6378:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6379:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6380:         return 'error: '.$queryid;
                   6381:     }
1.506     raeburn  6382:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6383:     my $tries = 1;
                   6384:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6385:         $reply = &get_query_reply($queryid);
                   6386:         $tries ++;
                   6387:     }
1.526     raeburn  6388:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6389:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6390:     } else {
1.901     albertel 6391:         my @responses = split(/:/,$reply);
1.515     raeburn  6392:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6393:             foreach my $line (@responses) {
                   6394:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6395:                 $$replyref{$key} = $value;
                   6396:             }
                   6397:         } else {
1.1117    foxr     6398:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6399:             foreach my $line (@responses) {
                   6400:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6401:                 $$replyref{$key} = $value;
                   6402:                 if ($value > 0) {
1.800     albertel 6403:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6404:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6405:                         my $destname = $pathname.'/'.$filename;
                   6406:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6407:                         if ($xml_classlist =~ /^error/) {
                   6408:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6409:                         } else {
1.506     raeburn  6410:                             if ( open(FILE,">$destname") ) {
                   6411:                                 print FILE &unescape($xml_classlist);
                   6412:                                 close(FILE);
1.526     raeburn  6413:                             } else {
                   6414:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6415:                             }
                   6416:                         }
                   6417:                     }
                   6418:                 }
                   6419:             }
                   6420:         }
                   6421:         return 'ok';
                   6422:     }
                   6423:     return 'error';
                   6424: }
                   6425: 
1.242     www      6426: sub get_query_reply {
                   6427:     my $queryid=shift;
1.1117    foxr     6428:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6429:     my $reply='';
                   6430:     for (1..100) {
                   6431: 	sleep 2;
                   6432:         if (-e $replyfile.'.end') {
1.448     albertel 6433: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6434: 		$reply = join('',<$fh>);
                   6435: 		close($fh);
1.240     www      6436: 	   } else { return 'error: reply_file_error'; }
1.242     www      6437:            return &unescape($reply);
                   6438: 	}
1.240     www      6439:     }
1.242     www      6440:     return 'timeout:'.$queryid;
1.240     www      6441: }
                   6442: 
                   6443: sub courselog_query {
1.241     www      6444: #
                   6445: # possible filters:
                   6446: # url: url or symb
                   6447: # username
                   6448: # domain
                   6449: # action: view, submit, grade
                   6450: # start: timestamp
                   6451: # end: timestamp
                   6452: #
1.240     www      6453:     my (%filters)=@_;
1.620     albertel 6454:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6455:     if ($filters{'url'}) {
                   6456: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6457:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6458:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6459:     }
1.620     albertel 6460:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6461:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6462:     return &log_query($cname,$cdom,'courselog',%filters);
                   6463: }
                   6464: 
                   6465: sub userlog_query {
1.858     raeburn  6466: #
                   6467: # possible filters:
                   6468: # action: log check role
                   6469: # start: timestamp
                   6470: # end: timestamp
                   6471: #
1.240     www      6472:     my ($uname,$udom,%filters)=@_;
                   6473:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6474: }
                   6475: 
1.506     raeburn  6476: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6477: 
                   6478: sub auto_run {
1.508     raeburn  6479:     my ($cnum,$cdom) = @_;
1.876     raeburn  6480:     my $response = 0;
                   6481:     my $settings;
                   6482:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6483:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6484:         $settings = $domconfig{'autoenroll'};
                   6485:         if ($settings->{'run'} eq '1') {
                   6486:             $response = 1;
                   6487:         }
                   6488:     } else {
1.934     raeburn  6489:         my $homeserver;
                   6490:         if (&is_course($cdom,$cnum)) {
                   6491:             $homeserver = &homeserver($cnum,$cdom);
                   6492:         } else {
                   6493:             $homeserver = &domain($cdom,'primary');
                   6494:         }
                   6495:         if ($homeserver ne 'no_host') {
                   6496:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6497:         }
1.876     raeburn  6498:     }
1.506     raeburn  6499:     return $response;
                   6500: }
1.776     albertel 6501: 
1.506     raeburn  6502: sub auto_get_sections {
1.508     raeburn  6503:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6504:     my $homeserver;
                   6505:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6506:         $homeserver = &homeserver($cnum,$cdom);
                   6507:     }
                   6508:     if (!defined($homeserver)) { 
                   6509:         if ($cdom =~ /^$match_domain$/) {
                   6510:             $homeserver = &domain($cdom,'primary');
                   6511:         }
                   6512:     }
                   6513:     my @secs;
                   6514:     if (defined($homeserver)) {
                   6515:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6516:         unless ($response eq 'refused') {
                   6517:             @secs = split(/:/,$response);
                   6518:         }
1.506     raeburn  6519:     }
                   6520:     return @secs;
                   6521: }
1.776     albertel 6522: 
1.506     raeburn  6523: sub auto_new_course {
1.1099    raeburn  6524:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6525:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6526:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6527:     return $response;
                   6528: }
1.776     albertel 6529: 
1.506     raeburn  6530: sub auto_validate_courseID {
1.508     raeburn  6531:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6532:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6533:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6534:     return $response;
                   6535: }
1.776     albertel 6536: 
1.1007    raeburn  6537: sub auto_validate_instcode {
1.1020    raeburn  6538:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6539:     my ($homeserver,$response);
                   6540:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6541:         $homeserver = &homeserver($cnum,$cdom);
                   6542:     }
                   6543:     if (!defined($homeserver)) {
                   6544:         if ($cdom =~ /^$match_domain$/) {
                   6545:             $homeserver = &domain($cdom,'primary');
                   6546:         }
                   6547:     }
1.1065    raeburn  6548:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6549:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6550:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6551:     return ($outcome,$description);
1.1007    raeburn  6552: }
                   6553: 
1.506     raeburn  6554: sub auto_create_password {
1.873     raeburn  6555:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6556:     my ($homeserver,$response);
1.506     raeburn  6557:     my $create_passwd = 0;
                   6558:     my $authchk = '';
1.873     raeburn  6559:     if ($udom =~ /^$match_domain$/) {
                   6560:         $homeserver = &domain($udom,'primary');
                   6561:     }
                   6562:     if ($homeserver eq '') {
                   6563:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6564:             $homeserver = &homeserver($cnum,$cdom);
                   6565:         }
                   6566:     }
                   6567:     if ($homeserver eq '') {
                   6568:         $authchk = 'nodomain';
1.506     raeburn  6569:     } else {
1.873     raeburn  6570:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6571:         if ($response eq 'refused') {
                   6572:             $authchk = 'refused';
                   6573:         } else {
1.901     albertel 6574:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6575:         }
1.506     raeburn  6576:     }
                   6577:     return ($authparam,$create_passwd,$authchk);
                   6578: }
                   6579: 
1.706     raeburn  6580: sub auto_photo_permission {
                   6581:     my ($cnum,$cdom,$students) = @_;
                   6582:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6583:     my ($outcome,$perm_reqd,$conditions) = 
                   6584: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6585:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6586: 	return (undef,undef);
                   6587:     }
1.706     raeburn  6588:     return ($outcome,$perm_reqd,$conditions);
                   6589: }
                   6590: 
                   6591: sub auto_checkphotos {
                   6592:     my ($uname,$udom,$pid) = @_;
                   6593:     my $homeserver = &homeserver($uname,$udom);
                   6594:     my ($result,$resulttype);
                   6595:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6596: 				   &escape($uname).':'.&escape($pid),
                   6597: 				   $homeserver));
1.709     albertel 6598:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6599: 	return (undef,undef);
                   6600:     }
1.706     raeburn  6601:     if ($outcome) {
                   6602:         ($result,$resulttype) = split(/:/,$outcome);
                   6603:     } 
                   6604:     return ($result,$resulttype);
                   6605: }
                   6606: 
                   6607: sub auto_photochoice {
                   6608:     my ($cnum,$cdom) = @_;
                   6609:     my $homeserver = &homeserver($cnum,$cdom);
                   6610:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6611: 						       &escape($cdom),
                   6612: 						       $homeserver)));
1.709     albertel 6613:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6614: 	return (undef,undef);
                   6615:     }
1.706     raeburn  6616:     return ($update,$comment);
                   6617: }
                   6618: 
                   6619: sub auto_photoupdate {
                   6620:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6621:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6622:     my $host=&hostname($homeserver);
1.706     raeburn  6623:     my $cmd = '';
                   6624:     my $maxtries = 1;
1.800     albertel 6625:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6626:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6627:     }
                   6628:     $cmd =~ s/%%$//;
                   6629:     $cmd = &escape($cmd);
                   6630:     my $query = 'institutionalphotos';
                   6631:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6632:     unless ($queryid=~/^\Q$host\E\_/) {
                   6633:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6634:         return 'error: '.$queryid;
                   6635:     }
                   6636:     my $reply = &get_query_reply($queryid);
                   6637:     my $tries = 1;
                   6638:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6639:         $reply = &get_query_reply($queryid);
                   6640:         $tries ++;
                   6641:     }
                   6642:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6643:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6644:     } else {
                   6645:         my @responses = split(/:/,$reply);
                   6646:         my $outcome = shift(@responses); 
                   6647:         foreach my $item (@responses) {
                   6648:             my ($key,$value) = split(/=/,$item);
                   6649:             $$photo{$key} = $value;
                   6650:         }
                   6651:         return $outcome;
                   6652:     }
                   6653:     return 'error';
                   6654: }
                   6655: 
1.521     raeburn  6656: sub auto_instcode_format {
1.793     albertel 6657:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6658: 	$cat_order) = @_;
1.521     raeburn  6659:     my $courses = '';
1.772     raeburn  6660:     my @homeservers;
1.521     raeburn  6661:     if ($caller eq 'global') {
1.841     albertel 6662: 	my %servers = &get_servers($codedom,'library');
                   6663: 	foreach my $tryserver (keys(%servers)) {
                   6664: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6665: 		push(@homeservers,$tryserver);
                   6666: 	    }
1.584     raeburn  6667:         }
1.1022    raeburn  6668:     } elsif ($caller eq 'requests') {
                   6669:         if ($codedom =~ /^$match_domain$/) {
                   6670:             my $chome = &domain($codedom,'primary');
                   6671:             unless ($chome eq 'no_host') {
                   6672:                 push(@homeservers,$chome);
                   6673:             }
                   6674:         }
1.521     raeburn  6675:     } else {
1.772     raeburn  6676:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6677:     }
1.793     albertel 6678:     foreach my $code (keys(%{$instcodes})) {
                   6679:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6680:     }
                   6681:     chop($courses);
1.772     raeburn  6682:     my $ok_response = 0;
                   6683:     my $response;
                   6684:     while (@homeservers > 0 && $ok_response == 0) {
                   6685:         my $server = shift(@homeservers); 
                   6686:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6687:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6688:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6689: 		split(/:/,$response);
1.772     raeburn  6690:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6691:             push(@{$codetitles},&str2array($codetitles_str));
                   6692:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6693:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6694:             $ok_response = 1;
                   6695:         }
                   6696:     }
                   6697:     if ($ok_response) {
1.521     raeburn  6698:         return 'ok';
1.772     raeburn  6699:     } else {
                   6700:         return $response;
1.521     raeburn  6701:     }
                   6702: }
                   6703: 
1.792     raeburn  6704: sub auto_instcode_defaults {
                   6705:     my ($domain,$returnhash,$code_order) = @_;
                   6706:     my @homeservers;
1.841     albertel 6707: 
                   6708:     my %servers = &get_servers($domain,'library');
                   6709:     foreach my $tryserver (keys(%servers)) {
                   6710: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6711: 	    push(@homeservers,$tryserver);
                   6712: 	}
1.792     raeburn  6713:     }
1.841     albertel 6714: 
1.792     raeburn  6715:     my $response;
1.841     albertel 6716:     foreach my $server (@homeservers) {
1.792     raeburn  6717:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6718:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6719: 	
                   6720: 	foreach my $pair (split(/\&/,$response)) {
                   6721: 	    my ($name,$value)=split(/\=/,$pair);
                   6722: 	    if ($name eq 'code_order') {
                   6723: 		@{$code_order} = split(/\&/,&unescape($value));
                   6724: 	    } else {
                   6725: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6726: 	    }
                   6727: 	}
                   6728: 	return 'ok';
1.792     raeburn  6729:     }
1.841     albertel 6730: 
                   6731:     return $response;
1.1003    raeburn  6732: }
                   6733: 
                   6734: sub auto_possible_instcodes {
1.1007    raeburn  6735:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6736:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6737:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6738:         return;
                   6739:     }
1.1003    raeburn  6740:     my (@homeservers,$uhome);
                   6741:     if (defined(&domain($domain,'primary'))) {
                   6742:         $uhome=&domain($domain,'primary');
                   6743:         push(@homeservers,&domain($domain,'primary'));
                   6744:     } else {
                   6745:         my %servers = &get_servers($domain,'library');
                   6746:         foreach my $tryserver (keys(%servers)) {
                   6747:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6748:                 push(@homeservers,$tryserver);
                   6749:             }
                   6750:         }
                   6751:     }
                   6752:     my $response;
                   6753:     foreach my $server (@homeservers) {
                   6754:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6755:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6756:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6757:             split(':',$response);
                   6758:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6759:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6760:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6761:             my ($name,$value)=split('=',$item);
                   6762:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6763:         }
                   6764:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6765:             my ($name,$value)=split('=',$item);
                   6766:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6767:         }
                   6768:         return 'ok';
                   6769:     }
                   6770:     return $response;
                   6771: }
1.792     raeburn  6772: 
1.1010    raeburn  6773: sub auto_courserequest_checks {
                   6774:     my ($dom) = @_;
1.1020    raeburn  6775:     my ($homeserver,%validations);
                   6776:     if ($dom =~ /^$match_domain$/) {
                   6777:         $homeserver = &domain($dom,'primary');
                   6778:     }
                   6779:     unless ($homeserver eq 'no_host') {
                   6780:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6781:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6782:             my @items = split(/&/,$response);
                   6783:             foreach my $item (@items) {
                   6784:                 my ($key,$value) = split('=',$item);
                   6785:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6786:             }
                   6787:         }
                   6788:     }
1.1010    raeburn  6789:     return %validations; 
                   6790: }
                   6791: 
1.1020    raeburn  6792: sub auto_courserequest_validation {
                   6793:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6794:     my ($homeserver,$response);
                   6795:     if ($dom =~ /^$match_domain$/) {
                   6796:         $homeserver = &domain($dom,'primary');
                   6797:     }
                   6798:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6799:           
1.1020    raeburn  6800:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6801:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6802:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6803:                                     $homeserver));
                   6804:     }
                   6805:     return $response;
                   6806: }
                   6807: 
1.777     albertel 6808: sub auto_validate_class_sec {
1.918     raeburn  6809:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6810:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6811:     my $ownerlist;
                   6812:     if (ref($owners) eq 'ARRAY') {
                   6813:         $ownerlist = join(',',@{$owners});
                   6814:     } else {
                   6815:         $ownerlist = $owners;
                   6816:     }
1.773     raeburn  6817:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6818:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6819:     return $response;
                   6820: }
                   6821: 
1.679     raeburn  6822: # ------------------------------------------------------- Course Group routines
                   6823: 
                   6824: sub get_coursegroups {
1.809     raeburn  6825:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6826:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6827: }
                   6828: 
1.679     raeburn  6829: sub modify_coursegroup {
                   6830:     my ($cdom,$cnum,$groupsettings) = @_;
                   6831:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6832: }
                   6833: 
1.809     raeburn  6834: sub toggle_coursegroup_status {
                   6835:     my ($cdom,$cnum,$group,$action) = @_;
                   6836:     my ($from_namespace,$to_namespace);
                   6837:     if ($action eq 'delete') {
                   6838:         $from_namespace = 'coursegroups';
                   6839:         $to_namespace = 'deleted_groups';
                   6840:     } else {
                   6841:         $from_namespace = 'deleted_groups';
                   6842:         $to_namespace = 'coursegroups';
                   6843:     }
                   6844:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6845:     if (my $tmp = &error(%curr_group)) {
                   6846:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6847:         return ('read error',$tmp);
                   6848:     } else {
                   6849:         my %savedsettings = %curr_group; 
1.809     raeburn  6850:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6851:         my $deloutcome;
                   6852:         if ($result eq 'ok') {
1.809     raeburn  6853:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6854:         } else {
                   6855:             return ('write error',$result);
                   6856:         }
                   6857:         if ($deloutcome eq 'ok') {
                   6858:             return 'ok';
                   6859:         } else {
                   6860:             return ('delete error',$deloutcome);
                   6861:         }
                   6862:     }
                   6863: }
                   6864: 
1.679     raeburn  6865: sub modify_group_roles {
1.957     raeburn  6866:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6867:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6868:     my $role = 'gr/'.&escape($userprivs);
                   6869:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6870:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6871:     if ($result eq 'ok') {
                   6872:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6873:     }
1.679     raeburn  6874:     return $result;
                   6875: }
                   6876: 
                   6877: sub modify_coursegroup_membership {
                   6878:     my ($cdom,$cnum,$membership) = @_;
                   6879:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6880:     return $result;
                   6881: }
                   6882: 
1.682     raeburn  6883: sub get_active_groups {
                   6884:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6885:     my $now = time;
                   6886:     my %groups = ();
                   6887:     foreach my $key (keys(%env)) {
1.811     albertel 6888:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6889:             my ($start,$end) = split(/\./,$env{$key});
                   6890:             if (($end!=0) && ($end<$now)) { next; }
                   6891:             if (($start!=0) && ($start>$now)) { next; }
                   6892:             if ($1 eq $cdom && $2 eq $cnum) {
                   6893:                 $groups{$3} = $env{$key} ;
                   6894:             }
                   6895:         }
                   6896:     }
                   6897:     return %groups;
                   6898: }
                   6899: 
1.683     raeburn  6900: sub get_group_membership {
                   6901:     my ($cdom,$cnum,$group) = @_;
                   6902:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6903: }
                   6904: 
                   6905: sub get_users_groups {
                   6906:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6907:     my @usersgroups;
1.683     raeburn  6908:     my $cachetime=1800;
                   6909: 
                   6910:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6911:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6912:     if (defined($cached)) {
1.734     albertel 6913:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6914:     } else {  
                   6915:         $grouplist = '';
1.816     raeburn  6916:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6917:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6918:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6919:         my $access_end = $env{'course.'.$courseid.
                   6920:                               '.default_enrollment_end_date'};
                   6921:         my $now = time;
                   6922:         foreach my $key (keys(%roleshash)) {
                   6923:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6924:                 my $group = $1;
                   6925:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6926:                     my $start = $2;
                   6927:                     my $end = $1;
                   6928:                     if ($start == -1) { next; } # deleted from group
                   6929:                     if (($start!=0) && ($start>$now)) { next; }
                   6930:                     if (($end!=0) && ($end<$now)) {
                   6931:                         if ($access_end && $access_end < $now) {
                   6932:                             if ($access_end - $end < 86400) {
                   6933:                                 push(@usersgroups,$group);
1.733     raeburn  6934:                             }
                   6935:                         }
1.817     raeburn  6936:                         next;
1.733     raeburn  6937:                     }
1.817     raeburn  6938:                     push(@usersgroups,$group);
1.683     raeburn  6939:                 }
                   6940:             }
                   6941:         }
1.817     raeburn  6942:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6943:         $grouplist = join(':',@usersgroups);
                   6944:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6945:     }
1.733     raeburn  6946:     return @usersgroups;
1.683     raeburn  6947: }
                   6948: 
                   6949: sub devalidate_getgroups_cache {
                   6950:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6951:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6952: 
1.683     raeburn  6953:     my $hashid="$udom:$uname:$courseid";
                   6954:     &devalidate_cache_new('getgroups',$hashid);
                   6955: }
                   6956: 
1.12      www      6957: # ------------------------------------------------------------------ Plain Text
                   6958: 
                   6959: sub plaintext {
1.988     raeburn  6960:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6961:     if ($short =~ m{^cr/}) {
1.758     albertel 6962: 	return (split('/',$short))[-1];
                   6963:     }
1.742     raeburn  6964:     if (!defined($cid)) {
                   6965:         $cid = $env{'request.course.id'};
                   6966:     }
                   6967:     my %rolenames = (
1.1008    raeburn  6968:                       Course    => 'std',
                   6969:                       Community => 'alt1',
1.742     raeburn  6970:                     );
1.1037    raeburn  6971:     if ($cid ne '') {
                   6972:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6973:             unless ($forcedefault) {
                   6974:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6975:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6976:                 return &Apache::lonlocal::mt($roletext);
                   6977:             }
                   6978:         }
                   6979:     }
                   6980:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6981:         (defined($rolenames{$type})) && 
                   6982:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6983:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6984:     } elsif ($cid ne '') {
                   6985:         my $crstype = $env{'course.'.$cid.'.type'};
                   6986:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6987:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6988:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6989:         }
1.742     raeburn  6990:     }
1.1037    raeburn  6991:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6992: }
                   6993: 
                   6994: # ----------------------------------------------------------------- Assign Role
                   6995: 
                   6996: sub assignrole {
1.957     raeburn  6997:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6998:         $context)=@_;
1.21      www      6999:     my $mrole;
                   7000:     if ($role =~ /^cr\//) {
1.393     www      7001:         my $cwosec=$url;
1.811     albertel 7002:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7003: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7004:            my $refused = 1;
                   7005:            if ($context eq 'requestcourses') {
                   7006:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7007:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7008:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7009:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7010:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7011:                            if ($crsenv{'internal.courseowner'} eq
                   7012:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7013:                                $refused = '';
                   7014:                            }
                   7015:                        }
                   7016:                    }
                   7017:                }
                   7018:            }
                   7019:            if ($refused) {
                   7020:                &logthis('Refused custom assignrole: '.
                   7021:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7022:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7023:                return 'refused';
                   7024:            }
1.104     www      7025:         }
1.21      www      7026:         $mrole='cr';
1.678     raeburn  7027:     } elsif ($role =~ /^gr\//) {
                   7028:         my $cwogrp=$url;
1.811     albertel 7029:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7030:         unless (&allowed('mdg',$cwogrp)) {
                   7031:             &logthis('Refused group assignrole: '.
                   7032:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7033:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7034:             return 'refused';
                   7035:         }
                   7036:         $mrole='gr';
1.21      www      7037:     } else {
1.82      www      7038:         my $cwosec=$url;
1.811     albertel 7039:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7040:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7041:             my $refused;
                   7042:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7043:                 if (!(&allowed('c'.$role,$url))) {
                   7044:                     $refused = 1;
                   7045:                 }
                   7046:             } else {
                   7047:                 $refused = 1;
                   7048:             }
1.947     raeburn  7049:             if ($refused) {
1.1045    raeburn  7050:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7051:                 if (!$selfenroll && $context eq 'course') {
                   7052:                     my %crsenv;
                   7053:                     if ($role eq 'cc' || $role eq 'co') {
                   7054:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7055:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7056:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7057:                                 if ($crsenv{'internal.courseowner'} eq 
                   7058:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7059:                                     $refused = '';
                   7060:                                 }
                   7061:                             }
                   7062:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7063:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7064:                                 if ($crsenv{'internal.courseowner'} eq 
                   7065:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7066:                                     $refused = '';
                   7067:                                 }
                   7068:                             }
                   7069:                         }
                   7070:                     }
                   7071:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7072:                     $refused = '';
1.1017    raeburn  7073:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7074:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7075:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7076:                         my $wrongcc;
                   7077:                         if ($cnum =~ /^$match_community$/) {
                   7078:                             $wrongcc = 1 if ($role eq 'cc');
                   7079:                         } else {
                   7080:                             $wrongcc = 1 if ($role eq 'co');
                   7081:                         }
                   7082:                         unless ($wrongcc) {
                   7083:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7084:                             if ($crsenv{'internal.courseowner'} eq 
                   7085:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7086:                                 $refused = '';
                   7087:                             }
1.1017    raeburn  7088:                         }
                   7089:                     }
                   7090:                 }
                   7091:                 if ($refused) {
1.947     raeburn  7092:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7093:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7094: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7095:                     return 'refused';
                   7096:                 }
1.932     raeburn  7097:             }
1.1131    raeburn  7098:         } elsif ($role eq 'au') {
                   7099:             if ($url ne '/'.$udom.'/') {
                   7100:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7101:                          ' to assign author role for '.$uname.':'.$udom.
                   7102:                          ' in domain: '.$url.' refused (wrong domain).');
                   7103:                 return 'refused';
                   7104:             }
1.104     www      7105:         }
1.21      www      7106:         $mrole=$role;
                   7107:     }
1.620     albertel 7108:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7109:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7110:     if ($end) { $command.='_'.$end; }
1.21      www      7111:     if ($start) {
                   7112: 	if ($end) { 
1.81      www      7113:            $command.='_'.$start; 
1.21      www      7114:         } else {
1.81      www      7115:            $command.='_0_'.$start;
1.21      www      7116:         }
                   7117:     }
1.739     raeburn  7118:     my $origstart = $start;
                   7119:     my $origend = $end;
1.957     raeburn  7120:     my $delflag;
1.357     www      7121: # actually delete
                   7122:     if ($deleteflag) {
1.373     www      7123: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7124: # modify command to delete the role
1.620     albertel 7125:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7126:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7127: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7128: # set start and finish to negative values for userrolelog
                   7129:            $start=-1;
                   7130:            $end=-1;
1.957     raeburn  7131:            $delflag = 1;
1.357     www      7132:         }
                   7133:     }
                   7134: # send command
1.349     www      7135:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7136: # log new user role if status is ok
1.349     www      7137:     if ($answer eq 'ok') {
1.663     raeburn  7138: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7139: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7140:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7141:         unless ($role =~ /^gr/) {
                   7142:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7143:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7144:         }
1.1053    raeburn  7145:         if ($role eq 'cc') {
                   7146:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7147:         }
1.349     www      7148:     }
                   7149:     return $answer;
1.169     harris41 7150: }
                   7151: 
1.1053    raeburn  7152: sub autoupdate_coowners {
                   7153:     my ($url,$end,$start,$uname,$udom) = @_;
                   7154:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7155:     if (($cdom ne '') && ($cnum ne '')) {
                   7156:         my $now = time;
                   7157:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7158:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7159:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7160:             my $instcode = $coursehash{'internal.coursecode'};
                   7161:             if ($instcode ne '') {
1.1056    raeburn  7162:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7163:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7164:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7165:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7166:                         if ($result eq 'valid') {
                   7167:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7168:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7169:                                     push(@newcoowners,$coowner);
                   7170:                                 }
                   7171:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7172:                                     push(@newcoowners,$uname.':'.$udom);
                   7173:                                 }
                   7174:                                 @newcoowners = sort(@newcoowners);
                   7175:                             } else {
                   7176:                                 push(@newcoowners,$uname.':'.$udom);
                   7177:                             }
                   7178:                         } else {
                   7179:                             if ($coursehash{'internal.co-owners'}) {
                   7180:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7181:                                     unless ($coowner eq $uname.':'.$udom) {
                   7182:                                         push(@newcoowners,$coowner);
                   7183:                                     }
                   7184:                                 }
                   7185:                                 unless (@newcoowners > 0) {
                   7186:                                     $delcoowners = 1;
                   7187:                                     $coowners = '';
                   7188:                                 }
                   7189:                             }
                   7190:                         }
                   7191:                         if (@newcoowners || $delcoowners) {
                   7192:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7193:                                             $delcoowners,@newcoowners);
                   7194:                         }
                   7195:                     }
                   7196:                 }
                   7197:             }
                   7198:         }
                   7199:     }
                   7200: }
                   7201: 
                   7202: sub store_coowners {
                   7203:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7204:     my $cid = $cdom.'_'.$cnum;
                   7205:     my ($coowners,$delresult,$putresult);
                   7206:     if (@newcoowners) {
                   7207:         $coowners = join(',',@newcoowners);
                   7208:         my %coownershash = (
                   7209:                             'internal.co-owners' => $coowners,
                   7210:                            );
                   7211:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7212:         if ($putresult eq 'ok') {
                   7213:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7214:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7215:             }
                   7216:         }
                   7217:     }
                   7218:     if ($delcoowners) {
                   7219:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7220:         if ($delresult eq 'ok') {
                   7221:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7222:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7223:             }
                   7224:         }
                   7225:     }
                   7226:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7227:         my %crsinfo =
                   7228:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7229:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7230:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7231:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7232:         }
                   7233:     }
                   7234: }
                   7235: 
1.169     harris41 7236: # -------------------------------------------------- Modify user authentication
1.197     www      7237: # Overrides without validation
                   7238: 
1.169     harris41 7239: sub modifyuserauth {
                   7240:     my ($udom,$uname,$umode,$upass)=@_;
                   7241:     my $uhome=&homeserver($uname,$udom);
1.197     www      7242:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7243:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7244:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7245:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7246:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7247: 		     &escape($upass),$uhome);
1.620     albertel 7248:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7249:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7250:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7251:     &log($udom,,$uname,$uhome,
1.620     albertel 7252:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7253:                                      $env{'user.name'}.', '.$umode.
1.197     www      7254:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7255:     unless ($reply eq 'ok') {
1.197     www      7256:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7257: 	return 'error: '.$reply;
                   7258:     }   
1.170     harris41 7259:     return 'ok';
1.80      www      7260: }
                   7261: 
1.81      www      7262: # --------------------------------------------------------------- Modify a user
1.80      www      7263: 
1.81      www      7264: sub modifyuser {
1.206     matthew  7265:     my ($udom,    $uname, $uid,
                   7266:         $umode,   $upass, $first,
                   7267:         $middle,  $last,  $gene,
1.1058    raeburn  7268:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7269:     $udom= &LONCAPA::clean_domain($udom);
                   7270:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7271:     my $showcandelete = 'none';
                   7272:     if (ref($candelete) eq 'ARRAY') {
                   7273:         if (@{$candelete} > 0) {
                   7274:             $showcandelete = join(', ',@{$candelete});
                   7275:         }
                   7276:     }
1.81      www      7277:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7278:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7279: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7280:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7281:                                      ' desiredhome not specified'). 
1.620     albertel 7282:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7283:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7284:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7285:     my $newuser;
                   7286:     if ($uhome eq 'no_host') {
                   7287:         $newuser = 1;
                   7288:     }
1.80      www      7289: # ----------------------------------------------------------------- Create User
1.406     albertel 7290:     if (($uhome eq 'no_host') && 
                   7291: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7292:         my $unhome='';
1.844     albertel 7293:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7294:             $unhome = $desiredhome;
1.620     albertel 7295: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7296: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7297:         } else { # load balancing routine for determining $unhome
1.81      www      7298:             my $loadm=10000000;
1.841     albertel 7299: 	    my %servers = &get_servers($udom,'library');
                   7300: 	    foreach my $tryserver (keys(%servers)) {
                   7301: 		my $answer=reply('load',$tryserver);
                   7302: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7303: 		    $loadm=$answer;
                   7304: 		    $unhome=$tryserver;
                   7305: 		}
1.80      www      7306: 	    }
                   7307:         }
                   7308:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7309: 	    return 'error: unable to find a home server for '.$uname.
                   7310:                    ' in domain '.$udom;
1.80      www      7311:         }
                   7312:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7313:                          &escape($upass),$unhome);
                   7314: 	unless ($reply eq 'ok') {
                   7315:             return 'error: '.$reply;
                   7316:         }   
1.230     stredwic 7317:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7318:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7319: 	    return 'error: unable verify users home machine.';
1.80      www      7320:         }
1.209     matthew  7321:     }   # End of creation of new user
1.80      www      7322: # ---------------------------------------------------------------------- Add ID
                   7323:     if ($uid) {
                   7324:        $uid=~tr/A-Z/a-z/;
                   7325:        my %uidhash=&idrget($udom,$uname);
1.196     www      7326:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7327:          && (!$forceid)) {
1.80      www      7328: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7329: 	      return 'error: user id "'.$uid.'" does not match '.
                   7330:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7331:           }
                   7332:        } else {
                   7333: 	  &idput($udom,($uname => $uid));
                   7334:        }
                   7335:     }
                   7336: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7337:     my @tmp=&get('environment',
1.899     raeburn  7338: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7339:                     'permanentemail','inststatus'],
1.134     albertel 7340: 		   $udom,$uname);
1.1075    raeburn  7341:     my (%names,%oldnames);
1.313     matthew  7342:     if ($tmp[0] =~ m/^error:.*/) { 
                   7343:         %names=(); 
                   7344:     } else {
                   7345:         %names = @tmp;
1.1075    raeburn  7346:         %oldnames = %names;
1.313     matthew  7347:     }
1.388     www      7348: #
1.1058    raeburn  7349: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7350: # of users did not contain them), do not overwrite existing values
                   7351: # unless field is in $candelete array ref.  
                   7352: #
                   7353: 
                   7354:     my @fields = ('firstname','middlename','lastname','generation',
                   7355:                   'permanentemail','id');
                   7356:     my %newvalues;
                   7357:     if (ref($candelete) eq 'ARRAY') {
                   7358:         foreach my $field (@fields) {
                   7359:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7360:                 if ($field eq 'firstname') {
                   7361:                     $names{$field} = $first;
                   7362:                 } elsif ($field eq 'middlename') {
                   7363:                     $names{$field} = $middle;
                   7364:                 } elsif ($field eq 'lastname') {
                   7365:                     $names{$field} = $last;
                   7366:                 } elsif ($field eq 'generation') { 
                   7367:                     $names{$field} = $gene;
                   7368:                 } elsif ($field eq 'permanentemail') {
                   7369:                     $names{$field} = $email;
                   7370:                 } elsif ($field eq 'id') {
                   7371:                     $names{$field}  = $uid;
                   7372:                 }
                   7373:             }
                   7374:         }
                   7375:     }
1.388     www      7376:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7377:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7378:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7379:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7380:     if ($email) {
                   7381:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7382:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7383:     }
1.899     raeburn  7384:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7385:     if (defined($inststatus)) {
                   7386:         $names{'inststatus'} = '';
                   7387:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7388:         if (ref($usertypes) eq 'HASH') {
                   7389:             my @okstatuses; 
                   7390:             foreach my $item (split(/:/,$inststatus)) {
                   7391:                 if (defined($usertypes->{$item})) {
                   7392:                     push(@okstatuses,$item);  
                   7393:                 }
                   7394:             }
                   7395:             if (@okstatuses) {
                   7396:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7397:             }
                   7398:         }
                   7399:     }
1.1075    raeburn  7400:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7401:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7402:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7403:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7404:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7405:     } else {
                   7406:         $logmsg .= ' during self creation';
                   7407:     }
1.1075    raeburn  7408:     my $changed;
                   7409:     if ($newuser) {
                   7410:         $changed = 1;
                   7411:     } else {
                   7412:         foreach my $field (@fields) {
                   7413:             if ($names{$field} ne $oldnames{$field}) {
                   7414:                 $changed = 1;
                   7415:                 last;
                   7416:             }
                   7417:         }
                   7418:     }
                   7419:     unless ($changed) {
                   7420:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7421:         &logthis($logmsg);
                   7422:         return 'ok';
                   7423:     }
                   7424:     my $reply = &put('environment', \%names, $udom,$uname);
                   7425:     if ($reply ne 'ok') { 
                   7426:         return 'error: '.$reply;
                   7427:     }
1.1087    raeburn  7428:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7429:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7430:     }
1.1075    raeburn  7431:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7432:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7433:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7434:     &logthis($logmsg);
1.134     albertel 7435:     return 'ok';
1.80      www      7436: }
                   7437: 
1.81      www      7438: # -------------------------------------------------------------- Modify student
1.80      www      7439: 
1.81      www      7440: sub modifystudent {
                   7441:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7442:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7443:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7444:     if (!$cid) {
1.620     albertel 7445: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7446: 	    return 'not_in_class';
                   7447: 	}
1.80      www      7448:     }
                   7449: # --------------------------------------------------------------- Make the user
1.81      www      7450:     my $reply=&modifyuser
1.209     matthew  7451: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7452:          $desiredhome,$email,$inststatus);
1.80      www      7453:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7454:     # This will cause &modify_student_enrollment to get the uid from the
                   7455:     # students environment
                   7456:     $uid = undef if (!$forceid);
1.455     albertel 7457:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7458: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7459:     return $reply;
                   7460: }
                   7461: 
                   7462: sub modify_student_enrollment {
1.957     raeburn  7463:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7464:     my ($cdom,$cnum,$chome);
                   7465:     if (!$cid) {
1.620     albertel 7466: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7467: 	    return 'not_in_class';
                   7468: 	}
1.620     albertel 7469: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7470: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7471:     } else {
                   7472: 	($cdom,$cnum)=split(/_/,$cid);
                   7473:     }
1.620     albertel 7474:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7475:     if (!$chome) {
1.457     raeburn  7476: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7477:     }
1.455     albertel 7478:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7479:     # Make sure the user exists
1.81      www      7480:     my $uhome=&homeserver($uname,$udom);
                   7481:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7482: 	return 'error: no such user';
                   7483:     }
1.297     matthew  7484:     # Get student data if we were not given enough information
                   7485:     if (!defined($first)  || $first  eq '' || 
                   7486:         !defined($last)   || $last   eq '' || 
                   7487:         !defined($uid)    || $uid    eq '' || 
                   7488:         !defined($middle) || $middle eq '' || 
                   7489:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7490:         # They did not supply us with enough data to enroll the student, so
                   7491:         # we need to pick up more information.
1.297     matthew  7492:         my %tmp = &get('environment',
1.294     matthew  7493:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7494:                        ,$udom,$uname);
                   7495: 
1.800     albertel 7496:         #foreach my $key (keys(%tmp)) {
                   7497:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7498:         #}
1.294     matthew  7499:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7500:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7501:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7502:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7503:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7504:     }
1.556     albertel 7505:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7506:     my $reply=cput('classlist',
                   7507: 		   {"$uname:$udom" => 
1.515     raeburn  7508: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7509: 		   $cdom,$cnum);
1.81      www      7510:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7511: 	return 'error: '.$reply;
1.652     albertel 7512:     } else {
                   7513: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7514:     }
1.297     matthew  7515:     # Add student role to user
1.83      www      7516:     my $uurl='/'.$cid;
1.81      www      7517:     $uurl=~s/\_/\//g;
                   7518:     if ($usec) {
                   7519: 	$uurl.='/'.$usec;
                   7520:     }
1.957     raeburn  7521:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7522: }
                   7523: 
1.556     albertel 7524: sub format_name {
                   7525:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7526:     my $name;
                   7527:     if ($first ne 'lastname') {
                   7528: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7529:     } else {
                   7530: 	if ($lastname=~/\S/) {
                   7531: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7532: 	    $name=~s/\s+,/,/;
                   7533: 	} else {
                   7534: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7535: 	}
                   7536:     }
                   7537:     $name=~s/^\s+//;
                   7538:     $name=~s/\s+$//;
                   7539:     $name=~s/\s+/ /g;
                   7540:     return $name;
                   7541: }
                   7542: 
1.84      www      7543: # ------------------------------------------------- Write to course preferences
                   7544: 
                   7545: sub writecoursepref {
                   7546:     my ($courseid,%prefs)=@_;
                   7547:     $courseid=~s/^\///;
                   7548:     $courseid=~s/\_/\//g;
                   7549:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7550:     my $chome=homeserver($cnum,$cdomain);
                   7551:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7552: 	return 'error: no such course';
                   7553:     }
                   7554:     my $cstring='';
1.800     albertel 7555:     foreach my $pref (keys(%prefs)) {
                   7556: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7557:     }
1.84      www      7558:     $cstring=~s/\&$//;
                   7559:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7560: }
                   7561: 
                   7562: # ---------------------------------------------------------- Make/modify course
                   7563: 
                   7564: sub createcourse {
1.741     raeburn  7565:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7566:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7567:     $url=&declutter($url);
                   7568:     my $cid='';
1.1028    raeburn  7569:     if ($context eq 'requestcourses') {
                   7570:         my $can_create = 0;
                   7571:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7572:         if ($udom eq $ownerdom) {
                   7573:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7574:                                   $context)) {
                   7575:                 $can_create = 1;
                   7576:             }
                   7577:         } else {
                   7578:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7579:                                            $category);
                   7580:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7581:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7582:                 if (@curr > 0) {
                   7583:                     my @options = qw(approval validate autolimit);
                   7584:                     my $optregex = join('|',@options);
                   7585:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7586:                         $can_create = 1;
                   7587:                     }
                   7588:                 }
                   7589:             }
                   7590:         }
                   7591:         if ($can_create) {
                   7592:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7593:                 unless (&allowed('ccc',$udom)) {
                   7594:                     return 'refused'; 
                   7595:                 }
1.1017    raeburn  7596:             }
                   7597:         } else {
                   7598:             return 'refused';
                   7599:         }
1.1028    raeburn  7600:     } elsif (!&allowed('ccc',$udom)) {
                   7601:         return 'refused';
1.84      www      7602:     }
1.1011    raeburn  7603: # --------------------------------------------------------------- Get Unique ID
                   7604:     my $uname;
                   7605:     if ($cnum =~ /^$match_courseid$/) {
                   7606:         my $chome=&homeserver($cnum,$udom,'true');
                   7607:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7608:             $uname = $cnum;
                   7609:         } else {
1.1038    raeburn  7610:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7611:         }
                   7612:     } else {
1.1038    raeburn  7613:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7614:     }
                   7615:     return $uname if ($uname =~ /^error/);
                   7616: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7617:     if (!defined($course_server)) {
                   7618:         if (defined(&domain($udom,'primary'))) {
                   7619:             $course_server = &domain($udom,'primary');
                   7620:         } else {
                   7621:             $course_server = $env{'user.home'}; 
                   7622:         }
                   7623:     }
                   7624:     my %host_servers =
                   7625:         &Apache::lonnet::get_servers($udom,'library');
                   7626:     unless ($host_servers{$course_server}) {
                   7627:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7628:     }
1.84      www      7629: # ------------------------------------------------------------- Make the course
                   7630:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7631:                       $course_server);
1.84      www      7632:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7633:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7634:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7635: 	return 'error: no such course';
                   7636:     }
1.271     www      7637: # ----------------------------------------------------------------- Course made
1.516     raeburn  7638: # log existence
1.1029    raeburn  7639:     my $now = time;
1.918     raeburn  7640:     my $newcourse = {
                   7641:                     $udom.'_'.$uname => {
1.921     raeburn  7642:                                      description => $description,
                   7643:                                      inst_code   => $inst_code,
                   7644:                                      owner       => $course_owner,
                   7645:                                      type        => $crstype,
1.1029    raeburn  7646:                                      creator     => $env{'user.name'}.':'.
                   7647:                                                     $env{'user.domain'},
                   7648:                                      created     => $now,
                   7649:                                      context     => $context,
1.918     raeburn  7650:                                                 },
                   7651:                     };
1.921     raeburn  7652:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7653: # set toplevel url
1.271     www      7654:     my $topurl=$url;
                   7655:     unless ($nonstandard) {
                   7656: # ------------------------------------------ For standard courses, make top url
                   7657:         my $mapurl=&clutter($url);
1.278     www      7658:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7659:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7660: <map>
                   7661: <resource id="1" type="start"></resource>
                   7662: <resource id="2" src="$mapurl"></resource>
                   7663: <resource id="3" type="finish"></resource>
                   7664: <link index="1" from="1" to="2"></link>
                   7665: <link index="2" from="2" to="3"></link>
                   7666: </map>
                   7667: ENDINITMAP
                   7668:         $topurl=&declutter(
1.638     albertel 7669:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7670:                           );
                   7671:     }
                   7672: # ----------------------------------------------------------- Write preferences
1.84      www      7673:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7674:                      ('description'              => $description,
                   7675:                       'url'                      => $topurl,
                   7676:                       'internal.creator'         => $env{'user.name'}.':'.
                   7677:                                                     $env{'user.domain'},
                   7678:                       'internal.created'         => $now,
                   7679:                       'internal.creationcontext' => $context)
                   7680:                     );
1.84      www      7681:     return '/'.$udom.'/'.$uname;
                   7682: }
                   7683: 
1.1011    raeburn  7684: # ------------------------------------------------------------------- Create ID
                   7685: sub generate_coursenum {
1.1038    raeburn  7686:     my ($udom,$crstype) = @_;
1.1011    raeburn  7687:     my $domdesc = &domain($udom);
                   7688:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7689:     my $first;
                   7690:     if ($crstype eq 'Community') {
                   7691:         $first = '0';
                   7692:     } else {
                   7693:         $first = int(1+rand(9)); 
                   7694:     } 
                   7695:     my $uname=$first.
1.1011    raeburn  7696:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7697:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7698:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7699: # ----------------------------------------------- Make sure that does not exist
                   7700:     my $uhome=&homeserver($uname,$udom,'true');
                   7701:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7702:         if ($crstype eq 'Community') {
                   7703:             $first = '0';
                   7704:         } else {
                   7705:             $first = int(1+rand(9));
                   7706:         }
                   7707:         $uname=$first.
1.1011    raeburn  7708:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7709:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7710:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7711:         $uhome=&homeserver($uname,$udom,'true');
                   7712:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7713:             return 'error: unable to generate unique course-ID';
                   7714:         }
                   7715:     }
                   7716:     return $uname;
                   7717: }
                   7718: 
1.813     albertel 7719: sub is_course {
                   7720:     my ($cdom,$cnum) = @_;
                   7721:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7722: 				undef,'.');
1.813     albertel 7723:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7724:         return 1;
                   7725:     }
                   7726:     return 0;
                   7727: }
                   7728: 
1.1015    raeburn  7729: sub store_userdata {
                   7730:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7731:     my $result;
1.1016    raeburn  7732:     if ($datakey ne '') {
1.1013    raeburn  7733:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7734:             if ($udom eq '' || $uname eq '') {
                   7735:                 $udom = $env{'user.domain'};
                   7736:                 $uname = $env{'user.name'};
                   7737:             }
                   7738:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7739:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7740:                 $result = 'error: no_host';
                   7741:             } else {
                   7742:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7743:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7744: 
                   7745:                 my $namevalue='';
                   7746:                 foreach my $key (keys(%{$storehash})) {
                   7747:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7748:                 }
                   7749:                 $namevalue=~s/\&$//;
1.1105    raeburn  7750:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7751:                                   $namevalue,$uhome);
1.1013    raeburn  7752:             }
                   7753:         } else {
                   7754:             $result = 'error: data to store was not a hash reference'; 
                   7755:         }
                   7756:     } else {
                   7757:         $result= 'error: invalid requestkey'; 
                   7758:     }
                   7759:     return $result;
                   7760: }
                   7761: 
1.21      www      7762: # ---------------------------------------------------------- Assign Custom Role
                   7763: 
                   7764: sub assigncustomrole {
1.957     raeburn  7765:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7766:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7767:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7768: }
                   7769: 
                   7770: # ----------------------------------------------------------------- Revoke Role
                   7771: 
                   7772: sub revokerole {
1.957     raeburn  7773:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7774:     my $now=time;
1.965     raeburn  7775:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7776: }
                   7777: 
                   7778: # ---------------------------------------------------------- Revoke Custom Role
                   7779: 
                   7780: sub revokecustomrole {
1.957     raeburn  7781:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7782:     my $now=time;
1.357     www      7783:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7784:            $deleteflag,$selfenroll,$context);
1.17      www      7785: }
                   7786: 
1.533     banghart 7787: # ------------------------------------------------------------ Disk usage
1.535     albertel 7788: sub diskusage {
1.955     raeburn  7789:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7790:     $directorypath =~ s/\/$//;
                   7791:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7792:                        .&escape($getpropath).':'.&escape($uname).':'
                   7793:                        .&escape($udom),homeserver($uname,$udom));
                   7794:     if ($listing eq 'unknown_cmd') {
                   7795:         if ($getpropath) {
                   7796:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7797:         }
                   7798:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7799:     }
1.514     albertel 7800:     return $listing;
1.512     banghart 7801: }
                   7802: 
1.566     banghart 7803: sub is_locked {
1.1096    raeburn  7804:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7805:     my @check;
                   7806:     my $is_locked;
1.1093    raeburn  7807:     push (@check,$file_name);
1.613     albertel 7808:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7809: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7810:     my ($tmp)=keys(%locked);
                   7811:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7812:     
1.566     banghart 7813:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7814:         $is_locked = 'false';
                   7815:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7816:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7817:                $is_locked = 'true';
1.1096    raeburn  7818:                if (ref($which) eq 'ARRAY') {
                   7819:                    push(@{$which},$entry);
                   7820:                } else {
                   7821:                    last;
                   7822:                }
1.745     raeburn  7823:            }
                   7824:        }
1.566     banghart 7825:     } else {
                   7826:         $is_locked = 'false';
                   7827:     }
1.1093    raeburn  7828:     return $is_locked;
1.566     banghart 7829: }
                   7830: 
1.759     albertel 7831: sub declutter_portfile {
                   7832:     my ($file) = @_;
1.833     albertel 7833:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7834:     return $file;
                   7835: }
                   7836: 
1.559     banghart 7837: # ------------------------------------------------------------- Mark as Read Only
                   7838: 
                   7839: sub mark_as_readonly {
                   7840:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7841:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7842:     my ($tmp)=keys(%current_permissions);
                   7843:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7844:     foreach my $file (@{$files}) {
1.759     albertel 7845: 	$file = &declutter_portfile($file);
1.561     banghart 7846:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7847:     }
1.613     albertel 7848:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7849:     return;
                   7850: }
                   7851: 
1.572     banghart 7852: # ------------------------------------------------------------Save Selected Files
                   7853: 
                   7854: sub save_selected_files {
                   7855:     my ($user, $path, @files) = @_;
                   7856:     my $filename = $user."savedfiles";
1.573     banghart 7857:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7858:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7859:     foreach my $file (@files) {
1.620     albertel 7860:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7861:     }
                   7862:     foreach my $file (@other_files) {
1.574     banghart 7863:         print (OUT $file."\n");
1.572     banghart 7864:     }
1.574     banghart 7865:     close (OUT);
1.572     banghart 7866:     return 'ok';
                   7867: }
                   7868: 
1.574     banghart 7869: sub clear_selected_files {
                   7870:     my ($user) = @_;
                   7871:     my $filename = $user."savedfiles";
1.1117    foxr     7872:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7873:     print (OUT undef);
                   7874:     close (OUT);
                   7875:     return ("ok");    
                   7876: }
                   7877: 
1.572     banghart 7878: sub files_in_path {
                   7879:     my ($user, $path) = @_;
                   7880:     my $filename = $user."savedfiles";
                   7881:     my %return_files;
1.1117    foxr     7882:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7883:     while (my $line_in = <IN>) {
1.574     banghart 7884:         chomp ($line_in);
                   7885:         my @paths_and_file = split (m!/!, $line_in);
                   7886:         my $file_part = pop (@paths_and_file);
                   7887:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7888:         $path_part.='/';
                   7889:         my $path_and_file = $path_part.$file_part;
                   7890:         if ($path_part eq $path) {
                   7891:             $return_files{$file_part}= 'selected';
                   7892:         }
                   7893:     }
1.574     banghart 7894:     close (IN);
                   7895:     return (\%return_files);
1.572     banghart 7896: }
                   7897: 
                   7898: # called in portfolio select mode, to show files selected NOT in current directory
                   7899: sub files_not_in_path {
                   7900:     my ($user, $path) = @_;
                   7901:     my $filename = $user."savedfiles";
                   7902:     my @return_files;
                   7903:     my $path_part;
1.1117    foxr     7904:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7905:     while (my $line = <IN>) {
1.572     banghart 7906:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7907:         my @paths_and_file = split(m|/|, $line);
                   7908:         my $file_part = pop(@paths_and_file);
                   7909:         chomp($file_part);
                   7910:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7911:         $path_part .= '/';
                   7912:         my $path_and_file = $path_part.$file_part;
                   7913:         if ($path_part ne $path) {
1.800     albertel 7914:             push(@return_files, ($path_and_file));
1.572     banghart 7915:         }
                   7916:     }
1.800     albertel 7917:     close(OUT);
1.574     banghart 7918:     return (@return_files);
1.572     banghart 7919: }
                   7920: 
1.745     raeburn  7921: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7922: 
1.745     raeburn  7923: sub get_portfile_permissions {
                   7924:     my ($domain,$user) = @_;
1.613     albertel 7925:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7926:     my ($tmp)=keys(%current_permissions);
                   7927:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7928:     return \%current_permissions;
                   7929: }
                   7930: 
                   7931: #---------------------------------------------Get portfolio file access controls
                   7932: 
1.749     raeburn  7933: sub get_access_controls {
1.745     raeburn  7934:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7935:     my %access;
                   7936:     my $real_file = $file;
                   7937:     $file =~ s/\.meta$//;
1.745     raeburn  7938:     if (defined($file)) {
1.749     raeburn  7939:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7940:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7941:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7942:             }
                   7943:         }
1.745     raeburn  7944:     } else {
1.749     raeburn  7945:         foreach my $key (keys(%{$current_permissions})) {
                   7946:             if ($key =~ /\0accesscontrol$/) {
                   7947:                 if (defined($group)) {
                   7948:                     if ($key !~ m-^\Q$group\E/-) {
                   7949:                         next;
                   7950:                     }
                   7951:                 }
                   7952:                 my ($fullpath) = split(/\0/,$key);
                   7953:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7954:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7955:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7956:                     }
                   7957:                 }
                   7958:             }
                   7959:         }
                   7960:     }
                   7961:     return %access;
                   7962: }
                   7963: 
                   7964: sub modify_access_controls {
                   7965:     my ($file_name,$changes,$domain,$user)=@_;
                   7966:     my ($outcome,$deloutcome);
                   7967:     my %store_permissions;
                   7968:     my %new_values;
                   7969:     my %new_control;
                   7970:     my %translation;
                   7971:     my @deletions = ();
                   7972:     my $now = time;
                   7973:     if (exists($$changes{'activate'})) {
                   7974:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7975:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7976:             my $numnew = scalar(@newitems);
                   7977:             for (my $i=0; $i<$numnew; $i++) {
                   7978:                 my $newkey = $newitems[$i];
                   7979:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7980:                 if ($newkey =~ /^\d+:/) { 
                   7981:                     $newkey =~ s/^(\d+)/$newid/;
                   7982:                     $translation{$1} = $newid;
                   7983:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7984:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7985:                     $translation{$1} = $newid;
                   7986:                 }
1.749     raeburn  7987:                 $new_values{$file_name."\0".$newkey} = 
                   7988:                                           $$changes{'activate'}{$newitems[$i]};
                   7989:                 $new_control{$newkey} = $now;
                   7990:             }
                   7991:         }
                   7992:     }
                   7993:     my %todelete;
                   7994:     my %changed_items;
                   7995:     foreach my $action ('delete','update') {
                   7996:         if (exists($$changes{$action})) {
                   7997:             if (ref($$changes{$action}) eq 'HASH') {
                   7998:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7999:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8000:                     if ($action eq 'delete') { 
                   8001:                         $todelete{$itemnum} = 1;
                   8002:                     } else {
                   8003:                         $changed_items{$itemnum} = $key;
                   8004:                     }
                   8005:                 }
1.745     raeburn  8006:             }
                   8007:         }
1.749     raeburn  8008:     }
                   8009:     # get lock on access controls for file.
                   8010:     my $lockhash = {
                   8011:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8012:                                                        ':'.$env{'user.domain'},
                   8013:                    }; 
                   8014:     my $tries = 0;
                   8015:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8016:    
                   8017:     while (($gotlock ne 'ok') && $tries <3) {
                   8018:         $tries ++;
                   8019:         sleep 1;
                   8020:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8021:     }
                   8022:     if ($gotlock eq 'ok') {
                   8023:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8024:         my ($tmp)=keys(%curr_permissions);
                   8025:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8026:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8027:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8028:             if (ref($curr_controls) eq 'HASH') {
                   8029:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8030:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8031:                     if (defined($todelete{$itemnum})) {
                   8032:                         push(@deletions,$file_name."\0".$control_item);
                   8033:                     } else {
                   8034:                         if (defined($changed_items{$itemnum})) {
                   8035:                             $new_control{$changed_items{$itemnum}} = $now;
                   8036:                             push(@deletions,$file_name."\0".$control_item);
                   8037:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8038:                         } else {
                   8039:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8040:                         }
                   8041:                     }
1.745     raeburn  8042:                 }
                   8043:             }
                   8044:         }
1.970     raeburn  8045:         my ($group);
                   8046:         if (&is_course($domain,$user)) {
                   8047:             ($group,my $file) = split(/\//,$file_name,2);
                   8048:         }
1.749     raeburn  8049:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8050:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8051:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8052:         #  remove lock
                   8053:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8054:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8055:         my $sqlresult =
1.970     raeburn  8056:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8057:                                     $group);
1.749     raeburn  8058:     } else {
                   8059:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8060:     }
1.749     raeburn  8061:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8062: }
                   8063: 
1.827     raeburn  8064: sub make_public_indefinitely {
                   8065:     my ($requrl) = @_;
                   8066:     my $now = time;
                   8067:     my $action = 'activate';
                   8068:     my $aclnum = 0;
                   8069:     if (&is_portfolio_url($requrl)) {
                   8070:         my (undef,$udom,$unum,$file_name,$group) =
                   8071:             &parse_portfolio_url($requrl);
                   8072:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8073:         my %access_controls = &get_access_controls($current_perms,
                   8074:                                                    $group,$file_name);
                   8075:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8076:             my ($num,$scope,$end,$start) = 
                   8077:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8078:             if ($scope eq 'public') {
                   8079:                 if ($start <= $now && $end == 0) {
                   8080:                     $action = 'none';
                   8081:                 } else {
                   8082:                     $action = 'update';
                   8083:                     $aclnum = $num;
                   8084:                 }
                   8085:                 last;
                   8086:             }
                   8087:         }
                   8088:         if ($action eq 'none') {
                   8089:              return 'ok';
                   8090:         } else {
                   8091:             my %changes;
                   8092:             my $newend = 0;
                   8093:             my $newstart = $now;
                   8094:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8095:             $changes{$action}{$newkey} = {
                   8096:                 type => 'public',
                   8097:                 time => {
                   8098:                     start => $newstart,
                   8099:                     end   => $newend,
                   8100:                 },
                   8101:             };
                   8102:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8103:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8104:             return $outcome;
                   8105:         }
                   8106:     } else {
                   8107:         return 'invalid';
                   8108:     }
                   8109: }
                   8110: 
1.745     raeburn  8111: #------------------------------------------------------Get Marked as Read Only
                   8112: 
                   8113: sub get_marked_as_readonly {
                   8114:     my ($domain,$user,$what,$group) = @_;
                   8115:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8116:     my @readonly_files;
1.629     banghart 8117:     my $cmp1=$what;
                   8118:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8119:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8120:         if (defined($group)) {
                   8121:             if ($file_name !~ m-^\Q$group\E/-) {
                   8122:                 next;
                   8123:             }
                   8124:         }
1.561     banghart 8125:         if (ref($value) eq "ARRAY"){
                   8126:             foreach my $stored_what (@{$value}) {
1.629     banghart 8127:                 my $cmp2=$stored_what;
1.759     albertel 8128:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8129:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8130:                 }
1.629     banghart 8131:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8132:                     push(@readonly_files, $file_name);
1.745     raeburn  8133:                     last;
1.563     banghart 8134:                 } elsif (!defined($what)) {
                   8135:                     push(@readonly_files, $file_name);
1.745     raeburn  8136:                     last;
1.561     banghart 8137:                 }
                   8138:             }
1.745     raeburn  8139:         }
1.561     banghart 8140:     }
                   8141:     return @readonly_files;
                   8142: }
1.577     banghart 8143: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8144: 
1.577     banghart 8145: sub get_marked_as_readonly_hash {
1.745     raeburn  8146:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8147:     my %readonly_files;
1.745     raeburn  8148:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8149:         if (defined($group)) {
                   8150:             if ($file_name !~ m-^\Q$group\E/-) {
                   8151:                 next;
                   8152:             }
                   8153:         }
1.577     banghart 8154:         if (ref($value) eq "ARRAY"){
                   8155:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8156:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8157:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8158:                         if ($lock_descriptor eq 'graded') {
                   8159:                             $readonly_files{$file_name} = 'graded';
                   8160:                         } elsif ($lock_descriptor eq 'handback') {
                   8161:                             $readonly_files{$file_name} = 'handback';
                   8162:                         } else {
                   8163:                             if (!exists($readonly_files{$file_name})) {
                   8164:                                 $readonly_files{$file_name} = 'locked';
                   8165:                             }
                   8166:                         }
1.745     raeburn  8167:                     }
1.750     banghart 8168:                 } 
1.577     banghart 8169:             }
                   8170:         } 
                   8171:     }
                   8172:     return %readonly_files;
                   8173: }
1.559     banghart 8174: # ------------------------------------------------------------ Unmark as Read Only
                   8175: 
                   8176: sub unmark_as_readonly {
1.629     banghart 8177:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8178:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8179:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8180:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8181:     my $symb_crs = $what;
                   8182:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8183:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8184:     my ($tmp)=keys(%current_permissions);
                   8185:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8186:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8187:     foreach my $file (@readonly_files) {
1.759     albertel 8188: 	my $clean_file = &declutter_portfile($file);
                   8189: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8190: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8191:         my @new_locks;
                   8192:         my @del_keys;
                   8193:         if (ref($current_locks) eq "ARRAY"){
                   8194:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8195:                 my $compare=$locker;
1.749     raeburn  8196:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8197:                     $compare=join('',@{$locker});
1.746     raeburn  8198:                     if ($compare ne $symb_crs) {
                   8199:                         push(@new_locks, $locker);
                   8200:                     }
1.563     banghart 8201:                 }
                   8202:             }
1.650     albertel 8203:             if (scalar(@new_locks) > 0) {
1.563     banghart 8204:                 $current_permissions{$file} = \@new_locks;
                   8205:             } else {
                   8206:                 push(@del_keys, $file);
1.613     albertel 8207:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8208:                 delete($current_permissions{$file});
1.563     banghart 8209:             }
                   8210:         }
1.561     banghart 8211:     }
1.613     albertel 8212:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8213:     return;
                   8214: }
1.512     banghart 8215: 
1.17      www      8216: # ------------------------------------------------------------ Directory lister
                   8217: 
                   8218: sub dirlist {
1.955     raeburn  8219:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8220:     $uri=~s/^\///;
                   8221:     $uri=~s/\/$//;
1.253     stredwic 8222:     my ($udom, $uname);
1.955     raeburn  8223:     if ($getuserdir) {
1.253     stredwic 8224:         $udom = $userdomain;
                   8225:         $uname = $username;
1.955     raeburn  8226:     } else {
                   8227:         (undef,$udom,$uname)=split(/\//,$uri);
                   8228:         if(defined($userdomain)) {
                   8229:             $udom = $userdomain;
                   8230:         }
                   8231:         if(defined($username)) {
                   8232:             $uname = $username;
                   8233:         }
1.253     stredwic 8234:     }
1.955     raeburn  8235:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8236: 
1.955     raeburn  8237:     $dirRoot = $perlvar{'lonDocRoot'};
                   8238:     if (defined($getpropath)) {
                   8239:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8240:         $dirRoot =~ s/\/$//;
1.955     raeburn  8241:     } elsif (defined($getuserdir)) {
                   8242:         my $subdir=$uname.'__';
                   8243:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8244:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8245:                    ."/$udom/$subdir/$uname";
                   8246:     } elsif (defined($alternateRoot)) {
                   8247:         $dirRoot = $alternateRoot;
1.751     banghart 8248:     }
1.253     stredwic 8249: 
                   8250:     if($udom) {
                   8251:         if($uname) {
1.1135    raeburn  8252:             my $uhome = &homeserver($uname,$udom);
1.1136  ! raeburn  8253:             if ($uhome eq 'no_host') {
        !          8254:                 return ([],'no_host');
        !          8255:             }
1.955     raeburn  8256:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8257:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8258:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8259:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8260:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8261:             } else {
                   8262:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8263:             }
1.605     matthew  8264:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8265:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8266:                 @listing_results = split(/:/,$listing);
                   8267:             } else {
                   8268:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8269:             }
1.1135    raeburn  8270:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136  ! raeburn  8271:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
        !          8272:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
        !          8273:                 return ([],$listing);
        !          8274:             } else {
        !          8275:                 return (\@listing_results);
1.1135    raeburn  8276:             }
1.955     raeburn  8277:         } elsif(!$alternateRoot) {
1.1136  ! raeburn  8278:             my (%allusers,%listerror);
1.841     albertel 8279: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8280:  	    foreach my $tryserver (keys(%servers)) {
                   8281:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8282:                                   &escape($udom),$tryserver);
                   8283:                 if ($listing eq 'unknown_cmd') {
                   8284: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8285: 				      $udom, $tryserver);
                   8286:                 } else {
                   8287:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8288:                 }
1.841     albertel 8289: 		if ($listing eq 'unknown_cmd') {
                   8290: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8291: 				      $udom, $tryserver);
                   8292: 		    @listing_results = split(/:/,$listing);
                   8293: 		} else {
                   8294: 		    @listing_results =
                   8295: 			map { &unescape($_); } split(/:/,$listing);
                   8296: 		}
1.1136  ! raeburn  8297:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
        !          8298:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
        !          8299:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
        !          8300:                     $listerror{$tryserver} = $listing;
        !          8301:                 } else {
1.841     albertel 8302: 		    foreach my $line (@listing_results) {
                   8303: 			my ($entry) = split(/&/,$line,2);
                   8304: 			$allusers{$entry} = 1;
                   8305: 		    }
                   8306: 		}
1.253     stredwic 8307:             }
1.1136  ! raeburn  8308:             my @alluserslist=();
1.800     albertel 8309:             foreach my $user (sort(keys(%allusers))) {
1.1136  ! raeburn  8310:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8311:             }
1.1136  ! raeburn  8312:             return (\@alluserslist);
1.253     stredwic 8313:         } else {
1.1136  ! raeburn  8314:             return ([],'missing username');
1.253     stredwic 8315:         }
1.955     raeburn  8316:     } elsif(!defined($getpropath)) {
1.1136  ! raeburn  8317:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
        !          8318:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
        !          8319:         return (\@all_domains);
1.955     raeburn  8320:     } else {
1.1136  ! raeburn  8321:         return ([],'missing domain');
1.275     stredwic 8322:     }
                   8323: }
                   8324: 
                   8325: # --------------------------------------------- GetFileTimestamp
                   8326: # This function utilizes dirlist and returns the date stamp for
                   8327: # when it was last modified.  It will also return an error of -1
                   8328: # if an error occurs
                   8329: 
                   8330: sub GetFileTimestamp {
1.955     raeburn  8331:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8332:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8333:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136  ! raeburn  8334:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
        !          8335:                                     undef,$getuserdir);
        !          8336:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
        !          8337:         return -1;
        !          8338:     }
        !          8339:     if (ref($fileref) eq 'ARRAY') {
        !          8340:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8341:         # @stats contains first the filename, then the stat output
                   8342:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8343:     } else {
                   8344:         return -1;
1.253     stredwic 8345:     }
1.26      www      8346: }
                   8347: 
1.712     albertel 8348: sub stat_file {
                   8349:     my ($uri) = @_;
1.787     albertel 8350:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8351: 
1.955     raeburn  8352:     my ($udom,$uname,$file);
1.712     albertel 8353:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8354: 	($udom,$uname,$file) =
1.811     albertel 8355: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8356: 	$file = 'userfiles/'.$file;
                   8357:     }
                   8358:     if ($uri =~ m-^/res/-) {
                   8359: 	($udom,$uname) = 
1.807     albertel 8360: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8361: 	$file = $uri;
                   8362:     }
                   8363: 
                   8364:     if (!$udom || !$uname || !$file) {
                   8365: 	# unable to handle the uri
                   8366: 	return ();
                   8367:     }
1.956     raeburn  8368:     my $getpropath;
                   8369:     if ($file =~ /^userfiles\//) {
                   8370:         $getpropath = 1;
                   8371:     }
1.1136  ! raeburn  8372:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
        !          8373:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
        !          8374:         return ();
        !          8375:     } else {
        !          8376:         if (ref($listref) eq 'ARRAY') {
        !          8377:             my @stats = split('&',$listref->[0]);
        !          8378: 	    shift(@stats); #filename is first
        !          8379: 	    return @stats;
        !          8380:         }
1.712     albertel 8381:     }
                   8382:     return ();
                   8383: }
                   8384: 
1.26      www      8385: # -------------------------------------------------------- Value of a Condition
                   8386: 
1.713     albertel 8387: # gets the value of a specific preevaluated condition
                   8388: #    stored in the string  $env{user.state.<cid>}
                   8389: # or looks up a condition reference in the bighash and if if hasn't
                   8390: # already been evaluated recurses into docondval to get the value of
                   8391: # the condition, then memoizing it to 
                   8392: #   $env{user.state.<cid>.<condition>}
1.40      www      8393: sub directcondval {
                   8394:     my $number=shift;
1.620     albertel 8395:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8396: 	&Apache::lonuserstate::evalstate();
                   8397:     }
1.713     albertel 8398:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8399: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8400:     } elsif ($number =~ /^_/) {
                   8401: 	my $sub_condition;
                   8402: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8403: 		&GDBM_READER(),0640)) {
                   8404: 	    $sub_condition=$bighash{'conditions'.$number};
                   8405: 	    untie(%bighash);
                   8406: 	}
                   8407: 	my $value = &docondval($sub_condition);
1.949     raeburn  8408: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8409: 	return $value;
                   8410:     }
1.620     albertel 8411:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8412:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8413:     } else {
                   8414:        return 2;
                   8415:     }
                   8416: }
                   8417: 
1.713     albertel 8418: # get the collection of conditions for this resource
1.26      www      8419: sub condval {
                   8420:     my $condidx=shift;
1.54      www      8421:     my $allpathcond='';
1.713     albertel 8422:     foreach my $cond (split(/\|/,$condidx)) {
                   8423: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8424: 	    $allpathcond.=
                   8425: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8426: 	}
1.191     harris41 8427:     }
1.54      www      8428:     $allpathcond=~s/\|$//;
1.713     albertel 8429:     return &docondval($allpathcond);
                   8430: }
                   8431: 
                   8432: #evaluates an expression of conditions
                   8433: sub docondval {
                   8434:     my ($allpathcond) = @_;
                   8435:     my $result=0;
                   8436:     if ($env{'request.course.id'}
                   8437: 	&& defined($allpathcond)) {
                   8438: 	my $operand='|';
                   8439: 	my @stack;
                   8440: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8441: 	    if ($chunk eq '(') {
                   8442: 		push @stack,($operand,$result);
                   8443: 	    } elsif ($chunk eq ')') {
                   8444: 		my $before=pop @stack;
                   8445: 		if (pop @stack eq '&') {
                   8446: 		    $result=$result>$before?$before:$result;
                   8447: 		} else {
                   8448: 		    $result=$result>$before?$result:$before;
                   8449: 		}
                   8450: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8451: 		$operand=$chunk;
                   8452: 	    } else {
                   8453: 		my $new=directcondval($chunk);
                   8454: 		if ($operand eq '&') {
                   8455: 		    $result=$result>$new?$new:$result;
                   8456: 		} else {
                   8457: 		    $result=$result>$new?$result:$new;
                   8458: 		}
                   8459: 	    }
                   8460: 	}
1.26      www      8461:     }
                   8462:     return $result;
1.421     albertel 8463: }
                   8464: 
                   8465: # ---------------------------------------------------- Devalidate courseresdata
                   8466: 
                   8467: sub devalidatecourseresdata {
                   8468:     my ($coursenum,$coursedomain)=@_;
                   8469:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8470:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8471: }
                   8472: 
1.763     www      8473: 
1.200     www      8474: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8475: #
                   8476: #  Parameters:
                   8477: #      $coursenum    - Number of the course.
                   8478: #      $coursedomain - Domain at which the course was created.
                   8479: #  Returns:
                   8480: #     A hash of the course parameters along (I think) with timestamps
                   8481: #     and version info.
1.877     foxr     8482: 
1.624     albertel 8483: sub get_courseresdata {
                   8484:     my ($coursenum,$coursedomain)=@_;
1.200     www      8485:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8486:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8487:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8488:     my %dumpreply;
1.417     albertel 8489:     unless (defined($cached)) {
1.624     albertel 8490: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8491: 	$result=\%dumpreply;
1.251     albertel 8492: 	my ($tmp) = keys(%dumpreply);
                   8493: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8494: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8495: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8496: 	    return $tmp;
1.416     albertel 8497: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8498: 	    $result=undef;
1.599     albertel 8499: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8500: 	}
                   8501:     }
1.624     albertel 8502:     return $result;
                   8503: }
                   8504: 
1.633     albertel 8505: sub devalidateuserresdata {
                   8506:     my ($uname,$udom)=@_;
                   8507:     my $hashid="$udom:$uname";
                   8508:     &devalidate_cache_new('userres',$hashid);
                   8509: }
                   8510: 
1.624     albertel 8511: sub get_userresdata {
                   8512:     my ($uname,$udom)=@_;
                   8513:     #most student don\'t have any data set, check if there is some data
                   8514:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8515: 
                   8516:     my $hashid="$udom:$uname";
                   8517:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8518:     if (!defined($cached)) {
                   8519: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8520: 	$result=\%resourcedata;
                   8521: 	&do_cache_new('userres',$hashid,$result,600);
                   8522:     }
                   8523:     my ($tmp)=keys(%$result);
                   8524:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8525: 	return $result;
                   8526:     }
                   8527:     #error 2 occurs when the .db doesn't exist
                   8528:     if ($tmp!~/error: 2 /) {
1.672     albertel 8529: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8530: 		 " Trying to get resource data for ".
                   8531: 		 $uname." at ".$udom.": ".
                   8532: 		 $tmp."</font>");
                   8533:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8534: 	#&EXT_cache_set($udom,$uname);
                   8535: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8536: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8537:     }
                   8538:     return $tmp;
                   8539: }
1.879     foxr     8540: #----------------------------------------------- resdata - return resource data
                   8541: #  Purpose:
                   8542: #    Return resource data for either users or for a course.
                   8543: #  Parameters:
                   8544: #     $name      - Course/user name.
                   8545: #     $domain    - Name of the domain the user/course is registered on.
                   8546: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8547: #     @which     - Array of names of resources desired.
                   8548: #  Returns:
                   8549: #     The value of the first reasource in @which that is found in the
                   8550: #     resource hash.
                   8551: #  Exceptional Conditions:
                   8552: #     If the $type passed in is not valid (not the string 'course' or 
                   8553: #     'user', an undefined  reference is returned.
                   8554: #     If none of the resources are found, an undef is returned
1.624     albertel 8555: sub resdata {
                   8556:     my ($name,$domain,$type,@which)=@_;
                   8557:     my $result;
                   8558:     if ($type eq 'course') {
                   8559: 	$result=&get_courseresdata($name,$domain);
                   8560:     } elsif ($type eq 'user') {
                   8561: 	$result=&get_userresdata($name,$domain);
                   8562:     }
                   8563:     if (!ref($result)) { return $result; }    
1.251     albertel 8564:     foreach my $item (@which) {
1.927     albertel 8565: 	if (defined($result->{$item->[0]})) {
                   8566: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8567: 	}
1.250     albertel 8568:     }
1.291     albertel 8569:     return undef;
1.200     www      8570: }
                   8571: 
1.379     matthew  8572: #
                   8573: # EXT resource caching routines
                   8574: #
                   8575: 
                   8576: sub clear_EXT_cache_status {
1.383     albertel 8577:     &delenv('cache.EXT.');
1.379     matthew  8578: }
                   8579: 
                   8580: sub EXT_cache_status {
                   8581:     my ($target_domain,$target_user) = @_;
1.383     albertel 8582:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8583:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8584:         # We know already the user has no data
                   8585:         return 1;
                   8586:     } else {
                   8587:         return 0;
                   8588:     }
                   8589: }
                   8590: 
                   8591: sub EXT_cache_set {
                   8592:     my ($target_domain,$target_user) = @_;
1.383     albertel 8593:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8594:     #&appenv({$cachename => time});
1.379     matthew  8595: }
                   8596: 
1.28      www      8597: # --------------------------------------------------------- Value of a Variable
1.58      www      8598: sub EXT {
1.715     albertel 8599: 
1.395     albertel 8600:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8601:     unless ($varname) { return ''; }
1.218     albertel 8602:     #get real user name/domain, courseid and symb
                   8603:     my $courseid;
1.359     albertel 8604:     my $publicuser;
1.427     www      8605:     if ($symbparm) {
                   8606: 	$symbparm=&get_symb_from_alias($symbparm);
                   8607:     }
1.218     albertel 8608:     if (!($uname && $udom)) {
1.790     albertel 8609:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8610:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8611:     } else {
1.620     albertel 8612: 	$courseid=$env{'request.course.id'};
1.218     albertel 8613:     }
1.48      www      8614:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8615:     my $rest;
1.320     albertel 8616:     if (defined($therest[0])) {
1.48      www      8617:        $rest=join('.',@therest);
                   8618:     } else {
                   8619:        $rest='';
                   8620:     }
1.320     albertel 8621: 
1.57      www      8622:     my $qualifierrest=$qualifier;
                   8623:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8624:     my $spacequalifierrest=$space;
                   8625:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8626:     if ($realm eq 'user') {
1.48      www      8627: # --------------------------------------------------------------- user.resource
                   8628: 	if ($space eq 'resource') {
1.651     albertel 8629: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8630: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8631: 		 &&
1.744     albertel 8632: 		 ($symbparm eq &symbread()) ) {	
                   8633: 		# if we are in the middle of processing the resource the
                   8634: 		# get the value we are planning on committing
                   8635:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8636:                     return $Apache::lonhomework::results{$qualifierrest};
                   8637:                 } else {
                   8638:                     return $Apache::lonhomework::history{$qualifierrest};
                   8639:                 }
1.335     albertel 8640: 	    } else {
1.359     albertel 8641: 		my %restored;
1.620     albertel 8642: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8643: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8644: 		} else {
                   8645: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8646: 		}
1.335     albertel 8647: 		return $restored{$qualifierrest};
                   8648: 	    }
1.48      www      8649: # ----------------------------------------------------------------- user.access
                   8650:         } elsif ($space eq 'access') {
1.218     albertel 8651: 	    # FIXME - not supporting calls for a specific user
1.48      www      8652:             return &allowed($qualifier,$rest);
                   8653: # ------------------------------------------ user.preferences, user.environment
                   8654:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8655: 	    if (($uname eq $env{'user.name'}) &&
                   8656: 		($udom eq $env{'user.domain'})) {
                   8657: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8658: 	    } else {
1.359     albertel 8659: 		my %returnhash;
                   8660: 		if (!$publicuser) {
                   8661: 		    %returnhash=&userenvironment($udom,$uname,
                   8662: 						 $qualifierrest);
                   8663: 		}
1.218     albertel 8664: 		return $returnhash{$qualifierrest};
                   8665: 	    }
1.48      www      8666: # ----------------------------------------------------------------- user.course
                   8667:         } elsif ($space eq 'course') {
1.218     albertel 8668: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8669:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8670: # ------------------------------------------------------------------- user.role
                   8671:         } elsif ($space eq 'role') {
1.218     albertel 8672: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8673:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8674:             if ($qualifier eq 'value') {
                   8675: 		return $role;
                   8676:             } elsif ($qualifier eq 'extent') {
                   8677:                 return $where;
                   8678:             }
                   8679: # ----------------------------------------------------------------- user.domain
                   8680:         } elsif ($space eq 'domain') {
1.218     albertel 8681:             return $udom;
1.48      www      8682: # ------------------------------------------------------------------- user.name
                   8683:         } elsif ($space eq 'name') {
1.218     albertel 8684:             return $uname;
1.48      www      8685: # ---------------------------------------------------- Any other user namespace
1.29      www      8686:         } else {
1.359     albertel 8687: 	    my %reply;
                   8688: 	    if (!$publicuser) {
                   8689: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8690: 	    }
                   8691: 	    return $reply{$qualifierrest};
1.48      www      8692:         }
1.236     www      8693:     } elsif ($realm eq 'query') {
                   8694: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8695:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8696: 						[$spacequalifierrest]);
1.620     albertel 8697: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8698:    } elsif ($realm eq 'request') {
1.48      www      8699: # ------------------------------------------------------------- request.browser
                   8700:         if ($space eq 'browser') {
1.430     www      8701: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8702: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8703: 		    return 1;
                   8704: 		} else {
                   8705: 		    return 0;
                   8706: 		}
                   8707: 	    } else {
1.620     albertel 8708: 		return $env{'browser.'.$qualifier};
1.430     www      8709: 	    }
1.57      www      8710: # ------------------------------------------------------------ request.filename
                   8711:         } else {
1.620     albertel 8712:             return $env{'request.'.$spacequalifierrest};
1.29      www      8713:         }
1.28      www      8714:     } elsif ($realm eq 'course') {
1.48      www      8715: # ---------------------------------------------------------- course.description
1.620     albertel 8716:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8717:     } elsif ($realm eq 'resource') {
1.165     www      8718: 
1.620     albertel 8719: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8720: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8721: 	}
1.693     albertel 8722: 
                   8723: 	if ($space eq 'title') {
                   8724: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8725: 	    return &gettitle($symbparm);
                   8726: 	}
                   8727: 	
                   8728: 	if ($space eq 'map') {
                   8729: 	    my ($map) = &decode_symb($symbparm);
                   8730: 	    return &symbread($map);
                   8731: 	}
1.905     albertel 8732: 	if ($space eq 'filename') {
                   8733: 	    if ($symbparm) {
                   8734: 		return &clutter((&decode_symb($symbparm))[2]);
                   8735: 	    }
                   8736: 	    return &hreflocation('',$env{'request.filename'});
                   8737: 	}
1.693     albertel 8738: 
                   8739: 	my ($section, $group, @groups);
1.593     albertel 8740: 	my ($courselevelm,$courselevel);
1.539     albertel 8741: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8742: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8743: 
1.218     albertel 8744: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8745: 
1.60      www      8746: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8747: 	    my $symbp=$symbparm;
1.735     albertel 8748: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8749: 
                   8750: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8751: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8752: 
1.620     albertel 8753: 	    if (($env{'user.name'} eq $uname) &&
                   8754: 		($env{'user.domain'} eq $udom)) {
                   8755: 		$section=$env{'request.course.sec'};
1.733     raeburn  8756:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8757:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8758: 	    } else {
1.539     albertel 8759: 		if (! defined($usection)) {
1.551     albertel 8760: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8761: 		} else {
                   8762: 		    $section = $usection;
                   8763: 		}
1.733     raeburn  8764:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8765: 	    }
                   8766: 
                   8767: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8768: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8769: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8770: 
1.593     albertel 8771: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8772: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8773: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8774: 
1.60      www      8775: # ----------------------------------------------------------- first, check user
1.624     albertel 8776: 
                   8777: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8778: 				       ([$courselevelr,'resource'],
                   8779: 					[$courselevelm,'map'     ],
                   8780: 					[$courselevel, 'course'  ]));
1.931     albertel 8781: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8782: 
1.594     albertel 8783: # ------------------------------------------------ second, check some of course
1.684     raeburn  8784:             my $coursereply;
1.691     raeburn  8785:             if (@groups > 0) {
                   8786:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8787:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8788:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8789:             }
1.96      www      8790: 
1.684     raeburn  8791: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8792: 				  $env{'course.'.$courseid.'.domain'},
                   8793: 				  'course',
                   8794: 				  ([$seclevelr,   'resource'],
                   8795: 				   [$seclevelm,   'map'     ],
                   8796: 				   [$seclevel,    'course'  ],
                   8797: 				   [$courselevelr,'resource']));
                   8798: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8799: 
1.60      www      8800: # ------------------------------------------------------ third, check map parms
1.218     albertel 8801: 	    my %parmhash=();
                   8802: 	    my $thisparm='';
                   8803: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8804: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8805: 		    &GDBM_READER(),0640)) {
1.218     albertel 8806: 		$thisparm=$parmhash{$symbparm};
                   8807: 		untie(%parmhash);
                   8808: 	    }
1.927     albertel 8809: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8810: 	}
1.594     albertel 8811: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8812: 
1.218     albertel 8813: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8814: 	my $filename;
                   8815: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8816: 	if ($symbparm) {
1.409     www      8817: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8818: 	} else {
1.620     albertel 8819: 	    $filename=$env{'request.filename'};
1.282     albertel 8820: 	}
                   8821: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8822: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8823: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8824: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8825: 
1.927     albertel 8826: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8827: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8828: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8829: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8830: 				     $env{'course.'.$courseid.'.domain'},
                   8831: 				     'course',
1.927     albertel 8832: 				     ([$courselevelm,'map'   ],
                   8833: 				      [$courselevel, 'course']));
                   8834: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8835: 	}
1.145     www      8836: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8837: 	unless ($space eq '0') {
1.336     albertel 8838: 	    my @parts=split(/_/,$space);
                   8839: 	    my $id=pop(@parts);
                   8840: 	    my $part=join('_',@parts);
                   8841: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8842: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8843: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8844: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8845: 	}
1.395     albertel 8846: 	if ($recurse) { return undef; }
                   8847: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8848: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8849: # ---------------------------------------------------- Any other user namespace
                   8850:     } elsif ($realm eq 'environment') {
                   8851: # ----------------------------------------------------------------- environment
1.620     albertel 8852: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8853: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8854: 	} else {
1.770     albertel 8855: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8856: 		return '';
                   8857: 	    }
1.219     albertel 8858: 	    my %returnhash=&userenvironment($udom,$uname,
                   8859: 					    $spacequalifierrest);
                   8860: 	    return $returnhash{$spacequalifierrest};
                   8861: 	}
1.28      www      8862:     } elsif ($realm eq 'system') {
1.48      www      8863: # ----------------------------------------------------------------- system.time
                   8864: 	if ($space eq 'time') {
                   8865: 	    return time;
                   8866:         }
1.696     albertel 8867:     } elsif ($realm eq 'server') {
                   8868: # ----------------------------------------------------------------- system.time
                   8869: 	if ($space eq 'name') {
                   8870: 	    return $ENV{'SERVER_NAME'};
                   8871:         }
1.28      www      8872:     }
1.48      www      8873:     return '';
1.61      www      8874: }
                   8875: 
1.927     albertel 8876: sub get_reply {
                   8877:     my ($reply_value) = @_;
1.940     raeburn  8878:     if (ref($reply_value) eq 'ARRAY') {
                   8879:         if (wantarray) {
                   8880: 	    return @$reply_value;
                   8881:         }
                   8882:         return $reply_value->[0];
                   8883:     } else {
                   8884:         return $reply_value;
1.927     albertel 8885:     }
                   8886: }
                   8887: 
1.691     raeburn  8888: sub check_group_parms {
                   8889:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8890:     my @groupitems = ();
                   8891:     my $resultitem;
1.927     albertel 8892:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8893:     foreach my $group (@{$groups}) {
                   8894:         foreach my $level (@levels) {
1.927     albertel 8895:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8896:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8897:         }
                   8898:     }
                   8899:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8900:                             $env{'course.'.$courseid.'.domain'},
                   8901:                                      'course',@groupitems);
                   8902:     return $coursereply;
                   8903: }
                   8904: 
                   8905: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8906:     my ($courseid,@groups) = @_;
                   8907:     @groups = sort(@groups);
1.691     raeburn  8908:     return @groups;
                   8909: }
                   8910: 
1.395     albertel 8911: sub packages_tab_default {
                   8912:     my ($uri,$varname)=@_;
                   8913:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8914: 
                   8915:     my (@extension,@specifics,$do_default);
                   8916:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8917: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8918: 	if ($pack_type eq 'default') {
                   8919: 	    $do_default=1;
                   8920: 	} elsif ($pack_type eq 'extension') {
                   8921: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8922: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8923: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8924: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8925: 	}
                   8926:     }
                   8927:     # first look for a package that matches the requested part id
                   8928:     foreach my $package (@specifics) {
                   8929: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8930: 	next if ($pack_part ne $part);
                   8931: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8932: 	    return $packagetab{"$pack_type&$name&default"};
                   8933: 	}
                   8934:     }
                   8935:     # look for any possible matching non extension_ package
                   8936:     foreach my $package (@specifics) {
                   8937: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8938: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8939: 	    return $packagetab{"$pack_type&$name&default"};
                   8940: 	}
1.585     albertel 8941: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8942: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8943: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8944: 	}
                   8945:     }
1.738     albertel 8946:     # look for any posible extension_ match
                   8947:     foreach my $package (@extension) {
                   8948: 	my ($package,$pack_type)=@{$package};
                   8949: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8950: 	    return $packagetab{"$pack_type&$name&default"};
                   8951: 	}
                   8952: 	if (defined($packagetab{$package."&$name&default"})) {
                   8953: 	    return $packagetab{$package."&$name&default"};
                   8954: 	}
                   8955:     }
                   8956:     # look for a global default setting
                   8957:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8958: 	return $packagetab{"default&$name&default"};
                   8959:     }
1.395     albertel 8960:     return undef;
                   8961: }
                   8962: 
1.334     albertel 8963: sub add_prefix_and_part {
                   8964:     my ($prefix,$part)=@_;
                   8965:     my $keyroot;
                   8966:     if (defined($prefix) && $prefix !~ /^__/) {
                   8967: 	# prefix that has a part already
                   8968: 	$keyroot=$prefix;
                   8969:     } elsif (defined($prefix)) {
                   8970: 	# prefix that is missing a part
                   8971: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8972:     } else {
                   8973: 	# no prefix at all
                   8974: 	if (defined($part)) { $keyroot='_'.$part; }
                   8975:     }
                   8976:     return $keyroot;
                   8977: }
                   8978: 
1.71      www      8979: # ---------------------------------------------------------------- Get metadata
                   8980: 
1.599     albertel 8981: my %metaentry;
1.1070    www      8982: my %importedpartids;
1.71      www      8983: sub metadata {
1.176     www      8984:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8985:     $uri=&declutter($uri);
1.288     albertel 8986:     # if it is a non metadata possible uri return quickly
1.529     albertel 8987:     if (($uri eq '') || 
                   8988: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8989: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8990:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8991: 	return undef;
                   8992:     }
                   8993:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8994: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8995: 	return undef;
1.288     albertel 8996:     }
1.73      www      8997:     my $filename=$uri;
                   8998:     $uri=~s/\.meta$//;
1.172     www      8999: #
                   9000: # Is the metadata already cached?
1.177     www      9001: # Look at timestamp of caching
1.172     www      9002: # Everything is cached by the main uri, libraries are never directly cached
                   9003: #
1.428     albertel 9004:     if (!defined($liburi)) {
1.599     albertel 9005: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9006: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9007:     }
                   9008:     {
1.1069    www      9009: # Imported parts would go here
1.1070    www      9010:         my %importedids=();
                   9011:         my @origfileimportpartids=();
1.1069    www      9012:         my $importedparts=0;
1.172     www      9013: #
                   9014: # Is this a recursive call for a library?
                   9015: #
1.599     albertel 9016: #	if (! exists($metacache{$uri})) {
                   9017: #	    $metacache{$uri}={};
                   9018: #	}
1.924     albertel 9019: 	my $cachetime = 60*60;
1.171     www      9020:         if ($liburi) {
                   9021: 	    $liburi=&declutter($liburi);
                   9022:             $filename=$liburi;
1.401     bowersj2 9023:         } else {
1.599     albertel 9024: 	    &devalidate_cache_new('meta',$uri);
                   9025: 	    undef(%metaentry);
1.401     bowersj2 9026: 	}
1.140     www      9027:         my %metathesekeys=();
1.73      www      9028:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9029: 	my $metastring;
1.924     albertel 9030: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 9031: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9032: 	    $metastring = 
1.929     albertel 9033: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9034: 					  ('grade_target' => 'meta'));
                   9035: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9036: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9037:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9038: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9039: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9040: 	    $metastring=&getfile($file);
1.489     albertel 9041: 	}
1.208     albertel 9042:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9043:         my $token;
1.140     www      9044:         undef %metathesekeys;
1.71      www      9045:         while ($token=$parser->get_token) {
1.339     albertel 9046: 	    if ($token->[0] eq 'S') {
                   9047: 		if (defined($token->[2]->{'package'})) {
1.172     www      9048: #
                   9049: # This is a package - get package info
                   9050: #
1.339     albertel 9051: 		    my $package=$token->[2]->{'package'};
                   9052: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9053: 		    if (defined($token->[2]->{'id'})) { 
                   9054: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9055: 		    }
1.599     albertel 9056: 		    if ($metaentry{':packages'}) {
                   9057: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9058: 		    } else {
1.599     albertel 9059: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9060: 		    }
1.736     albertel 9061: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9062: 			my $part=$keyroot;
                   9063: 			$part=~s/^\_//;
1.736     albertel 9064: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9065: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9066: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9067: 			    # ignore package.tab specified default values
                   9068:                             # here &package_tab_default() will fetch those
                   9069: 			    if ($subp eq 'default') { next; }
1.736     albertel 9070: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9071: 			    my $unikey;
                   9072: 			    if ($pack =~ /_0$/) {
                   9073: 				$unikey='parameter_0_'.$name;
                   9074: 				$part=0;
                   9075: 			    } else {
                   9076: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9077: 			    }
1.339     albertel 9078: 			    if ($subp eq 'display') {
                   9079: 				$value.=' [Part: '.$part.']';
                   9080: 			    }
1.599     albertel 9081: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9082: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9083: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9084: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9085: 			    }
1.599     albertel 9086: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9087: 				$metaentry{':'.$unikey}=
                   9088: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9089: 			    }
1.339     albertel 9090: 			}
                   9091: 		    }
                   9092: 		} else {
1.172     www      9093: #
                   9094: # This is not a package - some other kind of start tag
1.339     albertel 9095: #
                   9096: 		    my $entry=$token->[1];
1.1068    www      9097: 		    my $unikey='';
1.175     www      9098: 
1.339     albertel 9099: 		    if ($entry eq 'import') {
1.175     www      9100: #
                   9101: # Importing a library here
1.339     albertel 9102: #
1.1067    www      9103:                         my $location=$parser->get_text('/import');
                   9104:                         my $dir=$filename;
                   9105:                         $dir=~s|[^/]*$||;
                   9106:                         $location=&filelocation($dir,$location);
1.1069    www      9107:                        
1.1068    www      9108:                         my $importmode=$token->[2]->{'importmode'};
                   9109:                         if ($importmode eq 'problem') {
1.1069    www      9110: # Import as problem/response
1.1068    www      9111:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9112:                         } elsif ($importmode eq 'part') {
                   9113: # Import as part(s)
1.1069    www      9114:                            $importedparts=1;
                   9115: # We need to get the original file and the imported file to get the part order correct
                   9116: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9117: # Load and inspect original file
1.1070    www      9118:                            if ($#origfileimportpartids<0) {
                   9119:                               undef(%importedpartids);
                   9120:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9121:                               my $origfile=&getfile($origfilelocation);
                   9122:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9123:                            }
                   9124: 
1.1069    www      9125: # Load and inspect imported file
                   9126:                            my $impfile=&getfile($location);
                   9127:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9128:                            if ($#impfilepartids>=0) {
                   9129: # This problem had parts
1.1070    www      9130:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9131:                            } else {
                   9132: # Importing by turning a single problem into a problem part
                   9133: # It gets the import-tags ID as part-ID
                   9134:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9135:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9136:                            }
1.1068    www      9137:                         } else {
                   9138: # Normal import
                   9139:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9140:                            if (defined($token->[2]->{'id'})) {
                   9141:                               $unikey.='_'.$token->[2]->{'id'};
                   9142:                            }
1.1067    www      9143:                         }
                   9144: 
1.339     albertel 9145: 			if ($depthcount<20) {
1.736     albertel 9146: 			    my $metadata = 
                   9147: 				&metadata($uri,'keys', $location,$unikey,
                   9148: 					  $depthcount+1);
                   9149: 			    foreach my $meta (split(',',$metadata)) {
                   9150: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9151: 				$metathesekeys{$meta}=1;
1.339     albertel 9152: 			    }
1.1068    www      9153: 			
                   9154:                         }
1.1067    www      9155: 		    } else {
                   9156: #
                   9157: # Not importing, some other kind of non-package, non-library start tag
                   9158: # 
                   9159:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9160:                         if (defined($token->[2]->{'id'})) {
                   9161:                             $unikey.='_'.$token->[2]->{'id'};
                   9162:                         }
1.339     albertel 9163: 			if (defined($token->[2]->{'name'})) { 
                   9164: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9165: 			}
                   9166: 			$metathesekeys{$unikey}=1;
1.736     albertel 9167: 			foreach my $param (@{$token->[3]}) {
                   9168: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9169: 				$token->[2]->{$param};
1.339     albertel 9170: 			}
                   9171: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9172: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9173: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9174: 		 # only ws inside the tag, and not in default, so use default
                   9175: 		 # as value
1.599     albertel 9176: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9177: 			} elsif ( $internaltext =~ /\S/ ) {
                   9178: 		  # something interesting inside the tag
                   9179: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9180: 			} else {
1.908     albertel 9181: 		  # no interesting values, don't set a default
1.339     albertel 9182: 			}
1.172     www      9183: # end of not-a-package not-a-library import
1.339     albertel 9184: 		    }
1.172     www      9185: # end of not-a-package start tag
1.339     albertel 9186: 		}
1.172     www      9187: # the next is the end of "start tag"
1.339     albertel 9188: 	    }
                   9189: 	}
1.483     albertel 9190: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9191: 	$extension = lc($extension);
                   9192: 	if ($extension eq 'htm') { $extension='html'; }
                   9193: 
1.737     albertel 9194: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9195: 	    #no specific packages #how's our extension
                   9196: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9197: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9198: 					 \%metathesekeys);
                   9199: 	}
1.883     albertel 9200: 
                   9201: 	if (!exists($metaentry{':packages'})
                   9202: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9203: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9204: 		#no specific packages well let's get default then
                   9205: 		if ($key!~/^default&/) { next; }
1.488     albertel 9206: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9207: 					     \%metathesekeys);
                   9208: 	    }
                   9209: 	}
1.338     www      9210: # are there custom rights to evaluate
1.599     albertel 9211: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9212: 
1.338     www      9213:     #
                   9214:     # Importing a rights file here
1.339     albertel 9215:     #
                   9216: 	    unless ($depthcount) {
1.599     albertel 9217: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9218: 		my $dir=$filename;
                   9219: 		$dir=~s|[^/]*$||;
                   9220: 		$location=&filelocation($dir,$location);
1.736     albertel 9221: 		my $rights_metadata =
                   9222: 		    &metadata($uri,'keys',$location,'_rights',
                   9223: 			      $depthcount+1);
                   9224: 		foreach my $rights (split(',',$rights_metadata)) {
                   9225: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9226: 		    $metathesekeys{$rights}=1;
1.339     albertel 9227: 		}
                   9228: 	    }
                   9229: 	}
1.737     albertel 9230: 	# uniqifiy package listing
                   9231: 	my %seen;
                   9232: 	my @uniq_packages =
                   9233: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9234: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9235: 
1.1070    www      9236:         if ($importedparts) {
                   9237: # We had imported parts and need to rebuild partorder
                   9238:            $metaentry{':partorder'}='';
                   9239:            $metathesekeys{'partorder'}=1;
                   9240:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9241:                if ($origfileimportpartids[$index] eq 'part') {
                   9242: # original part, part of the problem
                   9243:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9244:                } else {
                   9245: # we have imported parts at this position
                   9246:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9247:                }
                   9248:            }
                   9249:            $metaentry{':partorder'}=~s/^\,//;
                   9250:         }
                   9251: 
1.737     albertel 9252: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9253: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9254: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9255: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9256: # this is the end of "was not already recently cached
1.71      www      9257:     }
1.599     albertel 9258:     return $metaentry{':'.$what};
1.261     albertel 9259: }
                   9260: 
1.488     albertel 9261: sub metadata_create_package_def {
1.483     albertel 9262:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9263:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9264:     if ($subp eq 'default') { next; }
                   9265:     
1.599     albertel 9266:     if (defined($metaentry{':packages'})) {
                   9267: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9268:     } else {
1.599     albertel 9269: 	$metaentry{':packages'}=$package;
1.483     albertel 9270:     }
                   9271:     my $value=$packagetab{$key};
                   9272:     my $unikey;
                   9273:     $unikey='parameter_0_'.$name;
1.599     albertel 9274:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9275:     $$metathesekeys{$unikey}=1;
1.599     albertel 9276:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9277: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9278:     }
1.599     albertel 9279:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9280: 	$metaentry{':'.$unikey}=
                   9281: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9282:     }
                   9283: }
                   9284: 
1.261     albertel 9285: sub metadata_generate_part0 {
                   9286:     my ($metadata,$metacache,$uri) = @_;
                   9287:     my %allnames;
1.737     albertel 9288:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9289: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9290: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9291: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9292: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9293: 	    $allnames{$name}=$part;
                   9294: 	  }
                   9295: 	}
                   9296:     }
                   9297:     foreach my $name (keys(%allnames)) {
                   9298:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9299:       my $key=":parameter_0_$name";
1.261     albertel 9300:       $$metacache{"$key.part"}='0';
                   9301:       $$metacache{"$key.name"}=$name;
1.428     albertel 9302:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9303: 					   $allnames{$name}.'_'.$name.
                   9304: 					   '.type'};
1.428     albertel 9305:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9306: 			     '.display'};
1.644     www      9307:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9308:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9309:       $$metacache{"$key.display"}=$olddis;
                   9310:     }
1.71      www      9311: }
                   9312: 
1.764     albertel 9313: # ------------------------------------------------------ Devalidate title cache
                   9314: 
                   9315: sub devalidate_title_cache {
                   9316:     my ($url)=@_;
                   9317:     if (!$env{'request.course.id'}) { return; }
                   9318:     my $symb=&symbread($url);
                   9319:     if (!$symb) { return; }
                   9320:     my $key=$env{'request.course.id'}."\0".$symb;
                   9321:     &devalidate_cache_new('title',$key);
                   9322: }
                   9323: 
1.1014    droeschl 9324: # ------------------------------------------------- Get the title of a course
                   9325: 
                   9326: sub current_course_title {
                   9327:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9328: }
1.301     www      9329: # ------------------------------------------------- Get the title of a resource
                   9330: 
                   9331: sub gettitle {
                   9332:     my $urlsymb=shift;
                   9333:     my $symb=&symbread($urlsymb);
1.534     albertel 9334:     if ($symb) {
1.620     albertel 9335: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9336: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9337: 	if (defined($cached)) { 
                   9338: 	    return $result;
                   9339: 	}
1.534     albertel 9340: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9341: 	my $title='';
1.907     albertel 9342: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9343: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9344: 	} else {
                   9345: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9346: 		    &GDBM_READER(),0640)) {
                   9347: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9348: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9349: 		untie(%bighash);
                   9350: 	    }
1.534     albertel 9351: 	}
                   9352: 	$title=~s/\&colon\;/\:/gs;
                   9353: 	if ($title) {
1.599     albertel 9354: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9355: 	}
                   9356: 	$urlsymb=$url;
                   9357:     }
                   9358:     my $title=&metadata($urlsymb,'title');
                   9359:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9360:     return $title;
1.301     www      9361: }
1.613     albertel 9362: 
1.614     albertel 9363: sub get_slot {
                   9364:     my ($which,$cnum,$cdom)=@_;
                   9365:     if (!$cnum || !$cdom) {
1.790     albertel 9366: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9367: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9368: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9369:     }
1.703     albertel 9370:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9371:     my %slotinfo;
                   9372:     if (exists($remembered{$key})) {
                   9373: 	$slotinfo{$which} = $remembered{$key};
                   9374:     } else {
                   9375: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9376: 	&Apache::lonhomework::showhash(%slotinfo);
                   9377: 	my ($tmp)=keys(%slotinfo);
                   9378: 	if ($tmp=~/^error:/) { return (); }
                   9379: 	$remembered{$key} = $slotinfo{$which};
                   9380:     }
1.616     albertel 9381:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9382: 	return %{$slotinfo{$which}};
                   9383:     }
                   9384:     return $slotinfo{$which};
1.614     albertel 9385: }
1.31      www      9386: # ------------------------------------------------- Update symbolic store links
                   9387: 
                   9388: sub symblist {
                   9389:     my ($mapname,%newhash)=@_;
1.438     www      9390:     $mapname=&deversion(&declutter($mapname));
1.31      www      9391:     my %hash;
1.620     albertel 9392:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9393:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9394:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9395: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9396: 		next if ($url eq 'last_known'
                   9397: 			 && $env{'form.no_update_last_known'});
                   9398: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9399: 						    $newhash{$url}->[1],
                   9400: 						    $newhash{$url}->[0]);
1.191     harris41 9401:             }
1.31      www      9402:             if (untie(%hash)) {
                   9403: 		return 'ok';
                   9404:             }
                   9405:         }
                   9406:     }
                   9407:     return 'error';
1.212     www      9408: }
                   9409: 
                   9410: # --------------------------------------------------------------- Verify a symb
                   9411: 
                   9412: sub symbverify {
1.510     www      9413:     my ($symb,$thisurl)=@_;
                   9414:     my $thisfn=$thisurl;
1.439     www      9415:     $thisfn=&declutter($thisfn);
1.215     www      9416: # direct jump to resource in page or to a sequence - will construct own symbs
                   9417:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9418: # check URL part
1.409     www      9419:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9420: 
1.431     www      9421:     unless ($url eq $thisfn) { return 0; }
1.213     www      9422: 
1.216     www      9423:     $symb=&symbclean($symb);
1.510     www      9424:     $thisurl=&deversion($thisurl);
1.439     www      9425:     $thisfn=&deversion($thisfn);
1.213     www      9426: 
                   9427:     my %bighash;
                   9428:     my $okay=0;
1.431     www      9429: 
1.620     albertel 9430:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9431:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9432:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9433:             $thisurl =~ s/\?.+$//;
                   9434:         }
1.510     www      9435:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9436:         unless ($ids) {
                   9437:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9438:             $ids=$bighash{$idkey};
1.216     www      9439:         }
                   9440:         if ($ids) {
                   9441: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9442: 	    foreach my $id (split(/\,/,$ids)) {
                   9443: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9444:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9445:                    $symb =~ s/\?.+$//;
                   9446:                }
1.216     www      9447:                if (
                   9448:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9449:    eq $symb) { 
1.620     albertel 9450: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9451: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9452:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9453: 		       $okay=1; 
                   9454: 		   }
                   9455: 	       }
1.216     www      9456: 	   }
                   9457:         }
1.213     www      9458: 	untie(%bighash);
                   9459:     }
                   9460:     return $okay;
1.31      www      9461: }
                   9462: 
1.210     www      9463: # --------------------------------------------------------------- Clean-up symb
                   9464: 
                   9465: sub symbclean {
                   9466:     my $symb=shift;
1.568     albertel 9467:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9468: # remove version from map
                   9469:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9470: 
1.210     www      9471: # remove version from URL
                   9472:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9473: 
1.507     www      9474: # remove wrapper
                   9475: 
1.510     www      9476:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9477:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9478:     return $symb;
1.409     www      9479: }
                   9480: 
                   9481: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9482: 
                   9483: sub encode_symb {
                   9484:     my ($map,$resid,$url)=@_;
                   9485:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9486: }
1.409     www      9487: 
                   9488: sub decode_symb {
1.568     albertel 9489:     my $symb=shift;
                   9490:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9491:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9492:     return (&fixversion($map),$resid,&fixversion($url));
                   9493: }
                   9494: 
                   9495: sub fixversion {
                   9496:     my $fn=shift;
1.609     banghart 9497:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9498:     my %bighash;
                   9499:     my $uri=&clutter($fn);
1.620     albertel 9500:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9501: # is this cached?
1.599     albertel 9502:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9503:     if (defined($cached)) { return $result; }
                   9504: # unfortunately not cached, or expired
1.620     albertel 9505:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9506: 	    &GDBM_READER(),0640)) {
                   9507:  	if ($bighash{'version_'.$uri}) {
                   9508:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9509:  	    unless (($version eq 'mostrecent') || 
                   9510: 		    ($version==&getversion($uri))) {
1.440     www      9511:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9512:  	    }
                   9513:  	}
                   9514:  	untie %bighash;
1.413     www      9515:     }
1.599     albertel 9516:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9517: }
                   9518: 
                   9519: sub deversion {
                   9520:     my $url=shift;
                   9521:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9522:     return $url;
1.210     www      9523: }
                   9524: 
1.31      www      9525: # ------------------------------------------------------ Return symb list entry
                   9526: 
                   9527: sub symbread {
1.249     www      9528:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9529:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9530:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9531: # no filename provided? try from environment
1.44      www      9532:     unless ($thisfn) {
1.620     albertel 9533:         if ($env{'request.symb'}) {
                   9534: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9535: 	}
1.620     albertel 9536: 	$thisfn=$env{'request.filename'};
1.44      www      9537:     }
1.569     albertel 9538:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9539: # is that filename actually a symb? Verify, clean, and return
                   9540:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9541: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9542: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9543: 	}
1.242     www      9544:     }
1.44      www      9545:     $thisfn=declutter($thisfn);
1.31      www      9546:     my %hash;
1.37      www      9547:     my %bighash;
                   9548:     my $syval='';
1.620     albertel 9549:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9550:         my $targetfn = $thisfn;
1.609     banghart 9551:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9552:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9553:         }
1.687     albertel 9554: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9555: 	    $targetfn=$1;
                   9556: 	}
1.620     albertel 9557:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9558:                       &GDBM_READER(),0640)) {
1.481     raeburn  9559: 	    $syval=$hash{$targetfn};
1.37      www      9560:             untie(%hash);
                   9561:         }
                   9562: # ---------------------------------------------------------- There was an entry
                   9563:         if ($syval) {
1.601     albertel 9564: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9565: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9566: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9567: 		    #return $env{$cache_str}='';
1.601     albertel 9568: 		#}    
                   9569: 		#$syval.=$1;
                   9570: 	    #}
1.37      www      9571:         } else {
                   9572: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9573:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9574:                             &GDBM_READER(),0640)) {
1.37      www      9575: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9576:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9577:               unless ($ids) { 
                   9578:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9579:               }
                   9580:               unless ($ids) {
                   9581: # alias?
                   9582: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9583:               }
1.37      www      9584:               if ($ids) {
                   9585: # ------------------------------------------------------------------- Has ID(s)
                   9586:                  my @possibilities=split(/\,/,$ids);
1.39      www      9587:                  if ($#possibilities==0) {
                   9588: # ----------------------------------------------- There is only one possibility
1.37      www      9589: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9590: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9591: 						    $resid,$thisfn);
1.249     www      9592:                  } elsif (!$donotrecurse) {
1.39      www      9593: # ------------------------------------------ There is more than one possibility
                   9594:                      my $realpossible=0;
1.800     albertel 9595:                      foreach my $id (@possibilities) {
                   9596: 			 my $file=$bighash{'src_'.$id};
1.39      www      9597:                          if (&allowed('bre',$file)) {
1.800     albertel 9598:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9599:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9600: 				$realpossible++;
1.626     albertel 9601:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9602: 						    $resid,$thisfn);
1.39      www      9603:                             }
                   9604: 			 }
1.191     harris41 9605:                      }
1.39      www      9606: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9607:                  } else {
                   9608:                      $syval='';
1.37      www      9609:                  }
                   9610: 	      }
                   9611:               untie(%bighash)
1.481     raeburn  9612:            }
1.31      www      9613:         }
1.62      www      9614:         if ($syval) {
1.620     albertel 9615: 	    return $env{$cache_str}=$syval;
1.62      www      9616:         }
1.31      www      9617:     }
1.949     raeburn  9618:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9619:     return $env{$cache_str}='';
1.31      www      9620: }
                   9621: 
                   9622: # ---------------------------------------------------------- Return random seed
                   9623: 
1.32      www      9624: sub numval {
                   9625:     my $txt=shift;
                   9626:     $txt=~tr/A-J/0-9/;
                   9627:     $txt=~tr/a-j/0-9/;
                   9628:     $txt=~tr/K-T/0-9/;
                   9629:     $txt=~tr/k-t/0-9/;
                   9630:     $txt=~tr/U-Z/0-5/;
                   9631:     $txt=~tr/u-z/0-5/;
                   9632:     $txt=~s/\D//g;
1.564     albertel 9633:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9634:     return int($txt);
1.368     albertel 9635: }
                   9636: 
1.484     albertel 9637: sub numval2 {
                   9638:     my $txt=shift;
                   9639:     $txt=~tr/A-J/0-9/;
                   9640:     $txt=~tr/a-j/0-9/;
                   9641:     $txt=~tr/K-T/0-9/;
                   9642:     $txt=~tr/k-t/0-9/;
                   9643:     $txt=~tr/U-Z/0-5/;
                   9644:     $txt=~tr/u-z/0-5/;
                   9645:     $txt=~s/\D//g;
                   9646:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9647:     my $total;
                   9648:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9649:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9650:     return int($total);
                   9651: }
                   9652: 
1.575     albertel 9653: sub numval3 {
                   9654:     use integer;
                   9655:     my $txt=shift;
                   9656:     $txt=~tr/A-J/0-9/;
                   9657:     $txt=~tr/a-j/0-9/;
                   9658:     $txt=~tr/K-T/0-9/;
                   9659:     $txt=~tr/k-t/0-9/;
                   9660:     $txt=~tr/U-Z/0-5/;
                   9661:     $txt=~tr/u-z/0-5/;
                   9662:     $txt=~s/\D//g;
                   9663:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9664:     my $total;
                   9665:     foreach my $val (@txts) { $total+=$val; }
                   9666:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9667:     return $total;
                   9668: }
                   9669: 
1.675     albertel 9670: sub digest {
                   9671:     my ($data)=@_;
                   9672:     my $digest=&Digest::MD5::md5($data);
                   9673:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9674:     my ($e,$f);
                   9675:     {
                   9676:         use integer;
                   9677:         $e=($a+$b);
                   9678:         $f=($c+$d);
                   9679:         if ($_64bit) {
                   9680:             $e=(($e<<32)>>32);
                   9681:             $f=(($f<<32)>>32);
                   9682:         }
                   9683:     }
                   9684:     if (wantarray) {
                   9685: 	return ($e,$f);
                   9686:     } else {
                   9687: 	my $g;
                   9688: 	{
                   9689: 	    use integer;
                   9690: 	    $g=($e+$f);
                   9691: 	    if ($_64bit) {
                   9692: 		$g=(($g<<32)>>32);
                   9693: 	    }
                   9694: 	}
                   9695: 	return $g;
                   9696:     }
                   9697: }
                   9698: 
1.368     albertel 9699: sub latest_rnd_algorithm_id {
1.675     albertel 9700:     return '64bit5';
1.366     albertel 9701: }
1.32      www      9702: 
1.503     albertel 9703: sub get_rand_alg {
                   9704:     my ($courseid)=@_;
1.790     albertel 9705:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9706:     if ($courseid) {
1.620     albertel 9707: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9708:     }
                   9709:     return &latest_rnd_algorithm_id();
                   9710: }
                   9711: 
1.562     albertel 9712: sub validCODE {
                   9713:     my ($CODE)=@_;
                   9714:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9715:     return 0;
                   9716: }
                   9717: 
1.491     albertel 9718: sub getCODE {
1.620     albertel 9719:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9720:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9721: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9722: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9723: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9724:     }
                   9725:     return undef;
                   9726: }
1.1133    foxr     9727: #
                   9728: #  Determines the random seed for a specific context:
                   9729: #
                   9730: # parameters:
                   9731: #   symb      - in course context the symb for the seed.
                   9732: #   course_id - The course id of the form domain_coursenum.
                   9733: #   domain    - Domain for the user.
                   9734: #   course    - Course for the user.
                   9735: #   cenv      - environment of the course.
                   9736: #
                   9737: # NOTE:
                   9738: #   All parameters are picked out of the environment if missing
                   9739: #   or not defined.
                   9740: #   If a symb cannot be determined the current time is used instead.
                   9741: #
                   9742: #  For a given well defined symb, courside, domain, username,
                   9743: #  and course environment, the seed is reproducible.
                   9744: #
1.31      www      9745: sub rndseed {
1.1133    foxr     9746:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 9747:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9748:     if (!defined($symb)) {
1.366     albertel 9749: 	unless ($symb=$wsymb) { return time; }
                   9750:     }
                   9751:     if (!$courseid) { $courseid=$wcourseid; }
                   9752:     if (!$domain) { $domain=$wdomain; }
                   9753:     if (!$username) { $username=$wusername }
1.1133    foxr     9754: 
                   9755:     my $which;
                   9756:     if (defined($cenv->{'rndseed'})) {
                   9757: 	$which = $cenv->{'rndseed'};
                   9758:     } else {
                   9759: 	$which =&get_rand_alg($courseid);
                   9760:     }
1.1110    www      9761: 
1.491     albertel 9762:     if (defined(&getCODE())) {
1.1133    foxr     9763: 
1.675     albertel 9764: 	if ($which eq '64bit5') {
                   9765: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9766: 	} elsif ($which eq '64bit4') {
1.575     albertel 9767: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9768: 	} else {
                   9769: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9770: 	}
1.675     albertel 9771:     } elsif ($which eq '64bit5') {
                   9772: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9773:     } elsif ($which eq '64bit4') {
                   9774: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9775:     } elsif ($which eq '64bit3') {
                   9776: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9777:     } elsif ($which eq '64bit2') {
                   9778: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9779:     } elsif ($which eq '64bit') {
                   9780: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9781:     }
                   9782:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9783: }
                   9784: 
                   9785: sub rndseed_32bit {
                   9786:     my ($symb,$courseid,$domain,$username)=@_;
                   9787:     {
                   9788: 	use integer;
                   9789: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9790: 	my $symbseed=numval($symb) << 22;
                   9791: 	my $namechck=unpack("%32C*",$username) << 17;
                   9792: 	my $nameseed=numval($username) << 12;
                   9793: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9794: 	my $courseseed=unpack("%32C*",$courseid);
                   9795: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9796: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9797: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9798: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9799: 	return $num;
                   9800:     }
                   9801: }
                   9802: 
                   9803: sub rndseed_64bit {
                   9804:     my ($symb,$courseid,$domain,$username)=@_;
                   9805:     {
                   9806: 	use integer;
                   9807: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9808: 	my $symbseed=numval($symb) << 10;
                   9809: 	my $namechck=unpack("%32S*",$username);
                   9810: 	
                   9811: 	my $nameseed=numval($username) << 21;
                   9812: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9813: 	my $courseseed=unpack("%32S*",$courseid);
                   9814: 	
                   9815: 	my $num1=$symbchck+$symbseed+$namechck;
                   9816: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9817: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9818: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9819: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9820: 	return "$num1,$num2";
1.155     albertel 9821:     }
1.366     albertel 9822: }
                   9823: 
1.443     albertel 9824: sub rndseed_64bit2 {
                   9825:     my ($symb,$courseid,$domain,$username)=@_;
                   9826:     {
                   9827: 	use integer;
                   9828: 	# strings need to be an even # of cahracters long, it it is odd the
                   9829:         # last characters gets thrown away
                   9830: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9831: 	my $symbseed=numval($symb) << 10;
                   9832: 	my $namechck=unpack("%32S*",$username.' ');
                   9833: 	
                   9834: 	my $nameseed=numval($username) << 21;
1.501     albertel 9835: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9836: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9837: 	
                   9838: 	my $num1=$symbchck+$symbseed+$namechck;
                   9839: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9840: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9841: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9842: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9843: 	return "$num1,$num2";
                   9844:     }
                   9845: }
                   9846: 
                   9847: sub rndseed_64bit3 {
                   9848:     my ($symb,$courseid,$domain,$username)=@_;
                   9849:     {
                   9850: 	use integer;
                   9851: 	# strings need to be an even # of cahracters long, it it is odd the
                   9852:         # last characters gets thrown away
                   9853: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9854: 	my $symbseed=numval2($symb) << 10;
                   9855: 	my $namechck=unpack("%32S*",$username.' ');
                   9856: 	
                   9857: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9858: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9859: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9860: 	
                   9861: 	my $num1=$symbchck+$symbseed+$namechck;
                   9862: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9863: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9864: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9865: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9866: 	
1.503     albertel 9867: 	return "$num1:$num2";
1.443     albertel 9868:     }
                   9869: }
                   9870: 
1.575     albertel 9871: sub rndseed_64bit4 {
                   9872:     my ($symb,$courseid,$domain,$username)=@_;
                   9873:     {
                   9874: 	use integer;
                   9875: 	# strings need to be an even # of cahracters long, it it is odd the
                   9876:         # last characters gets thrown away
                   9877: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9878: 	my $symbseed=numval3($symb) << 10;
                   9879: 	my $namechck=unpack("%32S*",$username.' ');
                   9880: 	
                   9881: 	my $nameseed=numval3($username) << 21;
                   9882: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9883: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9884: 	
                   9885: 	my $num1=$symbchck+$symbseed+$namechck;
                   9886: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9887: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9888: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9889: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9890: 	
1.575     albertel 9891: 	return "$num1:$num2";
                   9892:     }
                   9893: }
                   9894: 
1.675     albertel 9895: sub rndseed_64bit5 {
                   9896:     my ($symb,$courseid,$domain,$username)=@_;
                   9897:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9898:     return "$num1:$num2";
                   9899: }
                   9900: 
1.366     albertel 9901: sub rndseed_CODE_64bit {
                   9902:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9903:     {
1.366     albertel 9904: 	use integer;
1.443     albertel 9905: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9906: 	my $symbseed=numval2($symb);
1.491     albertel 9907: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9908: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9909: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9910: 	my $num1=$symbseed+$CODEchck;
                   9911: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9912: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9913: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9914: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9915: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9916: 	return "$num1:$num2";
1.366     albertel 9917:     }
                   9918: }
                   9919: 
1.575     albertel 9920: sub rndseed_CODE_64bit4 {
                   9921:     my ($symb,$courseid,$domain,$username)=@_;
                   9922:     {
                   9923: 	use integer;
                   9924: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9925: 	my $symbseed=numval3($symb);
                   9926: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9927: 	my $CODEseed=numval3(&getCODE());
                   9928: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9929: 	my $num1=$symbseed+$CODEchck;
                   9930: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9931: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9932: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9933: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9934: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9935: 	return "$num1:$num2";
                   9936:     }
                   9937: }
                   9938: 
1.675     albertel 9939: sub rndseed_CODE_64bit5 {
                   9940:     my ($symb,$courseid,$domain,$username)=@_;
                   9941:     my $code = &getCODE();
                   9942:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9943:     return "$num1:$num2";
                   9944: }
                   9945: 
1.366     albertel 9946: sub setup_random_from_rndseed {
                   9947:     my ($rndseed)=@_;
1.503     albertel 9948:     if ($rndseed =~/([,:])/) {
                   9949: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9950: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9951:     } else {
                   9952: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9953:     }
1.36      albertel 9954: }
                   9955: 
1.474     albertel 9956: sub latest_receipt_algorithm_id {
1.835     albertel 9957:     return 'receipt3';
1.474     albertel 9958: }
                   9959: 
1.480     www      9960: sub recunique {
                   9961:     my $fucourseid=shift;
                   9962:     my $unique;
1.835     albertel 9963:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9964: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9965: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9966:     } else {
                   9967: 	$unique=$perlvar{'lonReceipt'};
                   9968:     }
                   9969:     return unpack("%32C*",$unique);
                   9970: }
                   9971: 
                   9972: sub recprefix {
                   9973:     my $fucourseid=shift;
                   9974:     my $prefix;
1.835     albertel 9975:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9976: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9977: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9978:     } else {
                   9979: 	$prefix=$perlvar{'lonHostID'};
                   9980:     }
                   9981:     return unpack("%32C*",$prefix);
                   9982: }
                   9983: 
1.76      www      9984: sub ireceipt {
1.474     albertel 9985:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9986: 
                   9987:     my $return =&recprefix($fucourseid).'-';
                   9988: 
                   9989:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9990: 	$env{'request.state'} eq 'construct') {
                   9991: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9992: 	return $return;
                   9993:     }
                   9994: 
1.76      www      9995:     my $cuname=unpack("%32C*",$funame);
                   9996:     my $cudom=unpack("%32C*",$fudom);
                   9997:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9998:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9999:     my $cunique=&recunique($fucourseid);
1.474     albertel 10000:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10001:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10002: 
1.790     albertel 10003: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10004: 			       
                   10005: 	$return.= ($cunique%$cuname+
                   10006: 		   $cunique%$cudom+
                   10007: 		   $cusymb%$cuname+
                   10008: 		   $cusymb%$cudom+
                   10009: 		   $cucourseid%$cuname+
                   10010: 		   $cucourseid%$cudom+
                   10011: 		   $cpart%$cuname+
                   10012: 		   $cpart%$cudom);
                   10013:     } else {
                   10014: 	$return.= ($cunique%$cuname+
                   10015: 		   $cunique%$cudom+
                   10016: 		   $cusymb%$cuname+
                   10017: 		   $cusymb%$cudom+
                   10018: 		   $cucourseid%$cuname+
                   10019: 		   $cucourseid%$cudom);
                   10020:     }
                   10021:     return $return;
1.76      www      10022: }
                   10023: 
                   10024: sub receipt {
1.474     albertel 10025:     my ($part)=@_;
1.790     albertel 10026:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10027:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10028: }
1.260     ng       10029: 
1.790     albertel 10030: sub whichuser {
                   10031:     my ($passedsymb)=@_;
                   10032:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10033:     if (defined($env{'form.grade_symb'})) {
                   10034: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10035: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10036: 	if (!$allowed &&
                   10037: 	    exists($env{'request.course.sec'}) &&
                   10038: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10039: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10040: 			      '/'.$env{'request.course.sec'});
                   10041: 	}
                   10042: 	if ($allowed) {
                   10043: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10044: 	    $courseid=$tmp_courseid;
                   10045: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10046: 	    ($name)=&get_env_multiple('form.grade_username');
                   10047: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10048: 	}
                   10049:     }
                   10050:     if (!$passedsymb) {
                   10051: 	$symb=&symbread();
                   10052:     } else {
                   10053: 	$symb=$passedsymb;
                   10054:     }
                   10055:     $courseid=$env{'request.course.id'};
                   10056:     $domain=$env{'user.domain'};
                   10057:     $name=$env{'user.name'};
                   10058:     if ($name eq 'public' && $domain eq 'public') {
                   10059: 	if (!defined($env{'form.username'})) {
                   10060: 	    $env{'form.username'}.=time.rand(10000000);
                   10061: 	}
                   10062: 	$name.=$env{'form.username'};
                   10063:     }
                   10064:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10065: 
                   10066: }
                   10067: 
1.36      albertel 10068: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10069: # returns either the contents of the file or 
                   10070: # -1 if the file doesn't exist
1.481     raeburn  10071: #
                   10072: # if the target is a file that was uploaded via DOCS, 
                   10073: # a check will be made to see if a current copy exists on the local server,
                   10074: # if it does this will be served, otherwise a copy will be retrieved from
                   10075: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10076: # the local server.   
1.472     albertel 10077: 
1.36      albertel 10078: sub getfile {
1.538     albertel 10079:     my ($file) = @_;
1.609     banghart 10080:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10081:     &repcopy($file);
                   10082:     return &readfile($file);
                   10083: }
                   10084: 
                   10085: sub repcopy_userfile {
                   10086:     my ($file)=@_;
1.609     banghart 10087:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 10088:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 10089:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10090: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10091:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10092:     if (-e "$file") {
1.828     www      10093: # we already have a local copy, check it out
1.538     albertel 10094: 	my @fileinfo = stat($file);
1.828     www      10095: 	my $rtncode;
                   10096: 	my $info;
1.538     albertel 10097: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10098: 	if ($lwpresp ne 'ok') {
1.828     www      10099: # there is no such file anymore, even though we had a local copy
1.482     albertel 10100: 	    if ($rtncode eq '404') {
1.538     albertel 10101: 		unlink($file);
1.482     albertel 10102: 	    }
                   10103: 	    return -1;
                   10104: 	}
                   10105: 	if ($info < $fileinfo[9]) {
1.828     www      10106: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10107: 	    return 'ok';
1.828     www      10108: 	} else {
                   10109: # the file is outdated, get rid of it
                   10110: 	    unlink($file);
1.482     albertel 10111: 	}
1.828     www      10112:     }
                   10113: # one way or the other, at this point, we don't have the file
                   10114: # construct the correct path for the file
                   10115:     my @parts = ($cdom,$cnum); 
                   10116:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10117: 	push @parts, split(/\//,$1);
                   10118:     }
                   10119:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10120:     foreach my $part (@parts) {
                   10121: 	$path .= '/'.$part;
                   10122: 	if (!-e $path) {
                   10123: 	    mkdir($path,0770);
1.482     albertel 10124: 	}
                   10125:     }
1.828     www      10126: # now the path exists for sure
                   10127: # get a user agent
                   10128:     my $ua=new LWP::UserAgent;
                   10129:     my $transferfile=$file.'.in.transfer';
                   10130: # FIXME: this should flock
                   10131:     if (-e $transferfile) { return 'ok'; }
                   10132:     my $request;
                   10133:     $uri=~s/^\///;
1.980     raeburn  10134:     my $homeserver = &homeserver($cnum,$cdom);
                   10135:     my $protocol = $protocol{$homeserver};
                   10136:     $protocol = 'http' if ($protocol ne 'https');
                   10137:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10138:     my $response=$ua->request($request,$transferfile);
                   10139: # did it work?
                   10140:     if ($response->is_error()) {
                   10141: 	unlink($transferfile);
                   10142: 	&logthis("Userfile repcopy failed for $uri");
                   10143: 	return -1;
                   10144:     }
                   10145: # worked, rename the transfer file
                   10146:     rename($transferfile,$file);
1.607     raeburn  10147:     return 'ok';
1.481     raeburn  10148: }
                   10149: 
1.517     albertel 10150: sub tokenwrapper {
                   10151:     my $uri=shift;
1.980     raeburn  10152:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10153:     $uri=~s|^/||;
1.620     albertel 10154:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10155:     my $token=$1;
1.552     albertel 10156:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10157:     if ($udom && $uname && $file) {
                   10158: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10159:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10160:         my $homeserver = &homeserver($uname,$udom);
                   10161:         my $protocol = $protocol{$homeserver};
                   10162:         $protocol = 'http' if ($protocol ne 'https');
                   10163:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10164:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10165:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10166:     } else {
                   10167:         return '/adm/notfound.html';
                   10168:     }
                   10169: }
                   10170: 
1.828     www      10171: # call with reqtype HEAD: get last modification time
                   10172: # call with reqtype GET: get the file contents
                   10173: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10174: #
1.481     raeburn  10175: sub getuploaded {
                   10176:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10177:     $uri=~s/^\///;
1.980     raeburn  10178:     my $homeserver = &homeserver($cnum,$cdom);
                   10179:     my $protocol = $protocol{$homeserver};
                   10180:     $protocol = 'http' if ($protocol ne 'https');
                   10181:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10182:     my $ua=new LWP::UserAgent;
                   10183:     my $request=new HTTP::Request($reqtype,$uri);
                   10184:     my $response=$ua->request($request);
                   10185:     $$rtncode = $response->code;
1.482     albertel 10186:     if (! $response->is_success()) {
                   10187: 	return 'failed';
                   10188:     }      
                   10189:     if ($reqtype eq 'HEAD') {
1.486     www      10190: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10191:     } elsif ($reqtype eq 'GET') {
                   10192: 	$$info = $response->content;
1.472     albertel 10193:     }
1.482     albertel 10194:     return 'ok';
1.36      albertel 10195: }
                   10196: 
1.481     raeburn  10197: sub readfile {
                   10198:     my $file = shift;
                   10199:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10200:     my $fh;
                   10201:     open($fh,"<$file");
                   10202:     my $a='';
1.800     albertel 10203:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10204:     return $a;
                   10205: }
                   10206: 
1.36      albertel 10207: sub filelocation {
1.590     banghart 10208:     my ($dir,$file) = @_;
                   10209:     my $location;
                   10210:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10211: 
                   10212:     if ($file =~ m-^/adm/-) {
                   10213: 	$file=~s-^/adm/wrapper/-/-;
                   10214: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10215:     }
1.882     albertel 10216: 
1.590     banghart 10217:     if ($file=~m:^/~:) { # is a contruction space reference
                   10218:         $location = $file;
                   10219:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 10220:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 10221: 	# is a correct contruction space reference
                   10222:         $location = $file;
1.956     raeburn  10223:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   10224:         $location = $file;
1.609     banghart 10225:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10226:         my ($udom,$uname,$filename)=
1.811     albertel 10227:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10228:         my $home=&homeserver($uname,$udom);
                   10229:         my $is_me=0;
                   10230:         my @ids=&current_machine_ids();
                   10231:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10232:         if ($is_me) {
1.1117    foxr     10233:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10234:         } else {
                   10235:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10236:   	      $udom.'/'.$uname.'/'.$filename;
                   10237:         }
1.882     albertel 10238:     } elsif ($file =~ m-^/adm/-) {
                   10239: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10240:     } else {
                   10241:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   10242:         $file=~s:^/res/:/:;
                   10243:         if ( !( $file =~ m:^/:) ) {
                   10244:             $location = $dir. '/'.$file;
                   10245:         } else {
                   10246:             $location = '/home/httpd/html/res'.$file;
                   10247:         }
1.59      albertel 10248:     }
1.590     banghart 10249:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10250:     while ($location=~m{/\.\./}) {
                   10251: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10252: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10253: 	} else {
                   10254: 	    $location=~ s{/\.\./}{/}g;
                   10255: 	}
                   10256:     } #remove dir/..
1.590     banghart 10257:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10258:     return $location;
1.46      www      10259: }
1.36      albertel 10260: 
1.46      www      10261: sub hreflocation {
                   10262:     my ($dir,$file)=@_;
1.980     raeburn  10263:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10264: 	$file=filelocation($dir,$file);
1.700     albertel 10265:     } elsif ($file=~m-^/adm/-) {
                   10266: 	$file=~s-^/adm/wrapper/-/-;
                   10267: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10268:     }
                   10269:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10270: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 10271:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   10272: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 10273:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 10274: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 10275: 	    -/uploaded/$1/$2/-x;
1.46      www      10276:     }
1.913     albertel 10277:     if ($file=~ m{^/userfiles/}) {
                   10278: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10279:     }
1.462     albertel 10280:     return $file;
1.465     albertel 10281: }
                   10282: 
                   10283: sub current_machine_domains {
1.853     albertel 10284:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10285: }
                   10286: 
                   10287: sub machine_domains {
                   10288:     my ($hostname) = @_;
1.465     albertel 10289:     my @domains;
1.838     albertel 10290:     my %hostname = &all_hostnames();
1.465     albertel 10291:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10292: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10293: 	if ($hostname eq $name) {
1.844     albertel 10294: 	    push(@domains,&host_domain($id));
1.465     albertel 10295: 	}
                   10296:     }
                   10297:     return @domains;
                   10298: }
                   10299: 
                   10300: sub current_machine_ids {
1.853     albertel 10301:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10302: }
                   10303: 
                   10304: sub machine_ids {
                   10305:     my ($hostname) = @_;
                   10306:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10307:     my @ids;
1.888     albertel 10308:     my %name_to_host = &all_names();
1.889     albertel 10309:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10310: 	return @{ $name_to_host{$hostname} };
                   10311:     }
                   10312:     return;
1.31      www      10313: }
                   10314: 
1.824     raeburn  10315: sub additional_machine_domains {
                   10316:     my @domains;
                   10317:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10318:     while( my $line = <$fh>) {
                   10319:         $line =~ s/\s//g;
                   10320:         push(@domains,$line);
                   10321:     }
                   10322:     return @domains;
                   10323: }
                   10324: 
                   10325: sub default_login_domain {
                   10326:     my $domain = $perlvar{'lonDefDomain'};
                   10327:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10328:     foreach my $posdom (&current_machine_domains(),
                   10329:                         &additional_machine_domains()) {
                   10330:         if (lc($posdom) eq lc($testdomain)) {
                   10331:             $domain=$posdom;
                   10332:             last;
                   10333:         }
                   10334:     }
                   10335:     return $domain;
                   10336: }
                   10337: 
1.31      www      10338: # ------------------------------------------------------------- Declutters URLs
                   10339: 
                   10340: sub declutter {
                   10341:     my $thisfn=shift;
1.569     albertel 10342:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10343:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10344:     $thisfn=~s/^\///;
1.697     albertel 10345:     $thisfn=~s|^adm/wrapper/||;
                   10346:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10347:     $thisfn=~s/^res\///;
1.1032    raeburn  10348:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10349:         $thisfn=~s/\?.+$//;
                   10350:     }
1.268     www      10351:     return $thisfn;
                   10352: }
                   10353: 
                   10354: # ------------------------------------------------------------- Clutter up URLs
                   10355: 
                   10356: sub clutter {
                   10357:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10358:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10359: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10360:        $thisfn='/res'.$thisfn; 
                   10361:     }
1.1031    raeburn  10362:     if ($thisfn !~m|^/adm|) {
                   10363: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10364: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10365: 	} else {
                   10366: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10367: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10368: 	    if ($embstyle eq 'ssi'
                   10369: 		|| ($embstyle eq 'hdn')
                   10370: 		|| ($embstyle eq 'rat')
                   10371: 		|| ($embstyle eq 'prv')
                   10372: 		|| ($embstyle eq 'ign')) {
                   10373: 		#do nothing with these
                   10374: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10375: 		|| ($embstyle eq 'emb')
                   10376: 		|| ($embstyle eq 'wrp')) {
                   10377: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10378: 	    } elsif ($embstyle eq 'unk'
                   10379: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10380: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10381: 	    } else {
1.718     www      10382: #		&logthis("Got a blank emb style");
1.695     albertel 10383: 	    }
1.694     albertel 10384: 	}
                   10385:     }
1.31      www      10386:     return $thisfn;
1.12      www      10387: }
                   10388: 
1.787     albertel 10389: sub clutter_with_no_wrapper {
                   10390:     my $uri = &clutter(shift);
                   10391:     if ($uri =~ m-^/adm/-) {
                   10392: 	$uri =~ s-^/adm/wrapper/-/-;
                   10393: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10394:     }
                   10395:     return $uri;
                   10396: }
                   10397: 
1.557     albertel 10398: sub freeze_escape {
                   10399:     my ($value)=@_;
                   10400:     if (ref($value)) {
                   10401: 	$value=&nfreeze($value);
                   10402: 	return '__FROZEN__'.&escape($value);
                   10403:     }
                   10404:     return &escape($value);
                   10405: }
                   10406: 
1.11      www      10407: 
1.557     albertel 10408: sub thaw_unescape {
                   10409:     my ($value)=@_;
                   10410:     if ($value =~ /^__FROZEN__/) {
                   10411: 	substr($value,0,10,undef);
                   10412: 	$value=&unescape($value);
                   10413: 	return &thaw($value);
                   10414:     }
                   10415:     return &unescape($value);
                   10416: }
                   10417: 
1.436     albertel 10418: sub correct_line_ends {
                   10419:     my ($result)=@_;
                   10420:     $$result =~s/\r\n/\n/mg;
                   10421:     $$result =~s/\r/\n/mg;
1.415     albertel 10422: }
1.1       albertel 10423: # ================================================================ Main Program
                   10424: 
1.184     www      10425: sub goodbye {
1.204     albertel 10426:    &logthis("Starting Shut down");
1.443     albertel 10427: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10428:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10429: #converted
1.599     albertel 10430: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10431:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10432: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10433: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10434: #1.1 only
1.870     albertel 10435: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10436: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10437: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10438: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10439:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10440:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10441:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10442:    &flushcourselogs();
                   10443:    &logthis("Shutting down");
                   10444: }
                   10445: 
1.852     albertel 10446: sub get_dns {
1.869     albertel 10447:     my ($url,$func,$ignore_cache) = @_;
                   10448:     if (!$ignore_cache) {
                   10449: 	my ($content,$cached)=
                   10450: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10451: 	if ($cached) {
                   10452: 	    &$func($content);
                   10453: 	    return;
                   10454: 	}
                   10455:     }
                   10456: 
                   10457:     my %alldns;
1.852     albertel 10458:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10459:     foreach my $dns (<$config>) {
                   10460: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10461:         my $line = $1;
                   10462:         my ($host,$protocol) = split(/:/,$line);
                   10463:         if ($protocol ne 'https') {
                   10464:             $protocol = 'http';
                   10465:         }
                   10466: 	$alldns{$host} = $protocol;
1.869     albertel 10467:     }
                   10468:     while (%alldns) {
                   10469: 	my ($dns) = keys(%alldns);
1.852     albertel 10470: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10471:         $ua->timeout(30);
1.979     raeburn  10472: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10473: 	my $response=$ua->request($request);
1.979     raeburn  10474:         delete($alldns{$dns});
1.852     albertel 10475: 	next if ($response->is_error());
                   10476: 	my @content = split("\n",$response->content);
1.869     albertel 10477: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10478: 	&$func(\@content);
1.869     albertel 10479: 	return;
1.852     albertel 10480:     }
                   10481:     close($config);
1.871     albertel 10482:     my $which = (split('/',$url))[3];
                   10483:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10484:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10485:     my @content = <$config>;
                   10486:     &$func(\@content);
                   10487:     return;
1.852     albertel 10488: }
1.327     albertel 10489: # ------------------------------------------------------------ Read domain file
                   10490: {
1.852     albertel 10491:     my $loaded;
1.846     albertel 10492:     my %domain;
                   10493: 
1.852     albertel 10494:     sub parse_domain_tab {
                   10495: 	my ($lines) = @_;
                   10496: 	foreach my $line (@$lines) {
                   10497: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10498: 
1.846     albertel 10499: 	    chomp($line);
1.852     albertel 10500: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10501: 	    my %this_domain;
                   10502: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10503: 			       'lang_def', 'city', 'longi', 'lati',
                   10504: 			       'primary') {
                   10505: 		$this_domain{$field} = shift(@elements);
                   10506: 	    }
                   10507: 	    $domain{$name} = \%this_domain;
1.852     albertel 10508: 	}
                   10509:     }
1.864     albertel 10510: 
                   10511:     sub reset_domain_info {
                   10512: 	undef($loaded);
                   10513: 	undef(%domain);
                   10514:     }
                   10515: 
1.852     albertel 10516:     sub load_domain_tab {
1.869     albertel 10517: 	my ($ignore_cache) = @_;
                   10518: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10519: 	my $fh;
                   10520: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10521: 	    my @lines = <$fh>;
                   10522: 	    &parse_domain_tab(\@lines);
1.448     albertel 10523: 	}
1.852     albertel 10524: 	close($fh);
                   10525: 	$loaded = 1;
1.327     albertel 10526:     }
1.846     albertel 10527: 
                   10528:     sub domain {
1.852     albertel 10529: 	&load_domain_tab() if (!$loaded);
                   10530: 
1.846     albertel 10531: 	my ($name,$what) = @_;
                   10532: 	return if ( !exists($domain{$name}) );
                   10533: 
                   10534: 	if (!$what) {
                   10535: 	    return $domain{$name}{'description'};
                   10536: 	}
                   10537: 	return $domain{$name}{$what};
                   10538:     }
1.974     raeburn  10539: 
                   10540:     sub domain_info {
                   10541:         &load_domain_tab() if (!$loaded);
                   10542:         return %domain;
                   10543:     }
                   10544: 
1.327     albertel 10545: }
                   10546: 
                   10547: 
1.1       albertel 10548: # ------------------------------------------------------------- Read hosts file
                   10549: {
1.838     albertel 10550:     my %hostname;
1.844     albertel 10551:     my %hostdom;
1.845     albertel 10552:     my %libserv;
1.852     albertel 10553:     my $loaded;
1.888     albertel 10554:     my %name_to_host;
1.1074    raeburn  10555:     my %internetdom;
1.1107    raeburn  10556:     my %LC_dns_serv;
1.852     albertel 10557: 
                   10558:     sub parse_hosts_tab {
                   10559: 	my ($file) = @_;
                   10560: 	foreach my $configline (@$file) {
                   10561: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10562:             chomp($configline);
                   10563: 	    if ($configline =~ /^\^/) {
                   10564:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10565:                     $LC_dns_serv{$1} = 1;
                   10566:                 }
                   10567:                 next;
                   10568:             }
1.1074    raeburn  10569: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10570: 	    $name=~s/\s//g;
                   10571: 	    if ($id && $domain && $role && $name) {
                   10572: 		$hostname{$id}=$name;
1.888     albertel 10573: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10574: 		$hostdom{$id}=$domain;
                   10575: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10576:                 if (defined($protocol)) {
                   10577:                     if ($protocol eq 'https') {
                   10578:                         $protocol{$id} = $protocol;
                   10579:                     } else {
                   10580:                         $protocol{$id} = 'http'; 
                   10581:                     }
1.968     raeburn  10582:                 } else {
1.969     raeburn  10583:                     $protocol{$id} = 'http';
1.968     raeburn  10584:                 }
1.1074    raeburn  10585:                 if (defined($intdom)) {
                   10586:                     $internetdom{$id} = $intdom;
                   10587:                 }
1.852     albertel 10588: 	    }
                   10589: 	}
                   10590:     }
1.864     albertel 10591:     
                   10592:     sub reset_hosts_info {
1.897     albertel 10593: 	&purge_remembered();
1.864     albertel 10594: 	&reset_domain_info();
                   10595: 	&reset_hosts_ip_info();
1.892     albertel 10596: 	undef(%name_to_host);
1.864     albertel 10597: 	undef(%hostname);
                   10598: 	undef(%hostdom);
                   10599: 	undef(%libserv);
                   10600: 	undef($loaded);
                   10601:     }
1.1       albertel 10602: 
1.852     albertel 10603:     sub load_hosts_tab {
1.869     albertel 10604: 	my ($ignore_cache) = @_;
                   10605: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10606: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10607: 	my @config = <$config>;
                   10608: 	&parse_hosts_tab(\@config);
                   10609: 	close($config);
                   10610: 	$loaded=1;
1.1       albertel 10611:     }
1.852     albertel 10612: 
1.838     albertel 10613:     sub hostname {
1.852     albertel 10614: 	&load_hosts_tab() if (!$loaded);
                   10615: 
1.838     albertel 10616: 	my ($lonid) = @_;
                   10617: 	return $hostname{$lonid};
                   10618:     }
1.845     albertel 10619: 
1.838     albertel 10620:     sub all_hostnames {
1.852     albertel 10621: 	&load_hosts_tab() if (!$loaded);
                   10622: 
1.838     albertel 10623: 	return %hostname;
                   10624:     }
1.845     albertel 10625: 
1.888     albertel 10626:     sub all_names {
                   10627: 	&load_hosts_tab() if (!$loaded);
                   10628: 
                   10629: 	return %name_to_host;
                   10630:     }
                   10631: 
1.974     raeburn  10632:     sub all_host_domain {
                   10633:         &load_hosts_tab() if (!$loaded);
                   10634:         return %hostdom;
                   10635:     }
                   10636: 
1.845     albertel 10637:     sub is_library {
1.852     albertel 10638: 	&load_hosts_tab() if (!$loaded);
                   10639: 
1.845     albertel 10640: 	return exists($libserv{$_[0]});
                   10641:     }
                   10642: 
                   10643:     sub all_library {
1.852     albertel 10644: 	&load_hosts_tab() if (!$loaded);
                   10645: 
1.845     albertel 10646: 	return %libserv;
                   10647:     }
                   10648: 
1.1062    droeschl 10649:     sub unique_library {
                   10650: 	#2x reverse removes all hostnames that appear more than once
                   10651:         my %unique = reverse &all_library();
                   10652:         return reverse %unique;
                   10653:     }
                   10654: 
1.841     albertel 10655:     sub get_servers {
1.852     albertel 10656: 	&load_hosts_tab() if (!$loaded);
                   10657: 
1.841     albertel 10658: 	my ($domain,$type) = @_;
                   10659: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10660: 	                                          : %hostname;
                   10661: 	my %result;
1.842     albertel 10662: 	if (ref($domain) eq 'ARRAY') {
                   10663: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10664: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10665: 		    $result{$host} = $hostname;
                   10666: 		}
                   10667: 	    }
                   10668: 	} else {
                   10669: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10670: 		if ($hostdom{$host} eq $domain) {
                   10671: 		    $result{$host} = $hostname;
                   10672: 		}
1.841     albertel 10673: 	    }
                   10674: 	}
                   10675: 	return %result;
                   10676:     }
1.845     albertel 10677: 
1.1062    droeschl 10678:     sub get_unique_servers {
                   10679:         my %unique = reverse &get_servers(@_);
                   10680: 	return reverse %unique;
                   10681:     }
                   10682: 
1.844     albertel 10683:     sub host_domain {
1.852     albertel 10684: 	&load_hosts_tab() if (!$loaded);
                   10685: 
1.844     albertel 10686: 	my ($lonid) = @_;
                   10687: 	return $hostdom{$lonid};
                   10688:     }
                   10689: 
1.841     albertel 10690:     sub all_domains {
1.852     albertel 10691: 	&load_hosts_tab() if (!$loaded);
                   10692: 
1.841     albertel 10693: 	my %seen;
                   10694: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10695: 	return @uniq;
                   10696:     }
1.1074    raeburn  10697: 
                   10698:     sub internet_dom {
                   10699:         &load_hosts_tab() if (!$loaded);
                   10700: 
                   10701:         my ($lonid) = @_;
                   10702:         return $internetdom{$lonid};
                   10703:     }
1.1107    raeburn  10704: 
                   10705:     sub is_LC_dns {
                   10706:         &load_hosts_tab() if (!$loaded);
                   10707: 
                   10708:         my ($hostname) = @_;
                   10709:         return exists($LC_dns_serv{$hostname});
                   10710:     }
                   10711: 
1.1       albertel 10712: }
                   10713: 
1.847     albertel 10714: { 
                   10715:     my %iphost;
1.856     albertel 10716:     my %name_to_ip;
                   10717:     my %lonid_to_ip;
1.869     albertel 10718: 
1.847     albertel 10719:     sub get_hosts_from_ip {
                   10720: 	my ($ip) = @_;
                   10721: 	my %iphosts = &get_iphost();
                   10722: 	if (ref($iphosts{$ip})) {
                   10723: 	    return @{$iphosts{$ip}};
                   10724: 	}
                   10725: 	return;
1.839     albertel 10726:     }
1.864     albertel 10727:     
                   10728:     sub reset_hosts_ip_info {
                   10729: 	undef(%iphost);
                   10730: 	undef(%name_to_ip);
                   10731: 	undef(%lonid_to_ip);
                   10732:     }
1.856     albertel 10733: 
                   10734:     sub get_host_ip {
                   10735: 	my ($lonid) = @_;
                   10736: 	if (exists($lonid_to_ip{$lonid})) {
                   10737: 	    return $lonid_to_ip{$lonid};
                   10738: 	}
                   10739: 	my $name=&hostname($lonid);
                   10740:    	my $ip = gethostbyname($name);
                   10741: 	return if (!$ip || length($ip) ne 4);
                   10742: 	$ip=inet_ntoa($ip);
                   10743: 	$name_to_ip{$name}   = $ip;
                   10744: 	$lonid_to_ip{$lonid} = $ip;
                   10745: 	return $ip;
                   10746:     }
1.847     albertel 10747:     
                   10748:     sub get_iphost {
1.869     albertel 10749: 	my ($ignore_cache) = @_;
1.894     albertel 10750: 
1.869     albertel 10751: 	if (!$ignore_cache) {
                   10752: 	    if (%iphost) {
                   10753: 		return %iphost;
                   10754: 	    }
                   10755: 	    my ($ip_info,$cached)=
                   10756: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10757: 	    if ($cached) {
                   10758: 		%iphost      = %{$ip_info->[0]};
                   10759: 		%name_to_ip  = %{$ip_info->[1]};
                   10760: 		%lonid_to_ip = %{$ip_info->[2]};
                   10761: 		return %iphost;
                   10762: 	    }
                   10763: 	}
1.894     albertel 10764: 
                   10765: 	# get yesterday's info for fallback
                   10766: 	my %old_name_to_ip;
                   10767: 	my ($ip_info,$cached)=
                   10768: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10769: 	if ($cached) {
                   10770: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10771: 	}
                   10772: 
1.888     albertel 10773: 	my %name_to_host = &all_names();
                   10774: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10775: 	    my $ip;
                   10776: 	    if (!exists($name_to_ip{$name})) {
                   10777: 		$ip = gethostbyname($name);
                   10778: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10779: 		    if (defined($old_name_to_ip{$name})) {
                   10780: 			$ip = $old_name_to_ip{$name};
                   10781: 			&logthis("Can't find $name defaulting to old $ip");
                   10782: 		    } else {
                   10783: 			&logthis("Name $name no IP found");
                   10784: 			next;
                   10785: 		    }
                   10786: 		} else {
                   10787: 		    $ip=inet_ntoa($ip);
1.847     albertel 10788: 		}
                   10789: 		$name_to_ip{$name} = $ip;
                   10790: 	    } else {
                   10791: 		$ip = $name_to_ip{$name};
1.653     albertel 10792: 	    }
1.888     albertel 10793: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10794: 		$lonid_to_ip{$id} = $ip;
                   10795: 	    }
                   10796: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10797: 	}
1.869     albertel 10798: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10799: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10800: 				      48*60*60);
1.869     albertel 10801: 
1.847     albertel 10802: 	return %iphost;
1.598     albertel 10803:     }
                   10804: 
1.992     raeburn  10805:     #
                   10806:     #  Given a DNS returns the loncapa host name for that DNS 
                   10807:     # 
                   10808:     sub host_from_dns {
                   10809:         my ($dns) = @_;
                   10810:         my @hosts;
                   10811:         my $ip;
                   10812: 
1.993     raeburn  10813:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10814:             $ip = $name_to_ip{$dns};
                   10815:         }
                   10816:         if (!$ip) {
                   10817:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10818:             if (length($ip) == 4) { 
                   10819: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10820:             }
                   10821:         }
                   10822:         if ($ip) {
                   10823: 	    @hosts = get_hosts_from_ip($ip);
                   10824: 	    return $hosts[0];
                   10825:         }
                   10826:         return undef;
1.986     foxr     10827:     }
1.992     raeburn  10828: 
1.1074    raeburn  10829:     sub get_internet_names {
                   10830:         my ($lonid) = @_;
                   10831:         return if ($lonid eq '');
                   10832:         my ($idnref,$cached)=
                   10833:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10834:         if ($cached) {
                   10835:             return $idnref;
                   10836:         }
                   10837:         my $ip = &get_host_ip($lonid);
                   10838:         my @hosts = &get_hosts_from_ip($ip);
                   10839:         my %iphost = &get_iphost();
                   10840:         my (@idns,%seen);
                   10841:         foreach my $id (@hosts) {
                   10842:             my $dom = &host_domain($id);
                   10843:             my $prim_id = &domain($dom,'primary');
                   10844:             my $prim_ip = &get_host_ip($prim_id);
                   10845:             next if ($seen{$prim_ip});
                   10846:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10847:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10848:                     my $intdom = &internet_dom($id);
                   10849:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10850:                         push(@idns,$intdom);
                   10851:                     }
                   10852:                 }
                   10853:             }
                   10854:             $seen{$prim_ip} = 1;
                   10855:         }
                   10856:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10857:     }
                   10858: 
1.986     foxr     10859: }
                   10860: 
1.1079    raeburn  10861: sub all_loncaparevs {
                   10862:     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);
                   10863: }
                   10864: 
1.862     albertel 10865: BEGIN {
                   10866: 
                   10867: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10868:     unless ($readit) {
                   10869: {
                   10870:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10871:     %perlvar = (%perlvar,%{$configvars});
                   10872: }
                   10873: 
                   10874: 
1.1       albertel 10875: # ------------------------------------------------------ Read spare server file
                   10876: {
1.448     albertel 10877:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10878: 
                   10879:     while (my $configline=<$config>) {
                   10880:        chomp($configline);
1.284     matthew  10881:        if ($configline) {
1.784     albertel 10882: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10883: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10884: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10885:        }
                   10886:     }
1.448     albertel 10887:     close($config);
1.1       albertel 10888: }
1.11      www      10889: # ------------------------------------------------------------ Read permissions
                   10890: {
1.448     albertel 10891:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10892: 
                   10893:     while (my $configline=<$config>) {
1.448     albertel 10894: 	chomp($configline);
                   10895: 	if ($configline) {
                   10896: 	    my ($role,$perm)=split(/ /,$configline);
                   10897: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10898: 	}
1.11      www      10899:     }
1.448     albertel 10900:     close($config);
1.11      www      10901: }
                   10902: 
                   10903: # -------------------------------------------- Read plain texts for permissions
                   10904: {
1.448     albertel 10905:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10906: 
                   10907:     while (my $configline=<$config>) {
1.448     albertel 10908: 	chomp($configline);
                   10909: 	if ($configline) {
1.742     raeburn  10910: 	    my ($short,@plain)=split(/:/,$configline);
                   10911:             %{$prp{$short}} = ();
                   10912: 	    if (@plain > 0) {
                   10913:                 $prp{$short}{'std'} = $plain[0];
                   10914:                 for (my $i=1; $i<@plain; $i++) {
                   10915:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10916:                 }
                   10917:             }
1.448     albertel 10918: 	}
1.135     www      10919:     }
1.448     albertel 10920:     close($config);
1.135     www      10921: }
                   10922: 
                   10923: # ---------------------------------------------------------- Read package table
                   10924: {
1.448     albertel 10925:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10926: 
                   10927:     while (my $configline=<$config>) {
1.483     albertel 10928: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10929: 	chomp($configline);
                   10930: 	my ($short,$plain)=split(/:/,$configline);
                   10931: 	my ($pack,$name)=split(/\&/,$short);
                   10932: 	if ($plain ne '') {
                   10933: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10934: 	    $packagetab{$short}=$plain; 
                   10935: 	}
1.11      www      10936:     }
1.448     albertel 10937:     close($config);
1.329     matthew  10938: }
                   10939: 
1.1073    raeburn  10940: # ---------------------------------------------------------- Read loncaparev table
                   10941: {
                   10942:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10943:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10944:             while (my $configline=<$config>) {
                   10945:                 chomp($configline);
                   10946:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10947:                 $loncaparevs{$hostid}=$loncaparev;
                   10948:             }
                   10949:             close($config);
                   10950:         }
                   10951:     }
                   10952: }
                   10953: 
1.1074    raeburn  10954: # ---------------------------------------------------------- Read serverhostID table
                   10955: {
                   10956:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10957:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10958:             while (my $configline=<$config>) {
                   10959:                 chomp($configline);
                   10960:                 my ($name,$id)=split(/:/,$configline);
                   10961:                 $serverhomeIDs{$name}=$id;
                   10962:             }
                   10963:             close($config);
                   10964:         }
                   10965:     }
                   10966: }
                   10967: 
1.1079    raeburn  10968: {
                   10969:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10970:     if (-e $file) {
                   10971:         my $parser = HTML::LCParser->new($file);
                   10972:         while (my $token = $parser->get_token()) {
                   10973:             if ($token->[0] eq 'S') {
                   10974:                 my $item = $token->[1];
                   10975:                 my $name = $token->[2]{'name'};
                   10976:                 my $value = $token->[2]{'value'};
                   10977:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10978:                     my $release = $parser->get_text();
                   10979:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10980:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10981:                 }
                   10982:             }
                   10983:         }
                   10984:     }
1.1073    raeburn  10985: }
                   10986: 
1.329     matthew  10987: # ------------- set up temporary directory
                   10988: {
1.1117    foxr     10989:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10990: 
1.11      www      10991: }
                   10992: 
1.794     albertel 10993: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10994: 				'compress_threshold'=> 20_000,
                   10995:  			        });
1.185     www      10996: 
1.281     www      10997: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10998: $dumpcount=0;
1.958     www      10999: $locknum=0;
1.22      www      11000: 
1.163     harris41 11001: &logtouch();
1.672     albertel 11002: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11003: $readit=1;
1.564     albertel 11004:     {
                   11005: 	use integer;
                   11006: 	my $test=(2**32)+1;
1.568     albertel 11007: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11008: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11009:     }
1.195     www      11010: }
1.1       albertel 11011: }
1.179     www      11012: 
1.1       albertel 11013: 1;
1.191     harris41 11014: __END__
                   11015: 
1.243     albertel 11016: =pod
                   11017: 
1.191     harris41 11018: =head1 NAME
                   11019: 
1.243     albertel 11020: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11021: 
                   11022: =head1 SYNOPSIS
                   11023: 
1.243     albertel 11024: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11025: 
                   11026:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11027: 
1.243     albertel 11028: Common parameters:
                   11029: 
                   11030: =over 4
                   11031: 
                   11032: =item *
                   11033: 
                   11034: $uname : an internal username (if $cname expecting a course Id specifically)
                   11035: 
                   11036: =item *
                   11037: 
                   11038: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11039: 
                   11040: =item *
                   11041: 
                   11042: $symb : a resource instance identifier
                   11043: 
                   11044: =item *
                   11045: 
                   11046: $namespace : the name of a .db file that contains the data needed or
                   11047: being set.
                   11048: 
                   11049: =back
                   11050: 
1.394     bowersj2 11051: =head1 OVERVIEW
1.191     harris41 11052: 
1.394     bowersj2 11053: lonnet provides subroutines which interact with the
                   11054: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11055: about classes, users, and resources.
1.243     albertel 11056: 
                   11057: For many of these objects you can also use this to store data about
                   11058: them or modify them in various ways.
1.191     harris41 11059: 
1.394     bowersj2 11060: =head2 Symbs
1.191     harris41 11061: 
1.394     bowersj2 11062: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11063: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11064: map, the resource number of the resource in the map, and the URL of
                   11065: the resource itself. The latter is somewhat redundant, but might help
                   11066: if maps change.
                   11067: 
                   11068: An example is
                   11069: 
                   11070:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11071: 
                   11072: The respective map entry is
                   11073: 
                   11074:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11075:   title="Problem 2">
                   11076:  </resource>
                   11077: 
                   11078: Symbs are used by the random number generator, as well as to store and
                   11079: restore data specific to a certain instance of for example a problem.
                   11080: 
                   11081: =head2 Storing And Retrieving Data
                   11082: 
                   11083: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11084: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11085: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11086: is is the non-critical message twin of cstore. These functions are for
                   11087: handlers to store a perl hash to a user's permanent data space in an
                   11088: easy manner, and to retrieve it again on another call. It is expected
                   11089: that a handler would use this once at the beginning to retrieve data,
                   11090: and then again once at the end to send only the new data back.
                   11091: 
                   11092: The data is stored in the user's data directory on the user's
                   11093: homeserver under the ID of the course.
                   11094: 
                   11095: The hash that is returned by restore will have all of the previous
                   11096: value for all of the elements of the hash.
                   11097: 
                   11098: Example:
                   11099: 
                   11100:  #creating a hash
                   11101:  my %hash;
                   11102:  $hash{'foo'}='bar';
                   11103: 
                   11104:  #storing it
                   11105:  &Apache::lonnet::cstore(\%hash);
                   11106: 
                   11107:  #changing a value
                   11108:  $hash{'foo'}='notbar';
                   11109: 
                   11110:  #adding a new value
                   11111:  $hash{'bar'}='foo';
                   11112:  &Apache::lonnet::cstore(\%hash);
                   11113: 
                   11114:  #retrieving the hash
                   11115:  my %history=&Apache::lonnet::restore();
                   11116: 
                   11117:  #print the hash
                   11118:  foreach my $key (sort(keys(%history))) {
                   11119:    print("\%history{$key} = $history{$key}");
                   11120:  }
                   11121: 
                   11122: Will print out:
1.191     harris41 11123: 
1.394     bowersj2 11124:  %history{1:foo} = bar
                   11125:  %history{1:keys} = foo:timestamp
                   11126:  %history{1:timestamp} = 990455579
                   11127:  %history{2:bar} = foo
                   11128:  %history{2:foo} = notbar
                   11129:  %history{2:keys} = foo:bar:timestamp
                   11130:  %history{2:timestamp} = 990455580
                   11131:  %history{bar} = foo
                   11132:  %history{foo} = notbar
                   11133:  %history{timestamp} = 990455580
                   11134:  %history{version} = 2
                   11135: 
                   11136: Note that the special hash entries C<keys>, C<version> and
                   11137: C<timestamp> were added to the hash. C<version> will be equal to the
                   11138: total number of versions of the data that have been stored. The
                   11139: C<timestamp> attribute will be the UNIX time the hash was
                   11140: stored. C<keys> is available in every historical section to list which
                   11141: keys were added or changed at a specific historical revision of a
                   11142: hash.
                   11143: 
                   11144: B<Warning>: do not store the hash that restore returns directly. This
                   11145: will cause a mess since it will restore the historical keys as if the
                   11146: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11147: 
1.394     bowersj2 11148: Calling convention:
1.191     harris41 11149: 
1.394     bowersj2 11150:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11151:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11152: 
1.394     bowersj2 11153: For more detailed information, see lonnet specific documentation.
1.191     harris41 11154: 
1.394     bowersj2 11155: =head1 RETURN MESSAGES
1.191     harris41 11156: 
1.394     bowersj2 11157: =over 4
1.191     harris41 11158: 
1.394     bowersj2 11159: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11160: 
1.394     bowersj2 11161: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11162: when the connection is brought back up
1.191     harris41 11163: 
1.394     bowersj2 11164: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11165: for later delivery
1.191     harris41 11166: 
1.967     bisitz   11167: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11168: 
1.394     bowersj2 11169: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11170: that was requested
1.191     harris41 11171: 
1.243     albertel 11172: =back
1.191     harris41 11173: 
1.243     albertel 11174: =head1 PUBLIC SUBROUTINES
1.191     harris41 11175: 
1.243     albertel 11176: =head2 Session Environment Functions
1.191     harris41 11177: 
1.243     albertel 11178: =over 4
1.191     harris41 11179: 
1.394     bowersj2 11180: =item * 
                   11181: X<appenv()>
1.949     raeburn  11182: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11183: the user envirnoment file, and will be restored for each access this
1.620     albertel 11184: user makes during this session, also modifies the %env for the current
1.949     raeburn  11185: process. Optional rolesarrayref - if defined contains a reference to an array
                   11186: of roles which are exempt from the restriction on modifying user.role entries 
                   11187: in the user's environment.db and in %env.    
1.191     harris41 11188: 
                   11189: =item *
1.394     bowersj2 11190: X<delenv()>
1.987     raeburn  11191: B<delenv($delthis,$regexp)>: removes all items from the session
                   11192: environment file that begin with $delthis. If the 
                   11193: optional second arg - $regexp - is true, $delthis is treated as a 
                   11194: regular expression, otherwise \Q$delthis\E is used. 
                   11195: The values are also deleted from the current processes %env.
1.191     harris41 11196: 
1.795     albertel 11197: =item * get_env_multiple($name) 
                   11198: 
                   11199: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11200: values may be defined and end up as an array ref.
                   11201: 
                   11202: returns an array of values
                   11203: 
1.243     albertel 11204: =back
                   11205: 
                   11206: =head2 User Information
1.191     harris41 11207: 
1.243     albertel 11208: =over 4
1.191     harris41 11209: 
                   11210: =item *
1.394     bowersj2 11211: X<queryauthenticate()>
                   11212: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11213: authentication scheme
                   11214: 
                   11215: =item *
1.394     bowersj2 11216: X<authenticate()>
1.1073    raeburn  11217: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11218: authenticate user from domain's lib servers (first use the current
                   11219: one). C<$upass> should be the users password.
1.1073    raeburn  11220: $checkdefauth is optional (value is 1 if a check should be made to
                   11221:    authenticate user using default authentication method, and allow
                   11222:    account creation if username does not have account in the domain).
                   11223: $clientcancheckhost is optional (value is 1 if checking whether the
                   11224:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11225: 
                   11226: =item *
1.394     bowersj2 11227: X<homeserver()>
                   11228: B<homeserver($uname,$udom)>: find the server which has
                   11229: the user's directory and files (there must be only one), this caches
                   11230: the answer, and also caches if there is a borken connection.
1.191     harris41 11231: 
                   11232: =item *
1.394     bowersj2 11233: X<idget()>
                   11234: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11235: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11236: username, and only 1 username per ID in a specific domain) (returns
                   11237: hash: id=>name,id=>name)
1.191     harris41 11238: 
                   11239: =item *
1.394     bowersj2 11240: X<idrget()>
                   11241: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11242: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11243: 
                   11244: =item *
1.394     bowersj2 11245: X<idput()>
                   11246: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11247: 
                   11248: =item *
1.394     bowersj2 11249: X<rolesinit()>
                   11250: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 11251: 
                   11252: =item *
1.551     albertel 11253: X<getsection()>
                   11254: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11255: course $cname, return section name/number or '' for "not in course"
                   11256: and '-1' for "no section"
                   11257: 
                   11258: =item *
1.394     bowersj2 11259: X<userenvironment()>
                   11260: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11261: passed in @what from the requested user's environment, returns a hash
                   11262: 
1.858     raeburn  11263: =item * 
                   11264: X<userlog_query()>
1.859     albertel 11265: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11266: activity.log file. %filters defines filters applied when parsing the
                   11267: log file. These can be start or end timestamps, or the type of action
                   11268: - log to look for Login or Logout events, check for Checkin or
                   11269: Checkout, role for role selection. The response is in the form
                   11270: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11271: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11272: 
1.243     albertel 11273: =back
                   11274: 
                   11275: =head2 User Roles
                   11276: 
                   11277: =over 4
                   11278: 
                   11279: =item *
                   11280: 
1.810     raeburn  11281: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11282:  F: full access
                   11283:  U,I,K: authentication modes (cxx only)
                   11284:  '': forbidden
                   11285:  1: user needs to choose course
                   11286:  2: browse allowed
1.766     albertel 11287:  A: passphrase authentication needed
1.243     albertel 11288: 
                   11289: =item *
                   11290: 
                   11291: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11292: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11293: and course level
                   11294: 
                   11295: =item *
                   11296: 
1.988     raeburn  11297: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11298: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11299: $type is Course (default) or Community.
1.988     raeburn  11300: If $forcedefault evaluates to true, text returned will be default 
                   11301: text for $type. Otherwise, if this is a course, the text returned 
                   11302: will be a custom name for the role (if defined in the course's 
                   11303: environment).  If no custom name is defined the default is returned.
                   11304:    
1.832     raeburn  11305: =item *
                   11306: 
1.935     raeburn  11307: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11308: All arguments are optional. Returns a hash of a roles, either for
                   11309: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11310: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11311: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11312: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11313: For each key, value is set to colon-separated start and end times for
                   11314: the role.  If no username and domain are specified, will default to
1.934     raeburn  11315: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11316: of role statuses (active, future or previous), roles 
                   11317: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11318: to restrict the list of roles reported. If no array ref is 
                   11319: provided for types, will default to return only active roles.
1.834     albertel 11320: 
1.243     albertel 11321: =back
                   11322: 
                   11323: =head2 User Modification
                   11324: 
                   11325: =over 4
                   11326: 
                   11327: =item *
                   11328: 
1.957     raeburn  11329: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11330: user for the level given by URL.  Optional start and end dates (leave empty
                   11331: string or zero for "no date")
1.191     harris41 11332: 
                   11333: =item *
                   11334: 
1.243     albertel 11335: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11336: change a users, password, possible return values are: ok,
                   11337: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11338: refused
1.191     harris41 11339: 
                   11340: =item *
                   11341: 
1.243     albertel 11342: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11343: 
                   11344: =item *
                   11345: 
1.1058    raeburn  11346: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11347:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11348: 
                   11349: will update user information (firstname,middlename,lastname,generation,
                   11350: permanentemail), and if forceid is true, student/employee ID also.
                   11351: A user's institutional affiliation(s) can also be updated.
                   11352: User information fields will not be overwritten with empty entries 
                   11353: unless the field is included in the $candelete array reference.
                   11354: This array is included when a single user is modified via "Manage Users",
                   11355: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11356: 
                   11357: =item *
                   11358: 
1.286     matthew  11359: modifystudent
                   11360: 
1.957     raeburn  11361: modify a student's enrollment and identification information.
1.286     matthew  11362: The course id is resolved based on the current users environment.  
                   11363: This means the envoking user must be a course coordinator or otherwise
                   11364: associated with a course.
                   11365: 
1.297     matthew  11366: This call is essentially a wrapper for lonnet::modifyuser and
                   11367: lonnet::modify_student_enrollment
1.286     matthew  11368: 
                   11369: Inputs: 
                   11370: 
                   11371: =over 4
                   11372: 
1.957     raeburn  11373: =item B<$udom> Student's loncapa domain
1.286     matthew  11374: 
1.957     raeburn  11375: =item B<$uname> Student's loncapa login name
1.286     matthew  11376: 
1.964     bisitz   11377: =item B<$uid> Student/Employee ID
1.286     matthew  11378: 
1.957     raeburn  11379: =item B<$umode> Student's authentication mode
1.286     matthew  11380: 
1.957     raeburn  11381: =item B<$upass> Student's password
1.286     matthew  11382: 
1.957     raeburn  11383: =item B<$first> Student's first name
1.286     matthew  11384: 
1.957     raeburn  11385: =item B<$middle> Student's middle name
1.286     matthew  11386: 
1.957     raeburn  11387: =item B<$last> Student's last name
1.286     matthew  11388: 
1.957     raeburn  11389: =item B<$gene> Student's generation
1.286     matthew  11390: 
1.957     raeburn  11391: =item B<$usec> Student's section in course
1.286     matthew  11392: 
                   11393: =item B<$end> Unix time of the roles expiration
                   11394: 
                   11395: =item B<$start> Unix time of the roles start date
                   11396: 
                   11397: =item B<$forceid> If defined, allow $uid to be changed
                   11398: 
                   11399: =item B<$desiredhome> server to use as home server for student
                   11400: 
1.957     raeburn  11401: =item B<$email> Student's permanent e-mail address
                   11402: 
                   11403: =item B<$type> Type of enrollment (auto or manual)
                   11404: 
1.963     raeburn  11405: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11406: 
                   11407: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11408: 
1.963     raeburn  11409: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11410: 
1.963     raeburn  11411: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11412: 
1.963     raeburn  11413: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11414: 
1.286     matthew  11415: =back
1.297     matthew  11416: 
                   11417: =item *
                   11418: 
                   11419: modify_student_enrollment
                   11420: 
                   11421: Change a students enrollment status in a class.  The environment variable
                   11422: 'role.request.course' must be defined for this function to proceed.
                   11423: 
                   11424: Inputs:
                   11425: 
                   11426: =over 4
                   11427: 
                   11428: =item $udom, students domain
                   11429: 
                   11430: =item $uname, students name
                   11431: 
                   11432: =item $uid, students user id
                   11433: 
                   11434: =item $first, students first name
                   11435: 
                   11436: =item $middle
                   11437: 
                   11438: =item $last
                   11439: 
                   11440: =item $gene
                   11441: 
                   11442: =item $usec
                   11443: 
                   11444: =item $end
                   11445: 
                   11446: =item $start
                   11447: 
1.957     raeburn  11448: =item $type
                   11449: 
                   11450: =item $locktype
                   11451: 
                   11452: =item $cid
                   11453: 
                   11454: =item $selfenroll
                   11455: 
                   11456: =item $context
                   11457: 
1.297     matthew  11458: =back
                   11459: 
1.191     harris41 11460: 
                   11461: =item *
                   11462: 
1.243     albertel 11463: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11464: custom role; give a custom role to a user for the level given by URL.  Specify
                   11465: name and domain of role author, and role name
1.191     harris41 11466: 
                   11467: =item *
                   11468: 
1.243     albertel 11469: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11470: 
                   11471: =item *
                   11472: 
1.243     albertel 11473: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11474: 
                   11475: =back
                   11476: 
                   11477: =head2 Course Infomation
                   11478: 
                   11479: =over 4
1.191     harris41 11480: 
                   11481: =item *
                   11482: 
1.1118    foxr     11483: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11484: specified course id, including all environment settings for the
                   11485: course, the description of the course will be in the hash under the
                   11486: key 'description'
1.191     harris41 11487: 
1.1118    foxr     11488: $options is an optional parameter that if supplied is a hash reference that controls
                   11489: what how this function works.  It has the following key/values:
                   11490: 
                   11491: =over 4
                   11492: 
                   11493: =item freshen_cache
                   11494: 
                   11495: If defined, and the environment cache for the course is valid, it is 
                   11496: returned in the returned hash.
                   11497: 
                   11498: =item one_time
                   11499: 
                   11500: If defined, the last cache time is set to _now_
                   11501: 
                   11502: =item user
                   11503: 
                   11504: If defined, the supplied username is used instead of the current user.
                   11505: 
                   11506: 
                   11507: =back
                   11508: 
1.191     harris41 11509: =item *
                   11510: 
1.624     albertel 11511: resdata($name,$domain,$type,@which) : request for current parameter
                   11512: setting for a specific $type, where $type is either 'course' or 'user',
                   11513: @what should be a list of parameters to ask about. This routine caches
                   11514: answers for 5 minutes.
1.243     albertel 11515: 
1.877     foxr     11516: =item *
                   11517: 
                   11518: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11519: data base, returning a hash that is keyed by the resource name and has
                   11520: values that are the resource value.  I believe that the timestamps and
                   11521: versions are also returned.
                   11522: 
                   11523: 
1.243     albertel 11524: =back
                   11525: 
                   11526: =head2 Course Modification
                   11527: 
                   11528: =over 4
1.191     harris41 11529: 
                   11530: =item *
                   11531: 
1.243     albertel 11532: writecoursepref($courseid,%prefs) : write preferences (environment
                   11533: database) for a course
1.191     harris41 11534: 
                   11535: =item *
                   11536: 
1.1011    raeburn  11537: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11538: 
                   11539: =item *
                   11540: 
1.1038    raeburn  11541: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11542: 
                   11543: =back
                   11544: 
                   11545: =head2 Resource Subroutines
                   11546: 
                   11547: =over 4
1.191     harris41 11548: 
                   11549: =item *
                   11550: 
1.243     albertel 11551: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11552: 
                   11553: =item *
                   11554: 
1.243     albertel 11555: repcopy($filename) : subscribes to the requested file, and attempts to
                   11556: replicate from the owning library server, Might return
1.607     raeburn  11557: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11558: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11559: resource. Expects the local filesystem pathname
                   11560: (/home/httpd/html/res/....)
                   11561: 
                   11562: =back
                   11563: 
                   11564: =head2 Resource Information
                   11565: 
                   11566: =over 4
1.191     harris41 11567: 
                   11568: =item *
                   11569: 
1.243     albertel 11570: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11571: a vairety of different possible values, $varname should be a request
                   11572: string, and the other parameters can be used to specify who and what
                   11573: one is asking about.
                   11574: 
                   11575: Possible values for $varname are environment.lastname (or other item
                   11576: from the envirnment hash), user.name (or someother aspect about the
                   11577: user), resource.0.maxtries (or some other part and parameter of a
                   11578: resource)
1.204     albertel 11579: 
                   11580: =item *
                   11581: 
1.243     albertel 11582: directcondval($number) : get current value of a condition; reads from a state
                   11583: string
1.204     albertel 11584: 
                   11585: =item *
                   11586: 
1.243     albertel 11587: condval($condidx) : value of condition index based on state
1.204     albertel 11588: 
                   11589: =item *
                   11590: 
1.243     albertel 11591: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11592: resource's metadata, $what should be either a specific key, or either
                   11593: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11594: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11595: 
                   11596: this function automatically caches all requests
1.191     harris41 11597: 
                   11598: =item *
                   11599: 
1.243     albertel 11600: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11601: network of library servers; returns file handle of where SQL and regex results
                   11602: will be stored for query
1.191     harris41 11603: 
                   11604: =item *
                   11605: 
1.243     albertel 11606: symbread($filename) : return symbolic list entry (filename argument optional);
                   11607: returns the data handle
1.191     harris41 11608: 
                   11609: =item *
                   11610: 
1.243     albertel 11611: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11612: a possible symb for the URL in $thisfn, and if is an encryypted
                   11613: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11614: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11615: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11616: 
1.191     harris41 11617: 
                   11618: =item *
                   11619: 
1.243     albertel 11620: symbclean($symb) : removes versions numbers from a symb, returns the
                   11621: cleaned symb
1.191     harris41 11622: 
                   11623: =item *
                   11624: 
1.243     albertel 11625: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11626: course map, user must be in a course for it to work.
1.191     harris41 11627: 
                   11628: =item *
                   11629: 
1.243     albertel 11630: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11631: 
                   11632: =item *
                   11633: 
1.243     albertel 11634: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11635: a random seed, all arguments are optional, if they aren't sent it uses the
                   11636: environment to derive them. Note: if symb isn't sent and it can't get one
                   11637: from &symbread it will use the current time as its return value
1.191     harris41 11638: 
                   11639: =item *
                   11640: 
1.243     albertel 11641: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11642: unfakeable, receipt
1.191     harris41 11643: 
                   11644: =item *
                   11645: 
1.620     albertel 11646: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11647: 
                   11648: =item *
                   11649: 
1.243     albertel 11650: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11651: 
                   11652: =item *
                   11653: 
1.243     albertel 11654: 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 11655: 
                   11656: =item *
                   11657: 
1.243     albertel 11658: 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 11659: 
                   11660: =item *
                   11661: 
1.243     albertel 11662: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11663: 
                   11664: =item *
                   11665: 
1.243     albertel 11666: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11667: forcing spreadsheet to reevaluate the resource scores next time.
                   11668: 
                   11669: =back
                   11670: 
                   11671: =head2 Storing/Retreiving Data
                   11672: 
                   11673: =over 4
1.191     harris41 11674: 
                   11675: =item *
                   11676: 
1.243     albertel 11677: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11678: for this url; hashref needs to be given and should be a \%hashname; the
                   11679: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11680: be derived from the env
1.191     harris41 11681: 
                   11682: =item *
                   11683: 
1.243     albertel 11684: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11685: uses critical subroutine
1.191     harris41 11686: 
                   11687: =item *
                   11688: 
1.243     albertel 11689: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11690: all args are optional
1.191     harris41 11691: 
                   11692: =item *
                   11693: 
1.717     albertel 11694: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11695: dumps the complete (or key matching regexp) namespace into a hash
                   11696: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11697: normally &store()ed into
                   11698: 
                   11699: $range should be either an integer '100' (give me the first 100
                   11700:                                            matching records)
                   11701:               or be  two integers sperated by a - with no spaces
                   11702:                  '30-50' (give me the 30th through the 50th matching
                   11703:                           records)
                   11704: 
                   11705: 
                   11706: =item *
                   11707: 
                   11708: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11709: replaces a &store() version of data with a replacement set of data
                   11710: for a particular resource in a namespace passed in the $storehash hash 
                   11711: reference
                   11712: 
                   11713: =item *
                   11714: 
1.243     albertel 11715: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11716: works very similar to store/cstore, but all data is stored in a
                   11717: temporary location and can be reset using tmpreset, $storehash should
                   11718: be a hash reference, returns nothing on success
1.191     harris41 11719: 
                   11720: =item *
                   11721: 
1.243     albertel 11722: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11723: similar to restore, but all data is stored in a temporary location and
                   11724: can be reset using tmpreset. Returns a hash of values on success,
                   11725: error string otherwise.
1.191     harris41 11726: 
                   11727: =item *
                   11728: 
1.243     albertel 11729: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11730: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11731: 
                   11732: =item *
                   11733: 
1.243     albertel 11734: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11735: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11736: 
                   11737: =item *
                   11738: 
1.243     albertel 11739: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11740: namesp ($udom and $uname are optional)
1.191     harris41 11741: 
                   11742: =item *
                   11743: 
1.702     albertel 11744: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11745: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11746: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11747: 
1.702     albertel 11748: $range should be either an integer '100' (give me the first 100
                   11749:                                            matching records)
                   11750:               or be  two integers sperated by a - with no spaces
                   11751:                  '30-50' (give me the 30th through the 50th matching
                   11752:                           records)
1.449     matthew  11753: =item *
                   11754: 
                   11755: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11756: $store can be a scalar, an array reference, or if the amount to be 
                   11757: incremented is > 1, a hash reference.
                   11758: 
                   11759: ($udom and $uname are optional)
1.191     harris41 11760: 
                   11761: =item *
                   11762: 
1.243     albertel 11763: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11764: ($udom and $uname are optional)
1.191     harris41 11765: 
                   11766: =item *
                   11767: 
1.243     albertel 11768: cput($namespace,$storehash,$udom,$uname) : critical put
                   11769: ($udom and $uname are optional)
1.191     harris41 11770: 
                   11771: =item *
                   11772: 
1.748     albertel 11773: newput($namespace,$storehash,$udom,$uname) :
                   11774: 
                   11775: Attempts to store the items in the $storehash, but only if they don't
                   11776: currently exist, if this succeeds you can be certain that you have 
                   11777: successfully created a new key value pair in the $namespace db.
                   11778: 
                   11779: 
                   11780: Args:
                   11781:  $namespace: name of database to store values to
                   11782:  $storehash: hashref to store to the db
                   11783:  $udom: (optional) domain of user containing the db
                   11784:  $uname: (optional) name of user caontaining the db
                   11785: 
                   11786: Returns:
                   11787:  'ok' -> succeeded in storing all keys of $storehash
                   11788:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11789:                         least <key> already existed in the db (other
                   11790:                         requested keys may also already exist)
1.967     bisitz   11791:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11792:  'con_lost' -> unable to contact request server
                   11793:  'refused' -> action was not allowed by remote machine
                   11794: 
                   11795: 
                   11796: =item *
                   11797: 
1.243     albertel 11798: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11799: reference filled in from namesp (encrypts the return communication)
                   11800: ($udom and $uname are optional)
1.191     harris41 11801: 
                   11802: =item *
                   11803: 
1.243     albertel 11804: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11805: critical subroutine
                   11806: 
1.806     raeburn  11807: =item *
                   11808: 
1.860     raeburn  11809: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11810: array reference filled in from namespace found in domain level on either
                   11811: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11812: 
                   11813: =item *
                   11814: 
1.860     raeburn  11815: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11816: domain level either on specified domain server ($uhome) or primary domain 
                   11817: server ($udom and $uhome are optional)
1.806     raeburn  11818: 
1.943     raeburn  11819: =item * 
                   11820: 
                   11821: get_domain_defaults($target_domain) : returns hash with defaults for
                   11822: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11823: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11824: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11825: Values are retrieved from cache (if current), or from domain's configuration.db
                   11826: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11827: or lonTabs/domain.tab. 
                   11828: 
                   11829: %domdefaults = &get_auth_defaults($target_domain);
                   11830: 
1.243     albertel 11831: =back
                   11832: 
                   11833: =head2 Network Status Functions
                   11834: 
                   11835: =over 4
1.191     harris41 11836: 
                   11837: =item *
                   11838: 
                   11839: dirlist($uri) : return directory list based on URI
                   11840: 
                   11841: =item *
                   11842: 
1.243     albertel 11843: spareserver() : find server with least workload from spare.tab
                   11844: 
1.986     foxr     11845: 
                   11846: =item *
                   11847: 
                   11848: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11849: if there is no corresponding loncapa host.
                   11850: 
1.243     albertel 11851: =back
                   11852: 
1.986     foxr     11853: 
1.243     albertel 11854: =head2 Apache Request
                   11855: 
                   11856: =over 4
1.191     harris41 11857: 
                   11858: =item *
                   11859: 
1.243     albertel 11860: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11861: localhost, posts hash
                   11862: 
                   11863: =back
                   11864: 
                   11865: =head2 Data to String to Data
                   11866: 
                   11867: =over 4
1.191     harris41 11868: 
                   11869: =item *
                   11870: 
1.243     albertel 11871: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11872: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11873: 
                   11874: =item *
                   11875: 
1.243     albertel 11876: hashref2str($hashref) : convert a hashref into a string complete with
                   11877: escaping and '=' and '&' separators, supports elements that are
                   11878: arrayrefs and hashrefs
1.191     harris41 11879: 
                   11880: =item *
                   11881: 
1.243     albertel 11882: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11883: with escaping and '&' separators, supports elements that are arrayrefs
                   11884: and hashrefs
1.191     harris41 11885: 
                   11886: =item *
                   11887: 
1.243     albertel 11888: str2hash($string) : convert string to hash using unescaping and
                   11889: splitting on '=' and '&', supports elements that are arrayrefs and
                   11890: hashrefs
1.191     harris41 11891: 
                   11892: =item *
                   11893: 
1.243     albertel 11894: str2array($string) : convert string to hash using unescaping and
                   11895: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11896: 
                   11897: =back
                   11898: 
                   11899: =head2 Logging Routines
                   11900: 
                   11901: 
                   11902: These routines allow one to make log messages in the lonnet.log and
                   11903: lonnet.perm logfiles.
1.191     harris41 11904: 
1.1119    foxr     11905: =over 4
                   11906: 
1.191     harris41 11907: =item *
                   11908: 
1.243     albertel 11909: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11910: 
                   11911: =item *
                   11912: 
1.243     albertel 11913: logthis() : append message to the normal lonnet.log file, it gets
                   11914: preiodically rolled over and deleted.
1.191     harris41 11915: 
                   11916: =item *
                   11917: 
1.243     albertel 11918: logperm() : append a permanent message to lonnet.perm.log, this log
                   11919: file never gets deleted by any automated portion of the system, only
                   11920: messages of critical importance should go in here.
                   11921: 
1.1119    foxr     11922: 
1.243     albertel 11923: =back
                   11924: 
                   11925: =head2 General File Helper Routines
                   11926: 
                   11927: =over 4
1.191     harris41 11928: 
                   11929: =item *
                   11930: 
1.481     raeburn  11931: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11932: (a) files in /uploaded
                   11933:   (i) If a local copy of the file exists - 
                   11934:       compares modification date of local copy with last-modified date for 
                   11935:       definitive version stored on home server for course. If local copy is 
                   11936:       stale, requests a new version from the home server and stores it. 
                   11937:       If the original has been removed from the home server, then local copy 
                   11938:       is unlinked.
                   11939:   (ii) If local copy does not exist -
                   11940:       requests the file from the home server and stores it. 
                   11941:   
                   11942:   If $caller is 'uploadrep':  
                   11943:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11944:     for request for files originally uploaded via DOCS. 
                   11945:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11946:   
                   11947:   Otherwise:
                   11948:      This indicates a call from the content generation phase of the request.
                   11949:      -  returns the entire contents of the file or -1.
                   11950:      
                   11951: (b) files in /res
                   11952:    - returns the entire contents of a file or -1; 
                   11953:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11954: 
1.712     albertel 11955: 
                   11956: =item *
                   11957: 
                   11958: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11959:                   reference
                   11960: 
                   11961: returns either a stat() list of data about the file or an empty list
                   11962: if the file doesn't exist or couldn't find out about it (connection
                   11963: problems or user unknown)
                   11964: 
1.191     harris41 11965: =item *
                   11966: 
1.243     albertel 11967: filelocation($dir,$file) : returns file system location of a file
                   11968: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11969: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11970: and a file of ../bob will become /a/bob)
1.191     harris41 11971: 
                   11972: =item *
                   11973: 
                   11974: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11975: filelocation except for hrefs
                   11976: 
                   11977: =item *
                   11978: 
                   11979: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11980: 
1.243     albertel 11981: =back
                   11982: 
1.608     albertel 11983: =head2 Usererfile file routines (/uploaded*)
                   11984: 
                   11985: =over 4
                   11986: 
                   11987: =item *
                   11988: 
                   11989: userfileupload(): main rotine for putting a file in a user or course's
                   11990:                   filespace, arguments are,
                   11991: 
1.620     albertel 11992:  formname - required - this is the name of the element in $env where the
1.608     albertel 11993:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11994:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11995:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11996:  context - if coursedoc, store the file in the course of the active role
                   11997:              of the current user; 
                   11998:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11999:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12000:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12001:          if undefined, it will be placed in "unknown"
                   12002: 
                   12003:  (This routine calls clean_filename() to remove any dangerous
                   12004:  characters from the filename, and then calls finuserfileupload() to
                   12005:  complete the transaction)
                   12006: 
                   12007:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12008:  and /adm/notfound.html if unsuccessful
                   12009: 
                   12010: =item *
                   12011: 
                   12012: clean_filename(): routine for cleaing a filename up for storage in
                   12013:                  userfile space, argument is:
                   12014: 
                   12015:  filename - proposed filename
                   12016: 
                   12017: returns: the new clean filename
                   12018: 
                   12019: =item *
                   12020: 
1.1090    raeburn  12021: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12022: userspace, probably shouldn't be called directly
                   12023: 
                   12024:   docuname: username or courseid of destination for the file
                   12025:   docudom: domain of user/course of destination for the file
                   12026:   formname: same as for userfileupload()
1.1090    raeburn  12027:   fname: filename (including subdirectories) for the file
                   12028:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12029:   allfiles: reference to hash used to store objects found by parser
                   12030:   codebase: reference to hash used for codebases of java objects found by parser
                   12031:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12032:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12033:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12034:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12035:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12036:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12037:   mimetype: reference to scalar to accommodate mime type determined
                   12038:             from File::MMagic if $parser = parse.
1.608     albertel 12039: 
                   12040:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12041:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12042:  was 'overwrite').
                   12043:  
1.608     albertel 12044: 
                   12045: =item *
                   12046: 
                   12047: renameuserfile(): renames an existing userfile to a new name
                   12048: 
                   12049:   Args:
                   12050:    docuname: username or courseid of destination for the file
                   12051:    docudom: domain of user/course of destination for the file
                   12052:    old: current file name (including any subdirs under userfiles)
                   12053:    new: desired file name (including any subdirs under userfiles)
                   12054: 
                   12055: =item *
                   12056: 
                   12057: mkdiruserfile(): creates a directory is a userfiles dir
                   12058: 
                   12059:   Args:
                   12060:    docuname: username or courseid of destination for the file
                   12061:    docudom: domain of user/course of destination for the file
                   12062:    dir: dir to create (including any subdirs under userfiles)
                   12063: 
                   12064: =item *
                   12065: 
                   12066: removeuserfile(): removes a file that exists in userfiles
                   12067: 
                   12068:   Args:
                   12069:    docuname: username or courseid of destination for the file
                   12070:    docudom: domain of user/course of destination for the file
                   12071:    fname: filname to delete (including any subdirs under userfiles)
                   12072: 
                   12073: =item *
                   12074: 
                   12075: removeuploadedurl(): convience function for removeuserfile()
                   12076: 
                   12077:   Args:
                   12078:    url:  a full /uploaded/... url to delete
                   12079: 
1.747     albertel 12080: =item * 
                   12081: 
                   12082: get_portfile_permissions():
                   12083:   Args:
                   12084:     domain: domain of user or course contain the portfolio files
                   12085:     user: name of user or num of course contain the portfolio files
                   12086:   Returns:
                   12087:     hashref of a dump of the proper file_permissions.db
                   12088:    
                   12089: 
                   12090: =item * 
                   12091: 
                   12092: get_access_controls():
                   12093: 
                   12094: Args:
                   12095:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12096:   group: (optional) the group you want the files associated with
                   12097:   file: (optional) the file you want access info on
                   12098: 
                   12099: Returns:
1.749     raeburn  12100:     a hash (keys are file names) of hashes containing
                   12101:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12102:         values are XML containing access control settings (see below) 
1.747     albertel 12103: 
                   12104: Internal notes:
                   12105: 
1.749     raeburn  12106:  access controls are stored in file_permissions.db as key=value pairs.
                   12107:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12108:         where scope -> public,guest,course,group,domains or users.
                   12109:               end -> UNIX time for end of access (0 -> no end date)
                   12110:               start -> UNIX time for start of access
                   12111: 
                   12112:     value -> XML description of access control
                   12113:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12114:             <start></start>
                   12115:             <end></end>
                   12116: 
                   12117:             <password></password>  for scope type = guest
                   12118: 
                   12119:             <domain></domain>     for scope type = course or group
                   12120:             <number></number>
                   12121:             <roles id="">
                   12122:              <role></role>
                   12123:              <access></access>
                   12124:              <section></section>
                   12125:              <group></group>
                   12126:             </roles>
                   12127: 
                   12128:             <dom></dom>         for scope type = domains
                   12129: 
                   12130:             <users>             for scope type = users
                   12131:              <user>
                   12132:               <uname></uname>
                   12133:               <udom></udom>
                   12134:              </user>
                   12135:             </users>
                   12136:            </scope> 
                   12137:               
                   12138:  Access data is also aggregated for each file in an additional key=value pair:
                   12139:  key -> path to file/file_name\0accesscontrol 
                   12140:  value -> reference to hash
                   12141:           hash contains key = value pairs
                   12142:           where key = uniqueID:scope_end_start
                   12143:                 value = UNIX time record was last updated
                   12144: 
                   12145:           Used to improve speed of look-ups of access controls for each file.  
                   12146:  
                   12147:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12148: 
                   12149: modify_access_controls():
                   12150: 
                   12151: Modifies access controls for a portfolio file
                   12152: Args
                   12153: 1. file name
                   12154: 2. reference to hash of required changes,
                   12155: 3. domain
                   12156: 4. username
                   12157:   where domain,username are the domain of the portfolio owner 
                   12158:   (either a user or a course) 
                   12159: 
                   12160: Returns:
                   12161: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12162: 2. result of deletions ('ok' or 'error', with error message).
                   12163: 3. reference to hash of any new or updated access controls.
                   12164: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12165:    key = integer (inbound ID)
                   12166:    value = uniqueID  
1.747     albertel 12167: 
1.608     albertel 12168: =back
                   12169: 
1.243     albertel 12170: =head2 HTTP Helper Routines
                   12171: 
                   12172: =over 4
                   12173: 
1.191     harris41 12174: =item *
                   12175: 
                   12176: escape() : unpack non-word characters into CGI-compatible hex codes
                   12177: 
                   12178: =item *
                   12179: 
                   12180: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12181: 
1.243     albertel 12182: =back
                   12183: 
                   12184: =head1 PRIVATE SUBROUTINES
                   12185: 
                   12186: =head2 Underlying communication routines (Shouldn't call)
                   12187: 
                   12188: =over 4
                   12189: 
                   12190: =item *
                   12191: 
                   12192: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12193: 
                   12194: =item *
                   12195: 
                   12196: reply() : uses subreply to send a message to remote machine, logs all failures
                   12197: 
                   12198: =item *
                   12199: 
                   12200: critical() : passes a critical message to another server; if cannot
                   12201: get through then place message in connection buffer directory and
                   12202: returns con_delayed, if incapable of saving message, returns
                   12203: con_failed
                   12204: 
                   12205: =item *
                   12206: 
                   12207: reconlonc() : tries to reconnect lonc client processes.
                   12208: 
                   12209: =back
                   12210: 
                   12211: =head2 Resource Access Logging
                   12212: 
                   12213: =over 4
                   12214: 
                   12215: =item *
                   12216: 
                   12217: flushcourselogs() : flush (save) buffer logs and access logs
                   12218: 
                   12219: =item *
                   12220: 
                   12221: courselog($what) : save message for course in hash
                   12222: 
                   12223: =item *
                   12224: 
                   12225: courseacclog($what) : save message for course using &courselog().  Perform
                   12226: special processing for specific resource types (problems, exams, quizzes, etc).
                   12227: 
1.191     harris41 12228: =item *
                   12229: 
                   12230: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12231: as a PerlChildExitHandler
1.243     albertel 12232: 
                   12233: =back
                   12234: 
                   12235: =head2 Other
                   12236: 
                   12237: =over 4
                   12238: 
                   12239: =item *
                   12240: 
                   12241: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12242: 
                   12243: =back
                   12244: 
                   12245: =cut
1.877     foxr     12246: 

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