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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1126  ! raeburn     4: # $Id: lonnet.pm,v 1.1125 2011/08/05 04:35:50 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1117    foxr       98: 
1.1090    raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1106    raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1073    raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1073    raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   258:                     $ua->timeout(4);
1.1073    raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1081    raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1081    raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   274:                 $loncaparev = $1;
                    275:             }
1.993     raeburn   276:         }
1.1073    raeburn   277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   278:     }
                    279: }
                    280: 
1.1074    raeburn   281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    285:         if (defined($cached)) {
                    286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') { 
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
                    299:         }
                    300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
                    305:     }
                    306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    307: }
                    308: 
1.1121    raeburn   309: sub get_remote_globals {
                    310:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   311:     my ($result,%returnhash,%whatneeded);
                    312:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   313:         foreach my $what (sort(keys(%{$whathash}))) {
                    314:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   315:             my ($response,$cached);
1.1121    raeburn   316:             unless ($ignore_cache) {
1.1125    raeburn   317:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   318:             }
                    319:             if (defined($cached)) {
1.1125    raeburn   320:                 $returnhash{$what} = $response;
1.1121    raeburn   321:             } else {
1.1125    raeburn   322:                 $whatneeded{$what} = 1;
1.1121    raeburn   323:             }
                    324:         }
1.1125    raeburn   325:         if (keys(%whatneeded) == 0) {
                    326:             $result = 'ok';
                    327:         } else {
1.1121    raeburn   328:             my $requested = &freeze_escape(\%whatneeded);
                    329:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   330:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    331:                 ($rep eq 'unknown_cmd')) {
                    332:                 $result = $rep;
                    333:             } else {
                    334:                 $result = 'ok';
1.1121    raeburn   335:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   336:                 foreach my $item (@pairs) {
                    337:                     my ($key,$value)=split(/=/,$item,2);
                    338:                     my $what = &unescape($key);
                    339:                     my $hashid = $lonhost.'-'.$what;
                    340:                     $returnhash{$what}=&thaw_unescape($value);
                    341:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   342:                 }
                    343:             }
                    344:         }
                    345:     }
1.1125    raeburn   346:     return ($result,\%returnhash);
1.1121    raeburn   347: }
                    348: 
1.1124    raeburn   349: sub remote_devalidate_cache {
                    350:     my ($lonhost,$name,$id) = @_;
                    351:     my $response = &reply('devalidatecache',&escape($name).':'.&escape($id),$lonhost);
                    352:     return $response;
                    353: }
                    354: 
1.1       albertel  355: # -------------------------------------------------- Non-critical communication
                    356: sub subreply {
                    357:     my ($cmd,$server)=@_;
1.838     albertel  358:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      359:     #
                    360:     #  With loncnew process trimming, there's a timing hole between lonc server
                    361:     #  process exit and the master server picking up the listen on the AF_UNIX
                    362:     #  socket.  In that time interval, a lock file will exist:
                    363: 
                    364:     my $lockfile=$peerfile.".lock";
                    365:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    366: 	sleep(1);
                    367:     }
                    368:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      369:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      370:     #
1.550     foxr      371:     #   We'll give the connection a few tries before abandoning it.  If
                    372:     #   connection is not possible, we'll con_lost back to the client.
                    373:     #   
                    374:     my $client;
                    375:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    376: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    377: 				      Type    => SOCK_STREAM,
                    378: 				      Timeout => 10);
1.869     albertel  379: 	if ($client) {
1.550     foxr      380: 	    last;		# Connected!
1.850     albertel  381: 	} else {
1.853     albertel  382: 	    &create_connection(&hostname($server),$server);
1.550     foxr      383: 	}
1.850     albertel  384:         sleep(1);		# Try again later if failed connection.
1.550     foxr      385:     }
                    386:     my $answer;
                    387:     if ($client) {
1.704     albertel  388: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      389: 	$answer=<$client>;
                    390: 	if (!$answer) { $answer="con_lost"; }
                    391: 	chomp($answer);
                    392:     } else {
                    393: 	$answer = 'con_lost';	# Failed connection.
                    394:     }
1.1       albertel  395:     return $answer;
                    396: }
                    397: 
                    398: sub reply {
                    399:     my ($cmd,$server)=@_;
1.838     albertel  400:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  401:     my $answer=subreply($cmd,$server);
1.65      www       402:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  403:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       404:                 " $cmd to $server returned $answer</font>");
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: # ----------------------------------------------------------- Send USR1 to lonc
                    410: 
                    411: sub reconlonc {
1.891     albertel  412:     my ($lonid) = @_;
                    413:     my $hostname = &hostname($lonid);
                    414:     if ($lonid) {
                    415: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    416: 	if ($hostname && -e $peerfile) {
                    417: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    418: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    419: 					     Type    => SOCK_STREAM,
                    420: 					     Timeout => 10);
                    421: 	    if ($client) {
                    422: 		print $client ("reset_retries\n");
                    423: 		my $answer=<$client>;
                    424: 		#reset just this one.
                    425: 	    }
                    426: 	}
                    427: 	return;
                    428:     }
                    429: 
1.836     www       430:     &logthis("Trying to reconnect lonc");
1.1       albertel  431:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  432:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  433: 	my $loncpid=<$fh>;
                    434:         chomp($loncpid);
                    435:         if (kill 0 => $loncpid) {
                    436: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    437:             kill USR1 => $loncpid;
                    438:             sleep 1;
1.836     www       439:          } else {
1.12      www       440: 	    &logthis(
1.672     albertel  441:                "<font color=\"blue\">WARNING:".
1.12      www       442:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  443:         }
                    444:     } else {
1.836     www       445: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  446:     }
                    447: }
                    448: 
                    449: # ------------------------------------------------------ Critical communication
1.12      www       450: 
1.1       albertel  451: sub critical {
                    452:     my ($cmd,$server)=@_;
1.838     albertel  453:     unless (&hostname($server)) {
1.672     albertel  454:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       455:                " Critical message to unknown server ($server)</font>");
                    456:         return 'no_such_host';
                    457:     }
1.1       albertel  458:     my $answer=reply($cmd,$server);
                    459:     if ($answer eq 'con_lost') {
                    460: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  461: 	my $answer=reply($cmd,$server);
1.1       albertel  462:         if ($answer eq 'con_lost') {
                    463:             my $now=time;
                    464:             my $middlename=$cmd;
1.5       www       465:             $middlename=substr($middlename,0,16);
1.1       albertel  466:             $middlename=~s/\W//g;
                    467:             my $dfilename=
1.305     www       468:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    469:             $dumpcount++;
1.1       albertel  470:             {
1.448     albertel  471: 		my $dfh;
                    472: 		if (open($dfh,">$dfilename")) {
                    473: 		    print $dfh "$cmd\n"; 
                    474: 		    close($dfh);
                    475: 		}
1.1       albertel  476:             }
                    477:             sleep 2;
                    478:             my $wcmd='';
                    479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,"<$dfilename")) {
                    482: 		    $wcmd=<$dfh>; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             chomp($wcmd);
1.7       www       487:             if ($wcmd eq $cmd) {
1.672     albertel  488: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       489:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  490:                 &logperm("D:$server:$cmd");
                    491: 	        return 'con_delayed';
                    492:             } else {
1.672     albertel  493:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       494:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  495:                 &logperm("F:$server:$cmd");
                    496:                 return 'con_failed';
                    497:             }
                    498:         }
                    499:     }
                    500:     return $answer;
1.405     albertel  501: }
                    502: 
1.755     albertel  503: # ------------------------------------------- check if return value is an error
                    504: 
                    505: sub error {
                    506:     my ($result) = @_;
1.756     albertel  507:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  508: 	if ($2 == 2) { return undef; }
                    509: 	return $1;
                    510:     }
                    511:     return undef;
                    512: }
                    513: 
1.783     albertel  514: sub convert_and_load_session_env {
                    515:     my ($lonidsdir,$handle)=@_;
                    516:     my @profile;
                    517:     {
1.917     albertel  518: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    519: 	if (!$opened) {
1.915     albertel  520: 	    return 0;
                    521: 	}
1.783     albertel  522: 	flock($idf,LOCK_SH);
                    523: 	@profile=<$idf>;
                    524: 	close($idf);
                    525:     }
                    526:     my %temp_env;
                    527:     foreach my $line (@profile) {
1.786     albertel  528: 	if ($line !~ m/=/) {
                    529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	chomp($line);
                    532: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    533: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    534:     }
                    535:     unlink("$lonidsdir/$handle.id");
                    536:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    537: 	    0640)) {
                    538: 	%disk_env = %temp_env;
                    539: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    540: 	untie(%disk_env);
                    541:     }
1.786     albertel  542:     return 1;
1.783     albertel  543: }
                    544: 
1.374     www       545: # ------------------------------------------- Transfer profile into environment
1.780     albertel  546: my $env_loaded;
                    547: sub transfer_profile_to_env {
1.788     albertel  548:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    549:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       550: 
1.720     albertel  551:     if (!defined($lonidsdir)) {
                    552: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    553:     }
                    554:     if (!defined($handle)) {
                    555:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    556:     }
                    557: 
1.786     albertel  558:     my $convert;
                    559:     {
1.917     albertel  560:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561: 	if (!$opened) {
1.915     albertel  562: 	    return;
                    563: 	}
1.786     albertel  564: 	flock($idf,LOCK_SH);
                    565: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 		&GDBM_READER(),0640)) {
                    567: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    568: 	    untie(%disk_env);
                    569: 	} else {
                    570: 	    $convert = 1;
                    571: 	}
                    572:     }
                    573:     if ($convert) {
                    574: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    575: 	    &logthis("Failed to load session, or convert session.");
                    576: 	}
1.374     www       577:     }
1.783     albertel  578: 
1.786     albertel  579:     my %remove;
1.783     albertel  580:     while ( my $envname = each(%env) ) {
1.433     matthew   581:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    582:             if ($time < time-300) {
1.783     albertel  583:                 $remove{$key}++;
1.433     matthew   584:             }
                    585:         }
                    586:     }
1.783     albertel  587: 
1.619     albertel  588:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  589:     $env_loaded=1;
1.783     albertel  590:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   591:         &delenv($expired_key);
1.374     www       592:     }
1.1       albertel  593: }
                    594: 
1.916     albertel  595: # ---------------------------------------------------- Check for valid session 
                    596: sub check_for_valid_session {
                    597:     my ($r) = @_;
                    598:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    599:     my $lonid=$cookies{'lonID'};
                    600:     return undef if (!$lonid);
                    601: 
                    602:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    603:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    604:     return undef if (!-e "$lonidsdir/$handle.id");
                    605: 
1.917     albertel  606:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    607:     return undef if (!$opened);
1.916     albertel  608: 
                    609:     flock($idf,LOCK_SH);
                    610:     my %disk_env;
                    611:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    612: 	    &GDBM_READER(),0640)) {
                    613: 	return undef;	
                    614:     }
                    615: 
                    616:     if (!defined($disk_env{'user.name'})
                    617: 	|| !defined($disk_env{'user.domain'})) {
                    618: 	return undef;
                    619:     }
                    620:     return $handle;
                    621: }
                    622: 
1.830     albertel  623: sub timed_flock {
                    624:     my ($file,$lock_type) = @_;
                    625:     my $failed=0;
                    626:     eval {
                    627: 	local $SIG{__DIE__}='DEFAULT';
                    628: 	local $SIG{ALRM}=sub {
                    629: 	    $failed=1;
                    630: 	    die("failed lock");
                    631: 	};
                    632: 	alarm(13);
                    633: 	flock($file,$lock_type);
                    634: 	alarm(0);
                    635:     };
                    636:     if ($failed) {
                    637: 	return undef;
                    638:     } else {
                    639: 	return 1;
                    640:     }
                    641: }
                    642: 
1.5       www       643: # ---------------------------------------------------------- Append Environment
                    644: 
                    645: sub appenv {
1.949     raeburn   646:     my ($newenv,$roles) = @_;
                    647:     if (ref($newenv) eq 'HASH') {
                    648:         foreach my $key (keys(%{$newenv})) {
                    649:             my $refused = 0;
                    650: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    651:                 $refused = 1;
                    652:                 if (ref($roles) eq 'ARRAY') {
                    653:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    654:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    655:                         $refused = 0;
                    656:                     }
                    657:                 }
                    658:             }
                    659:             if ($refused) {
                    660:                 &logthis("<font color=\"blue\">WARNING: ".
                    661:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    662:                          .'</font>');
                    663: 	        delete($newenv->{$key});
                    664:             } else {
                    665:                 $env{$key}=$newenv->{$key};
                    666:             }
                    667:         }
                    668:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    669:         if ($opened
                    670: 	    && &timed_flock($env_file,LOCK_EX)
                    671: 	    &&
                    672: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    673: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    674: 	    while (my ($key,$value) = each(%{$newenv})) {
                    675: 	        $disk_env{$key} = $value;
                    676: 	    }
                    677: 	    untie(%disk_env);
1.35      www       678:         }
1.191     harris41  679:     }
1.56      www       680:     return 'ok';
                    681: }
                    682: # ----------------------------------------------------- Delete from Environment
                    683: 
                    684: sub delenv {
1.1104    raeburn   685:     my ($delthis,$regexp,$roles) = @_;
                    686:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    687:         my $refused = 1;
                    688:         if (ref($roles) eq 'ARRAY') {
                    689:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    690:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    691:                 $refused = 0;
                    692:             }
                    693:         }
                    694:         if ($refused) {
                    695:             &logthis("<font color=\"blue\">WARNING: ".
                    696:                      "Attempt to delete from environment ".$delthis);
                    697:             return 'error';
                    698:         }
1.56      www       699:     }
1.917     albertel  700:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:     if ($opened
1.915     albertel  702: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  703: 	&&
                    704: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  706: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   707: 	    if ($regexp) {
                    708:                 if ($key=~/^$delthis/) {
                    709:                     delete($env{$key});
                    710:                     delete($disk_env{$key});
                    711:                 } 
                    712:             } else {
                    713:                 if ($key=~/^\Q$delthis\E/) {
                    714: 		    delete($env{$key});
                    715: 		    delete($disk_env{$key});
                    716: 	        }
                    717:             }
1.448     albertel  718: 	}
1.783     albertel  719: 	untie(%disk_env);
1.5       www       720:     }
                    721:     return 'ok';
1.369     albertel  722: }
                    723: 
1.790     albertel  724: sub get_env_multiple {
                    725:     my ($name) = @_;
                    726:     my @values;
                    727:     if (defined($env{$name})) {
                    728:         # exists is it an array
                    729:         if (ref($env{$name})) {
                    730:             @values=@{ $env{$name} };
                    731:         } else {
                    732:             $values[0]=$env{$name};
                    733:         }
                    734:     }
                    735:     return(@values);
                    736: }
                    737: 
1.958     www       738: # ------------------------------------------------------------------- Locking
                    739: 
                    740: sub set_lock {
                    741:     my ($text)=@_;
                    742:     $locknum++;
                    743:     my $id=$$.'-'.$locknum;
                    744:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    745:              'session.lock.'.$id => $text});
                    746:     return $id;
                    747: }
                    748: 
                    749: sub get_locks {
                    750:     my $num=0;
                    751:     my %texts=();
                    752:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    753:        if ($lock=~/\w/) {
                    754:           $num++;
                    755:           $texts{$lock}=$env{'session.lock.'.$lock};
                    756:        }
                    757:    }
                    758:    return ($num,%texts);
                    759: }
                    760: 
                    761: sub remove_lock {
                    762:     my ($id)=@_;
                    763:     my $newlocks='';
                    764:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    765:        if (($lock=~/\w/) && ($lock ne $id)) {
                    766:           $newlocks.=','.$lock;
                    767:        }
                    768:     }
                    769:     &appenv({'session.locks' => $newlocks});
                    770:     &delenv('session.lock.'.$id);
                    771: }
                    772: 
                    773: sub remove_all_locks {
                    774:     my $activelocks=$env{'session.locks'};
                    775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    776:        if ($lock=~/\w/) {
                    777:           &remove_lock($lock);
                    778:        }
                    779:     }
                    780: }
                    781: 
                    782: 
1.369     albertel  783: # ------------------------------------------ Find out current server userload
                    784: sub userload {
                    785:     my $numusers=0;
                    786:     {
                    787: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    788: 	my $filename;
                    789: 	my $curtime=time;
                    790: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  791: 	    next if ($filename eq '.' || $filename eq '..');
                    792: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  793: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  794: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  795: 	}
                    796: 	closedir(LONIDS);
                    797:     }
                    798:     my $userloadpercent=0;
                    799:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    800:     if ($maxuserload) {
1.371     albertel  801: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  802:     }
1.372     albertel  803:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  804:     return $userloadpercent;
1.283     www       805: }
                    806: 
1.1       albertel  807: # ------------------------------ Find server with least workload from spare.tab
1.11      www       808: 
1.1       albertel  809: sub spareserver {
1.1083    raeburn   810:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  811:     my $spare_server;
1.370     albertel  812:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  813:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    814:                                                      :  $userloadpercent;
1.1083    raeburn   815:     my ($uint_dom,$remotesessions);
                    816:     if (($udom ne '') && (&domain($udom) ne '')) {
                    817:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    818:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    819:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    820:         $remotesessions = $udomdefaults{'remotesessions'};
                    821:     }
1.1123    raeburn   822:     my $spareshash = &this_host_spares($udom);
                    823:     if (ref($spareshash) eq 'HASH') {
                    824:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    825:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    826:                 if ($uint_dom) {
                    827:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    828:                                                  $try_server));
                    829:                 }
                    830: 	        ($spare_server, $lowest_load) =
                    831: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    832:             }
1.1083    raeburn   833:         }
1.784     albertel  834: 
1.1123    raeburn   835:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    836: 
                    837:         if (!$found_server) {
                    838:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    839: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    840:                     if ($uint_dom) {
                    841:                         next unless (&spare_can_host($udom,$uint_dom,
                    842:                                                      $remotesessions,$try_server));
                    843:                     }
                    844: 	            ($spare_server, $lowest_load) =
                    845: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    846:                 }
                    847: 	    }
                    848:         }
1.784     albertel  849:     }
                    850: 
                    851:     if (!$want_server_name) {
1.968     raeburn   852:         my $protocol = 'http';
                    853:         if ($protocol{$spare_server} eq 'https') {
                    854:             $protocol = $protocol{$spare_server};
                    855:         }
1.1001    raeburn   856:         if (defined($spare_server)) {
                    857:             my $hostname = &hostname($spare_server);
1.1083    raeburn   858:             if (defined($hostname)) {
1.1001    raeburn   859: 	        $spare_server = $protocol.'://'.$hostname;
                    860:             }
                    861:         }
1.784     albertel  862:     }
                    863:     return $spare_server;
                    864: }
                    865: 
                    866: sub compare_server_load {
                    867:     my ($try_server, $spare_server, $lowest_load) = @_;
                    868: 
                    869:     my $loadans     = &reply('load',    $try_server);
                    870:     my $userloadans = &reply('userload',$try_server);
                    871: 
                    872:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   873: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  874:     }
                    875: 
                    876:     my $load;
                    877:     if ($loadans =~ /\d/) {
                    878: 	if ($userloadans =~ /\d/) {
                    879: 	    #both are numbers, pick the bigger one
                    880: 	    $load = ($loadans > $userloadans) ? $loadans 
                    881: 		                              : $userloadans;
1.411     albertel  882: 	} else {
1.784     albertel  883: 	    $load = $loadans;
1.411     albertel  884: 	}
1.784     albertel  885:     } else {
                    886: 	$load = $userloadans;
                    887:     }
                    888: 
                    889:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    890: 	$spare_server = $try_server;
                    891: 	$lowest_load  = $load;
1.370     albertel  892:     }
1.784     albertel  893:     return ($spare_server,$lowest_load);
1.202     matthew   894: }
1.914     albertel  895: 
                    896: # --------------------------- ask offload servers if user already has a session
                    897: sub find_existing_session {
                    898:     my ($udom,$uname) = @_;
1.1123    raeburn   899:     my $spareshash = &this_host_spares($udom);
                    900:     if (ref($spareshash) eq 'HASH') {
                    901:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    902:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    903:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    904:             }
                    905:         }
                    906:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    907:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    908:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    909:             }
                    910:         }
1.914     albertel  911:     }
                    912:     return;
                    913: }
                    914: 
                    915: # -------------------------------- ask if server already has a session for user
                    916: sub has_user_session {
                    917:     my ($lonid,$udom,$uname) = @_;
                    918:     my $result = &reply(join(':','userhassession',
                    919: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    920:     return 1 if ($result eq 'ok');
                    921: 
                    922:     return 0;
                    923: }
                    924: 
1.1076    raeburn   925: # --------- determine least loaded server in a user's domain which allows login
                    926: 
                    927: sub choose_server {
1.1115    raeburn   928:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   929:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   930:     my %servers = &get_servers($udom);
1.1076    raeburn   931:     my $lowest_load = 30000;
1.1116    raeburn   932:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   933:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   934:         my $loginvia;
                    935:         if ($checkloginvia) {
                    936:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   937:             if ($loginvia) {
                    938:                 my ($server,$path) = split(/:/,$loginvia);
                    939:                 ($login_host, $lowest_load) =
                    940:                     &compare_server_load($server, $login_host, $lowest_load);
                    941:                 if ($login_host eq $server) {
                    942:                     $portal_path = $path;
                    943:                 }
                    944:             } else {
                    945:                 ($login_host, $lowest_load) =
                    946:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    947:                 if ($login_host eq $lonhost) {
                    948:                     $portal_path = '';
                    949:                 }
                    950:             }
                    951:         } else {
1.1076    raeburn   952:             ($login_host, $lowest_load) =
1.1116    raeburn   953:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   954:         }
                    955:     }
                    956:     if ($login_host ne '') {
1.1116    raeburn   957:         $hostname = &hostname($login_host);
1.1076    raeburn   958:     }
1.1116    raeburn   959:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   960: }
                    961: 
1.202     matthew   962: # --------------------------------------------- Try to change a user's password
                    963: 
                    964: sub changepass {
1.799     raeburn   965:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   966:     $currentpass = &escape($currentpass);
                    967:     $newpass     = &escape($newpass);
1.1030    raeburn   968:     my $lonhost = $perlvar{'lonHostID'};
                    969:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   970: 		       $server);
                    971:     if (! $answer) {
                    972: 	&logthis("No reply on password change request to $server ".
                    973: 		 "by $uname in domain $udom.");
                    974:     } elsif ($answer =~ "^ok") {
                    975:         &logthis("$uname in $udom successfully changed their password ".
                    976: 		 "on $server.");
                    977:     } elsif ($answer =~ "^pwchange_failure") {
                    978: 	&logthis("$uname in $udom was unable to change their password ".
                    979: 		 "on $server.  The action was blocked by either lcpasswd ".
                    980: 		 "or pwchange");
                    981:     } elsif ($answer =~ "^non_authorized") {
                    982:         &logthis("$uname in $udom did not get their password correct when ".
                    983: 		 "attempting to change it on $server.");
                    984:     } elsif ($answer =~ "^auth_mode_error") {
                    985:         &logthis("$uname in $udom attempted to change their password despite ".
                    986: 		 "not being locally or internally authenticated on $server.");
                    987:     } elsif ($answer =~ "^unknown_user") {
                    988:         &logthis("$uname in $udom attempted to change their password ".
                    989: 		 "on $server but were unable to because $server is not ".
                    990: 		 "their home server.");
                    991:     } elsif ($answer =~ "^refused") {
                    992: 	&logthis("$server refused to change $uname in $udom password because ".
                    993: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   994:     } elsif ($answer =~ "invalid_client") {
                    995:         &logthis("$server refused to change $uname in $udom password because ".
                    996:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   997:     }
                    998:     return $answer;
1.1       albertel  999: }
                   1000: 
1.169     harris41 1001: # ----------------------- Try to determine user's current authentication scheme
                   1002: 
                   1003: sub queryauthenticate {
                   1004:     my ($uname,$udom)=@_;
1.456     albertel 1005:     my $uhome=&homeserver($uname,$udom);
                   1006:     if (!$uhome) {
                   1007: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1008: 	return 'no_host';
                   1009:     }
                   1010:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1011:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1012: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1013:     }
1.456     albertel 1014:     return $answer;
1.169     harris41 1015: }
                   1016: 
1.1       albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1018: 
1.1       albertel 1019: sub authenticate {
1.1073    raeburn  1020:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1021:     $upass=&escape($upass);
                   1022:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1023:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1024:     my $newhome;
1.836     www      1025:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1026: # Maybe the machine was offline and only re-appeared again recently?
                   1027:         &reconlonc();
                   1028: # One more
1.952     raeburn  1029: 	$uhome=&homeserver($uname,$udom,1);
                   1030:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1031:             if (defined(&domain($udom,'primary'))) {
                   1032:                 $newhome=&domain($udom,'primary');
                   1033:             }
                   1034:             if ($newhome ne '') {
                   1035:                 $uhome = $newhome;
                   1036:             }
                   1037:         }
1.836     www      1038: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1039: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1040: 	    return 'no_host';
                   1041:         }
1.1       albertel 1042:     }
1.1073    raeburn  1043:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1044:     if ($answer eq 'authorized') {
1.952     raeburn  1045:         if ($newhome) {
                   1046:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1047:             return 'no_account_on_host'; 
                   1048:         } else {
                   1049:             &logthis("User $uname at $udom authorized by $uhome");
                   1050:             return $uhome;
                   1051:         }
1.471     albertel 1052:     }
                   1053:     if ($answer eq 'non_authorized') {
                   1054: 	&logthis("User $uname at $udom rejected by $uhome");
                   1055: 	return 'no_host'; 
1.9       www      1056:     }
1.471     albertel 1057:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1058:     return 'no_host';
                   1059: }
                   1060: 
1.1073    raeburn  1061: sub can_host_session {
1.1074    raeburn  1062:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1063:     my $canhost = 1;
1.1074    raeburn  1064:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1065:     if (ref($remotesessions) eq 'HASH') {
                   1066:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1067:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1068:                 $canhost = 0;
                   1069:             } else {
                   1070:                 $canhost = 1;
                   1071:             }
                   1072:         }
                   1073:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1074:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1075:                 $canhost = 1;
                   1076:             } else {
                   1077:                 $canhost = 0;
                   1078:             }
                   1079:         }
                   1080:         if ($canhost) {
                   1081:             if ($remotesessions->{'version'} ne '') {
                   1082:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1083:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1084:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1085:                         my $major = $1;
                   1086:                         my $minor = $2;
                   1087:                         if (($major < $reqmajor ) ||
                   1088:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1089:                             $canhost = 0;
                   1090:                         }
                   1091:                     } else {
                   1092:                         $canhost = 0;
                   1093:                     }
                   1094:                 }
                   1095:             }
                   1096:         }
                   1097:     }
                   1098:     if ($canhost) {
                   1099:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1100:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1101:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1102:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1103:                 if (($uint_dom ne '') && 
                   1104:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1105:                     $canhost = 0;
                   1106:                 } else {
                   1107:                     $canhost = 1;
                   1108:                 }
                   1109:             }
                   1110:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1111:                 if (($uint_dom ne '') && 
                   1112:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1113:                     $canhost = 1;
                   1114:                 } else {
                   1115:                     $canhost = 0;
                   1116:                 }
                   1117:             }
                   1118:         }
                   1119:     }
                   1120:     return $canhost;
                   1121: }
                   1122: 
1.1083    raeburn  1123: sub spare_can_host {
                   1124:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1125:     my $canhost=1;
                   1126:     my @intdoms;
                   1127:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1128:     if (ref($internet_names) eq 'ARRAY') {
                   1129:         @intdoms = @{$internet_names};
                   1130:     }
                   1131:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1132:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1133:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1134:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1135:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1136:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1137:                                      $remotesessions,
                   1138:                                      $defdomdefaults{'hostedsessions'});
                   1139:     }
                   1140:     return $canhost;
                   1141: }
                   1142: 
1.1123    raeburn  1143: sub this_host_spares {
                   1144:     my ($dom) = @_;
1.1126  ! raeburn  1145:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1146:     my @hosts = &current_machine_ids();
                   1147:     foreach my $lonhost (@hosts) {
                   1148:         if (&host_domain($lonhost) eq $dom) {
1.1126  ! raeburn  1149:             $dom_in_use = $dom;
        !          1150:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1151:             last;
                   1152:         }
                   1153:     }
1.1126  ! raeburn  1154:     if ($dom_in_use ne '') {
        !          1155:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
        !          1156:     }
        !          1157:     if (ref($result) ne 'HASH') {
        !          1158:         $lonhost_in_use = $perlvar{'lonHostID'};
        !          1159:         $dom_in_use = &host_domain($lonhost_in_use);
        !          1160:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
        !          1161:         if (ref($result) ne 'HASH') {
        !          1162:             $result = \%spareid;
        !          1163:         }
        !          1164:     }
        !          1165:     return $result;
        !          1166: }
        !          1167: 
        !          1168: sub spares_for_offload  {
        !          1169:     my ($dom_in_use,$lonhost_in_use) = @_;
        !          1170:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1171:     if (defined($cached)) {
                   1172:         return $result;
                   1173:     } else {
1.1126  ! raeburn  1174:         my $cachetime = 60*60*24;
        !          1175:         my %domconfig =
        !          1176:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
        !          1177:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
        !          1178:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
        !          1179:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
        !          1180:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1181:                 }
                   1182:             }
                   1183:         }
                   1184:     }
1.1126  ! raeburn  1185:     return;
1.1123    raeburn  1186: }
                   1187: 
1.1       albertel 1188: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1189: 
1.599     albertel 1190: my %homecache;
1.1       albertel 1191: sub homeserver {
1.230     stredwic 1192:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1193:     my $index="$uname:$udom";
1.426     albertel 1194: 
1.599     albertel 1195:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1196: 
                   1197:     my %servers = &get_servers($udom,'library');
                   1198:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1199:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1200: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1201: 
                   1202: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1203: 	if ($answer eq 'found') {
                   1204: 	    delete($badServerCache{$tryserver}); 
                   1205: 	    return $homecache{$index}=$tryserver;
                   1206: 	} elsif ($answer eq 'no_host') {
                   1207: 	    $badServerCache{$tryserver}=1;
                   1208: 	}
1.1       albertel 1209:     }    
                   1210:     return 'no_host';
1.70      www      1211: }
                   1212: 
                   1213: # ------------------------------------- Find the usernames behind a list of IDs
                   1214: 
                   1215: sub idget {
                   1216:     my ($udom,@ids)=@_;
                   1217:     my %returnhash=();
                   1218:     
1.841     albertel 1219:     my %servers = &get_servers($udom,'library');
                   1220:     foreach my $tryserver (keys(%servers)) {
                   1221: 	my $idlist=join('&',@ids);
                   1222: 	$idlist=~tr/A-Z/a-z/; 
                   1223: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1224: 	my @answer=();
                   1225: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1226: 	    @answer=split(/\&/,$reply);
                   1227: 	}                    ;
                   1228: 	my $i;
                   1229: 	for ($i=0;$i<=$#ids;$i++) {
                   1230: 	    if ($answer[$i]) {
                   1231: 		$returnhash{$ids[$i]}=$answer[$i];
                   1232: 	    } 
                   1233: 	}
                   1234:     } 
1.70      www      1235:     return %returnhash;
                   1236: }
                   1237: 
                   1238: # ------------------------------------- Find the IDs behind a list of usernames
                   1239: 
                   1240: sub idrget {
                   1241:     my ($udom,@unames)=@_;
                   1242:     my %returnhash=();
1.800     albertel 1243:     foreach my $uname (@unames) {
                   1244:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1245:     }
1.70      www      1246:     return %returnhash;
                   1247: }
                   1248: 
                   1249: # ------------------------------- Store away a list of names and associated IDs
                   1250: 
                   1251: sub idput {
                   1252:     my ($udom,%ids)=@_;
                   1253:     my %servers=();
1.800     albertel 1254:     foreach my $uname (keys(%ids)) {
                   1255: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1256:         my $uhom=&homeserver($uname,$udom);
1.70      www      1257:         if ($uhom ne 'no_host') {
1.800     albertel 1258:             my $id=&escape($ids{$uname});
1.70      www      1259:             $id=~tr/A-Z/a-z/;
1.800     albertel 1260:             my $esc_unam=&escape($uname);
1.70      www      1261: 	    if ($servers{$uhom}) {
1.800     albertel 1262: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1263:             } else {
1.800     albertel 1264:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1265:             }
                   1266:         }
1.191     harris41 1267:     }
1.800     albertel 1268:     foreach my $server (keys(%servers)) {
                   1269:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1270:     }
1.344     www      1271: }
                   1272: 
1.1023    raeburn  1273: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1274: sub dump_dom {
1.1023    raeburn  1275:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1276:     if (!$udom) {
                   1277:         $udom=$env{'user.domain'};
                   1278:     }
                   1279:     my %returnhash;
1.1023    raeburn  1280:     if ($udom) {
                   1281:         my $uname = &get_domainconfiguser($udom);
                   1282:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1283:     }
                   1284:     return %returnhash;
                   1285: }
                   1286: 
1.1023    raeburn  1287: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1288: 
                   1289: sub get_dom {
1.860     raeburn  1290:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1291:     my $items='';
                   1292:     foreach my $item (@$storearr) {
                   1293:         $items.=&escape($item).'&';
                   1294:     }
                   1295:     $items=~s/\&$//;
1.860     raeburn  1296:     if (!$udom) {
                   1297:         $udom=$env{'user.domain'};
                   1298:         if (defined(&domain($udom,'primary'))) {
                   1299:             $uhome=&domain($udom,'primary');
                   1300:         } else {
1.874     albertel 1301:             undef($uhome);
1.860     raeburn  1302:         }
                   1303:     } else {
                   1304:         if (!$uhome) {
                   1305:             if (defined(&domain($udom,'primary'))) {
                   1306:                 $uhome=&domain($udom,'primary');
                   1307:             }
                   1308:         }
                   1309:     }
                   1310:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1311:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1312:         my %returnhash;
1.875     albertel 1313:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1314:             return %returnhash;
                   1315:         }
1.806     raeburn  1316:         my @pairs=split(/\&/,$rep);
                   1317:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1318:             return @pairs;
                   1319:         }
                   1320:         my $i=0;
                   1321:         foreach my $item (@$storearr) {
                   1322:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1323:             $i++;
                   1324:         }
                   1325:         return %returnhash;
                   1326:     } else {
1.880     banghart 1327:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1328:     }
                   1329: }
                   1330: 
                   1331: # -------------------------------------------- put items in domain db files 
                   1332: 
                   1333: sub put_dom {
1.860     raeburn  1334:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1335:     if (!$udom) {
                   1336:         $udom=$env{'user.domain'};
                   1337:         if (defined(&domain($udom,'primary'))) {
                   1338:             $uhome=&domain($udom,'primary');
                   1339:         } else {
1.874     albertel 1340:             undef($uhome);
1.860     raeburn  1341:         }
                   1342:     } else {
                   1343:         if (!$uhome) {
                   1344:             if (defined(&domain($udom,'primary'))) {
                   1345:                 $uhome=&domain($udom,'primary');
                   1346:             }
                   1347:         }
                   1348:     } 
                   1349:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1350:         my $items='';
                   1351:         foreach my $item (keys(%$storehash)) {
                   1352:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1353:         }
                   1354:         $items=~s/\&$//;
                   1355:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1356:     } else {
1.860     raeburn  1357:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1358:     }
                   1359: }
                   1360: 
1.1023    raeburn  1361: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1362: sub newput_dom {
1.1023    raeburn  1363:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1364:     my $result;
                   1365:     if (!$udom) {
                   1366:         $udom=$env{'user.domain'};
                   1367:     }
1.1023    raeburn  1368:     if ($udom) {
                   1369:         my $uname = &get_domainconfiguser($udom);
                   1370:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1371:     }
                   1372:     return $result;
                   1373: }
                   1374: 
1.1023    raeburn  1375: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1376: sub del_dom {
1.1023    raeburn  1377:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1378:     if (ref($storearr) eq 'ARRAY') {
                   1379:         if (!$udom) {
                   1380:             $udom=$env{'user.domain'};
                   1381:         }
1.1023    raeburn  1382:         if ($udom) {
                   1383:             my $uname = &get_domainconfiguser($udom); 
                   1384:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1385:         }
                   1386:     }
                   1387: }
                   1388: 
1.1023    raeburn  1389: # ----------------------------------construct domainconfig user for a domain 
                   1390: sub get_domainconfiguser {
                   1391:     my ($udom) = @_;
                   1392:     return $udom.'-domainconfig';
                   1393: }
                   1394: 
1.837     raeburn  1395: sub retrieve_inst_usertypes {
                   1396:     my ($udom) = @_;
                   1397:     my (%returnhash,@order);
1.989     raeburn  1398:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1399:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1400:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1401:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1402:         @order = @{$domdefs{'inststatusorder'}};
                   1403:     } else {
                   1404:         if (defined(&domain($udom,'primary'))) {
                   1405:             my $uhome=&domain($udom,'primary');
                   1406:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1407:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1408:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1409:                 return (\%returnhash,\@order);
                   1410:             }
                   1411:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1412:             my @pairs=split(/\&/,$hashitems);
                   1413:             foreach my $item (@pairs) {
                   1414:                 my ($key,$value)=split(/=/,$item,2);
                   1415:                 $key = &unescape($key);
                   1416:                 next if ($key =~ /^error: 2 /);
                   1417:                 $returnhash{$key}=&thaw_unescape($value);
                   1418:             }
                   1419:             my @esc_order = split(/\&/,$orderitems);
                   1420:             foreach my $item (@esc_order) {
                   1421:                 push(@order,&unescape($item));
                   1422:             }
                   1423:         } else {
                   1424:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1425:         }
                   1426:     }
                   1427:     return (\%returnhash,\@order);
                   1428: }
                   1429: 
1.868     raeburn  1430: sub is_domainimage {
                   1431:     my ($url) = @_;
                   1432:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1433:         if (&domain($1) ne '') {
                   1434:             return '1';
                   1435:         }
                   1436:     }
                   1437:     return;
                   1438: }
                   1439: 
1.899     raeburn  1440: sub inst_directory_query {
                   1441:     my ($srch) = @_;
                   1442:     my $udom = $srch->{'srchdomain'};
                   1443:     my %results;
                   1444:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1445:     my $outcome;
1.899     raeburn  1446:     if ($homeserver ne '') {
1.904     albertel 1447: 	my $queryid=&reply("querysend:instdirsearch:".
                   1448: 			   &escape($srch->{'srchby'}).':'.
                   1449: 			   &escape($srch->{'srchterm'}).':'.
                   1450: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1451: 	my $host=&hostname($homeserver);
                   1452: 	if ($queryid !~/^\Q$host\E\_/) {
                   1453: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1454: 	    return;
                   1455: 	}
                   1456: 	my $response = &get_query_reply($queryid);
                   1457: 	my $maxtries = 5;
                   1458: 	my $tries = 1;
                   1459: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1460: 	    $response = &get_query_reply($queryid);
                   1461: 	    $tries ++;
                   1462: 	}
                   1463: 
                   1464:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1465:             if ($response eq 'unavailable') {
                   1466:                 $outcome = $response;
                   1467:             } else {
                   1468:                 $outcome = 'ok';
                   1469:                 my @matches = split(/\n/,$response);
                   1470:                 foreach my $match (@matches) {
                   1471:                     my ($key,$value) = split(/=/,$match);
                   1472:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1473:                 }
1.899     raeburn  1474:             }
                   1475:         }
                   1476:     }
1.909     raeburn  1477:     return ($outcome,%results);
1.899     raeburn  1478: }
                   1479: 
                   1480: sub usersearch {
                   1481:     my ($srch) = @_;
                   1482:     my $dom = $srch->{'srchdomain'};
                   1483:     my %results;
                   1484:     my %libserv = &all_library();
                   1485:     my $query = 'usersearch';
                   1486:     foreach my $tryserver (keys(%libserv)) {
                   1487:         if (&host_domain($tryserver) eq $dom) {
                   1488:             my $host=&hostname($tryserver);
                   1489:             my $queryid=
1.911     raeburn  1490:                 &reply("querysend:".&escape($query).':'.
                   1491:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1492:                        &escape($srch->{'srchtype'}).':'.
                   1493:                        &escape($srch->{'srchterm'}),$tryserver);
                   1494:             if ($queryid !~/^\Q$host\E\_/) {
                   1495:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1496:                 next;
1.899     raeburn  1497:             }
                   1498:             my $reply = &get_query_reply($queryid);
                   1499:             my $maxtries = 1;
                   1500:             my $tries = 1;
                   1501:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1502:                 $reply = &get_query_reply($queryid);
                   1503:                 $tries ++;
                   1504:             }
                   1505:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1506:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1507:             } else {
1.911     raeburn  1508:                 my @matches;
                   1509:                 if ($reply =~ /\n/) {
                   1510:                     @matches = split(/\n/,$reply);
                   1511:                 } else {
                   1512:                     @matches = split(/\&/,$reply);
                   1513:                 }
1.899     raeburn  1514:                 foreach my $match (@matches) {
                   1515:                     my ($uname,$udom,%userhash);
1.911     raeburn  1516:                     foreach my $entry (split(/:/,$match)) {
                   1517:                         my ($key,$value) =
                   1518:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1519:                         $userhash{$key} = $value;
                   1520:                         if ($key eq 'username') {
                   1521:                             $uname = $value;
                   1522:                         } elsif ($key eq 'domain') {
                   1523:                             $udom = $value;
1.911     raeburn  1524:                         }
1.899     raeburn  1525:                     }
                   1526:                     $results{$uname.':'.$udom} = \%userhash;
                   1527:                 }
                   1528:             }
                   1529:         }
                   1530:     }
                   1531:     return %results;
                   1532: }
                   1533: 
1.912     raeburn  1534: sub get_instuser {
                   1535:     my ($udom,$uname,$id) = @_;
                   1536:     my $homeserver = &domain($udom,'primary');
                   1537:     my ($outcome,%results);
                   1538:     if ($homeserver ne '') {
                   1539:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1540:                            &escape($id).':'.&escape($udom),$homeserver);
                   1541:         my $host=&hostname($homeserver);
                   1542:         if ($queryid !~/^\Q$host\E\_/) {
                   1543:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1544:             return;
                   1545:         }
                   1546:         my $response = &get_query_reply($queryid);
                   1547:         my $maxtries = 5;
                   1548:         my $tries = 1;
                   1549:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1550:             $response = &get_query_reply($queryid);
                   1551:             $tries ++;
                   1552:         }
                   1553:         if (!&error($response) && $response ne 'refused') {
                   1554:             if ($response eq 'unavailable') {
                   1555:                 $outcome = $response;
                   1556:             } else {
                   1557:                 $outcome = 'ok';
                   1558:                 my @matches = split(/\n/,$response);
                   1559:                 foreach my $match (@matches) {
                   1560:                     my ($key,$value) = split(/=/,$match);
                   1561:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1562:                 }
                   1563:             }
                   1564:         }
                   1565:     }
                   1566:     my %userinfo;
                   1567:     if (ref($results{$uname}) eq 'HASH') {
                   1568:         %userinfo = %{$results{$uname}};
                   1569:     } 
                   1570:     return ($outcome,%userinfo);
                   1571: }
                   1572: 
                   1573: sub inst_rulecheck {
1.923     raeburn  1574:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1575:     my %returnhash;
                   1576:     if ($udom ne '') {
                   1577:         if (ref($rules) eq 'ARRAY') {
                   1578:             @{$rules} = map {&escape($_);} (@{$rules});
                   1579:             my $rulestr = join(':',@{$rules});
                   1580:             my $homeserver=&domain($udom,'primary');
                   1581:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1582:                 my $response;
                   1583:                 if ($item eq 'username') {                
                   1584:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1585:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1586:                                               $homeserver));
1.923     raeburn  1587:                 } elsif ($item eq 'id') {
                   1588:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1589:                                               ':'.&escape($id).':'.$rulestr,
                   1590:                                               $homeserver));
1.945     raeburn  1591:                 } elsif ($item eq 'selfcreate') {
                   1592:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1593:                                                &escape($udom).':'.&escape($uname).
                   1594:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1595:                 }
1.912     raeburn  1596:                 if ($response ne 'refused') {
                   1597:                     my @pairs=split(/\&/,$response);
                   1598:                     foreach my $item (@pairs) {
                   1599:                         my ($key,$value)=split(/=/,$item,2);
                   1600:                         $key = &unescape($key);
                   1601:                         next if ($key =~ /^error: 2 /);
                   1602:                         $returnhash{$key}=&thaw_unescape($value);
                   1603:                     }
                   1604:                 }
                   1605:             }
                   1606:         }
                   1607:     }
                   1608:     return %returnhash;
                   1609: }
                   1610: 
                   1611: sub inst_userrules {
1.923     raeburn  1612:     my ($udom,$check) = @_;
1.912     raeburn  1613:     my (%ruleshash,@ruleorder);
                   1614:     if ($udom ne '') {
                   1615:         my $homeserver=&domain($udom,'primary');
                   1616:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1617:             my $response;
                   1618:             if ($check eq 'id') {
                   1619:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1620:                                  $homeserver);
1.943     raeburn  1621:             } elsif ($check eq 'email') {
                   1622:                 $response=&reply('instemailrules:'.&escape($udom),
                   1623:                                  $homeserver);
1.923     raeburn  1624:             } else {
                   1625:                 $response=&reply('instuserrules:'.&escape($udom),
                   1626:                                  $homeserver);
                   1627:             }
1.912     raeburn  1628:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1629:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1630:                 ($response ne 'no_such_host')) {
                   1631:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1632:                 my @pairs=split(/\&/,$hashitems);
                   1633:                 foreach my $item (@pairs) {
                   1634:                     my ($key,$value)=split(/=/,$item,2);
                   1635:                     $key = &unescape($key);
                   1636:                     next if ($key =~ /^error: 2 /);
                   1637:                     $ruleshash{$key}=&thaw_unescape($value);
                   1638:                 }
                   1639:                 my @esc_order = split(/\&/,$orderitems);
                   1640:                 foreach my $item (@esc_order) {
                   1641:                     push(@ruleorder,&unescape($item));
                   1642:                 }
                   1643:             }
                   1644:         }
                   1645:     }
                   1646:     return (\%ruleshash,\@ruleorder);
                   1647: }
                   1648: 
1.976     raeburn  1649: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1650: 
                   1651: sub get_domain_defaults {
                   1652:     my ($domain) = @_;
                   1653:     my $cachetime = 60*60*24;
                   1654:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1655:     if (defined($cached)) {
                   1656:         if (ref($result) eq 'HASH') {
                   1657:             return %{$result};
                   1658:         }
                   1659:     }
                   1660:     my %domdefaults;
                   1661:     my %domconfig =
1.989     raeburn  1662:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1663:                                   'requestcourses','inststatus',
1.1073    raeburn  1664:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1665:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1666:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1667:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1668:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1669:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1670:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1671:     } else {
                   1672:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1673:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1674:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1675:     }
1.976     raeburn  1676:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1677:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1678:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1679:         } else {
                   1680:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1681:         } 
                   1682:         my @usertools = ('aboutme','blog','portfolio');
                   1683:         foreach my $item (@usertools) {
                   1684:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1685:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1686:             }
                   1687:         }
                   1688:     }
1.985     raeburn  1689:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1690:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1691:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1692:         }
                   1693:     }
1.989     raeburn  1694:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1695:         foreach my $item ('inststatustypes','inststatusorder') {
                   1696:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1697:         }
                   1698:     }
1.1047    raeburn  1699:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1700:         foreach my $item ('canuse_pdfforms') {
                   1701:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1702:         }
                   1703:     }
1.1073    raeburn  1704:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1705:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1706:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1707:         }
                   1708:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1709:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1710:         }
                   1711:     }
1.943     raeburn  1712:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1713:                                   $cachetime);
                   1714:     return %domdefaults;
                   1715: }
                   1716: 
1.344     www      1717: # --------------------------------------------------- Assign a key to a student
                   1718: 
                   1719: sub assign_access_key {
1.364     www      1720: #
                   1721: # a valid key looks like uname:udom#comments
                   1722: # comments are being appended
                   1723: #
1.498     www      1724:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1725:     $kdom=
1.620     albertel 1726:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1727:     $knum=
1.620     albertel 1728:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1729:     $cdom=
1.620     albertel 1730:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1731:     $cnum=
1.620     albertel 1732:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1733:     $udom=$env{'user.name'} unless (defined($udom));
                   1734:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1735:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1736:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1737:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1738:                                                   # assigned to this person
                   1739:                                                   # - this should not happen,
1.345     www      1740:                                                   # unless something went wrong
                   1741:                                                   # the first time around
                   1742: # ready to assign
1.364     www      1743:         $logentry=$1.'; '.$logentry;
1.496     www      1744:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1745:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1746: # key now belongs to user
1.346     www      1747: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1748:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1749:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1750:                 return 'ok';
                   1751:             } else {
                   1752:                 return 
                   1753:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1754: 	    }
                   1755:         } else {
                   1756:             return 'error: Could not assign key, try again later.';
                   1757:         }
1.364     www      1758:     } elsif (!$existing{$ckey}) {
1.345     www      1759: # the key does not exist
                   1760: 	return 'error: The key does not exist';
                   1761:     } else {
                   1762: # the key is somebody else's
                   1763: 	return 'error: The key is already in use';
                   1764:     }
1.344     www      1765: }
                   1766: 
1.364     www      1767: # ------------------------------------------ put an additional comment on a key
                   1768: 
                   1769: sub comment_access_key {
                   1770: #
                   1771: # a valid key looks like uname:udom#comments
                   1772: # comments are being appended
                   1773: #
                   1774:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1775:     $cdom=
1.620     albertel 1776:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1777:     $cnum=
1.620     albertel 1778:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1779:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1780:     if ($existing{$ckey}) {
                   1781:         $existing{$ckey}.='; '.$logentry;
                   1782: # ready to assign
1.367     www      1783:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1784:                                                  $cdom,$cnum) eq 'ok') {
                   1785: 	    return 'ok';
                   1786:         } else {
                   1787: 	    return 'error: Count not store comment.';
                   1788:         }
                   1789:     } else {
                   1790: # the key does not exist
                   1791: 	return 'error: The key does not exist';
                   1792:     }
                   1793: }
                   1794: 
1.344     www      1795: # ------------------------------------------------------ Generate a set of keys
                   1796: 
                   1797: sub generate_access_keys {
1.364     www      1798:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1799:     $cdom=
1.620     albertel 1800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1801:     $cnum=
1.620     albertel 1802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1803:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1804:     unless (($cdom) && ($cnum)) { return 0; }
                   1805:     if ($number>10000) { return 0; }
                   1806:     sleep(2); # make sure don't get same seed twice
                   1807:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1808:     my $total=0;
                   1809:     for (my $i=1;$i<=$number;$i++) {
                   1810:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1811:                   sprintf("%lx",int(100000*rand)).'-'.
                   1812:                   sprintf("%lx",int(100000*rand));
                   1813:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1814:        $newkey=~s/0/h/g; # and also 0 and O
                   1815:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1816:        if ($existing{$newkey}) {
                   1817:            $i--;
                   1818:        } else {
1.364     www      1819: 	  if (&put('accesskeys',
                   1820:               { $newkey => '# generated '.localtime().
1.620     albertel 1821:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1822:                            '; '.$logentry },
                   1823: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1824:               $total++;
                   1825: 	  }
                   1826:        }
                   1827:     }
1.620     albertel 1828:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1829:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1830:     return $total;
                   1831: }
                   1832: 
                   1833: # ------------------------------------------------------- Validate an accesskey
                   1834: 
                   1835: sub validate_access_key {
                   1836:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1837:     $cdom=
1.620     albertel 1838:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1839:     $cnum=
1.620     albertel 1840:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1841:     $udom=$env{'user.domain'} unless (defined($udom));
                   1842:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1843:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1844:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1845: }
                   1846: 
                   1847: # ------------------------------------- Find the section of student in a course
1.652     albertel 1848: sub devalidate_getsection_cache {
                   1849:     my ($udom,$unam,$courseid)=@_;
                   1850:     my $hashid="$udom:$unam:$courseid";
                   1851:     &devalidate_cache_new('getsection',$hashid);
                   1852: }
1.298     matthew  1853: 
1.815     albertel 1854: sub courseid_to_courseurl {
                   1855:     my ($courseid) = @_;
                   1856:     #already url style courseid
                   1857:     return $courseid if ($courseid =~ m{^/});
                   1858: 
                   1859:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1860: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1861: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1862: 	return "/$cdom/$cnum";
                   1863:     }
                   1864: 
                   1865:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1866:     if (exists($courseinfo{'num'})) {
                   1867: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1868:     }
                   1869: 
                   1870:     return undef;
                   1871: }
                   1872: 
1.298     matthew  1873: sub getsection {
                   1874:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1875:     my $cachetime=1800;
1.551     albertel 1876: 
                   1877:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1878:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1879:     if (defined($cached)) { return $result; }
                   1880: 
1.298     matthew  1881:     my %Pending; 
                   1882:     my %Expired;
                   1883:     #
                   1884:     # Each role can either have not started yet (pending), be active, 
                   1885:     #    or have expired.
                   1886:     #
                   1887:     # If there is an active role, we are done.
                   1888:     #
                   1889:     # If there is more than one role which has not started yet, 
                   1890:     #     choose the one which will start sooner
                   1891:     # If there is one role which has not started yet, return it.
                   1892:     #
                   1893:     # If there is more than one expired role, choose the one which ended last.
                   1894:     # If there is a role which has expired, return it.
                   1895:     #
1.815     albertel 1896:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1897:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1898:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1899:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1900:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1901:         my $section=$1;
                   1902:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1903:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1904:         my $now=time;
1.548     albertel 1905:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1906:             $Expired{$end}=$section;
                   1907:             next;
                   1908:         }
1.548     albertel 1909:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1910:             $Pending{$start}=$section;
                   1911:             next;
                   1912:         }
1.599     albertel 1913:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1914:     }
                   1915:     #
                   1916:     # Presumedly there will be few matching roles from the above
                   1917:     # loop and the sorting time will be negligible.
                   1918:     if (scalar(keys(%Pending))) {
                   1919:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1920:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1921:     } 
                   1922:     if (scalar(keys(%Expired))) {
                   1923:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1924:         my $time = pop(@sorted);
1.599     albertel 1925:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1926:     }
1.599     albertel 1927:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1928: }
1.70      www      1929: 
1.599     albertel 1930: sub save_cache {
                   1931:     &purge_remembered();
1.722     albertel 1932:     #&Apache::loncommon::validate_page();
1.620     albertel 1933:     undef(%env);
1.780     albertel 1934:     undef($env_loaded);
1.599     albertel 1935: }
1.452     albertel 1936: 
1.599     albertel 1937: my $to_remember=-1;
                   1938: my %remembered;
                   1939: my %accessed;
                   1940: my $kicks=0;
                   1941: my $hits=0;
1.849     albertel 1942: sub make_key {
                   1943:     my ($name,$id) = @_;
1.872     albertel 1944:     if (length($id) > 65 
                   1945: 	&& length(&escape($id)) > 200) {
                   1946: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1947:     }
1.849     albertel 1948:     return &escape($name.':'.$id);
                   1949: }
                   1950: 
1.599     albertel 1951: sub devalidate_cache_new {
                   1952:     my ($name,$id,$debug) = @_;
                   1953:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1954:     $id=&make_key($name,$id);
1.599     albertel 1955:     $memcache->delete($id);
                   1956:     delete($remembered{$id});
                   1957:     delete($accessed{$id});
                   1958: }
                   1959: 
                   1960: sub is_cached_new {
                   1961:     my ($name,$id,$debug) = @_;
1.849     albertel 1962:     $id=&make_key($name,$id);
1.599     albertel 1963:     if (exists($remembered{$id})) {
                   1964: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1965: 	$accessed{$id}=[&gettimeofday()];
                   1966: 	$hits++;
                   1967: 	return ($remembered{$id},1);
                   1968:     }
                   1969:     my $value = $memcache->get($id);
                   1970:     if (!(defined($value))) {
                   1971: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1972: 	return (undef,undef);
1.416     albertel 1973:     }
1.599     albertel 1974:     if ($value eq '__undef__') {
                   1975: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1976: 	$value=undef;
                   1977:     }
                   1978:     &make_room($id,$value,$debug);
                   1979:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1980:     return ($value,1);
                   1981: }
                   1982: 
                   1983: sub do_cache_new {
                   1984:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1985:     $id=&make_key($name,$id);
1.599     albertel 1986:     my $setvalue=$value;
                   1987:     if (!defined($setvalue)) {
                   1988: 	$setvalue='__undef__';
                   1989:     }
1.623     albertel 1990:     if (!defined($time) ) {
                   1991: 	$time=600;
                   1992:     }
1.599     albertel 1993:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1994:     my $result = $memcache->set($id,$setvalue,$time);
                   1995:     if (! $result) {
1.872     albertel 1996: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1997: 	$memcache->disconnect_all();
1.872     albertel 1998:     }
1.600     albertel 1999:     # need to make a copy of $value
1.919     albertel 2000:     &make_room($id,$value,$debug);
1.599     albertel 2001:     return $value;
                   2002: }
                   2003: 
                   2004: sub make_room {
                   2005:     my ($id,$value,$debug)=@_;
1.919     albertel 2006: 
                   2007:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2008:                                     : $value;
1.599     albertel 2009:     if ($to_remember<0) { return; }
                   2010:     $accessed{$id}=[&gettimeofday()];
                   2011:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2012:     my $to_kick;
                   2013:     my $max_time=0;
                   2014:     foreach my $other (keys(%accessed)) {
                   2015: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2016: 	    $to_kick=$other;
                   2017: 	    $max_time=&tv_interval($accessed{$other});
                   2018: 	}
                   2019:     }
                   2020:     delete($remembered{$to_kick});
                   2021:     delete($accessed{$to_kick});
                   2022:     $kicks++;
                   2023:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2024:     return;
                   2025: }
                   2026: 
1.599     albertel 2027: sub purge_remembered {
1.604     albertel 2028:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2029:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2030:     undef(%remembered);
                   2031:     undef(%accessed);
1.428     albertel 2032: }
1.70      www      2033: # ------------------------------------- Read an entry from a user's environment
                   2034: 
                   2035: sub userenvironment {
                   2036:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2037:     my $items;
                   2038:     foreach my $item (@what) {
                   2039:         $items.=&escape($item).'&';
                   2040:     }
                   2041:     $items=~s/\&$//;
1.70      www      2042:     my %returnhash=();
1.1009    raeburn  2043:     my $uhome = &homeserver($unam,$udom);
                   2044:     unless ($uhome eq 'no_host') {
                   2045:         my @answer=split(/\&/, 
                   2046:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2047:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2048:             return %returnhash;
                   2049:         }
1.1009    raeburn  2050:         my $i;
                   2051:         for ($i=0;$i<=$#what;$i++) {
                   2052: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2053:         }
1.70      www      2054:     }
                   2055:     return %returnhash;
1.1       albertel 2056: }
                   2057: 
1.617     albertel 2058: # ---------------------------------------------------------- Get a studentphoto
                   2059: sub studentphoto {
                   2060:     my ($udom,$unam,$ext) = @_;
                   2061:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2062:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2063:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2064:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2065:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2066:             } else {
                   2067:                 my ($result,$perm_reqd)=
1.707     albertel 2068: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2069:                 if ($result eq 'ok') {
                   2070:                     if (!($perm_reqd eq 'yes')) {
                   2071:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2072:                     }
                   2073:                 }
                   2074:             }
                   2075:         }
                   2076:     } else {
                   2077:         my ($result,$perm_reqd) = 
1.707     albertel 2078: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2079:         if ($result eq 'ok') {
                   2080:             if (!($perm_reqd eq 'yes')) {
                   2081:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2082:             }
                   2083:         }
                   2084:     }
                   2085:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2086: }
                   2087: 
                   2088: sub retrievestudentphoto {
                   2089:     my ($udom,$unam,$ext,$type) = @_;
                   2090:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2091:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2092:     if ($ret eq 'ok') {
                   2093:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2094:         if ($type eq 'thumbnail') {
                   2095:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2096:         }
                   2097:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2098:         return $tokenurl;
                   2099:     } else {
                   2100:         if ($type eq 'thumbnail') {
                   2101:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2102:         } else { 
                   2103:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2104:         }
1.617     albertel 2105:     }
                   2106: }
                   2107: 
1.263     www      2108: # -------------------------------------------------------------------- New chat
                   2109: 
                   2110: sub chatsend {
1.724     raeburn  2111:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2112:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2113:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2114:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2115:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2116: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2117: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2118: }
                   2119: 
                   2120: # ------------------------------------------ Find current version of a resource
                   2121: 
                   2122: sub getversion {
                   2123:     my $fname=&clutter(shift);
                   2124:     unless ($fname=~/^\/res\//) { return -1; }
                   2125:     return &currentversion(&filelocation('',$fname));
                   2126: }
                   2127: 
                   2128: sub currentversion {
                   2129:     my $fname=shift;
                   2130:     my $author=$fname;
                   2131:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2132:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2133:     my $home=&homeserver($uname,$udom);
1.292     www      2134:     if ($home eq 'no_host') { 
                   2135:         return -1; 
                   2136:     }
1.1112    www      2137:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2138:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2139: 	return -1;
                   2140:     }
1.1112    www      2141:     return $answer;
1.263     www      2142: }
                   2143: 
1.1111    www      2144: #
                   2145: # Return special version number of resource if set by override, empty otherwise
                   2146: #
                   2147: sub usedversion {
                   2148:     my $fname=shift;
                   2149:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2150:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2151:     if ($urlversion) { return $urlversion; }
                   2152:     return '';
                   2153: }
                   2154: 
1.1       albertel 2155: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2156: 
1.1       albertel 2157: sub subscribe {
                   2158:     my $fname=shift;
1.761     raeburn  2159:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2160:     $fname=~s/[\n\r]//g;
1.1       albertel 2161:     my $author=$fname;
                   2162:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2163:     my ($udom,$uname)=split(/\//,$author);
                   2164:     my $home=homeserver($uname,$udom);
1.335     albertel 2165:     if ($home eq 'no_host') {
                   2166:         return 'not_found';
1.1       albertel 2167:     }
                   2168:     my $answer=reply("sub:$fname",$home);
1.64      www      2169:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2170: 	$answer.=' by '.$home;
                   2171:     }
1.1       albertel 2172:     return $answer;
                   2173: }
                   2174:     
1.8       www      2175: # -------------------------------------------------------------- Replicate file
                   2176: 
                   2177: sub repcopy {
                   2178:     my $filename=shift;
1.23      www      2179:     $filename=~s/\/+/\//g;
1.607     raeburn  2180:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2181:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2182:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2183: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2184: 	return &repcopy_userfile($filename);
                   2185:     }
1.532     albertel 2186:     $filename=~s/[\n\r]//g;
1.8       www      2187:     my $transname="$filename.in.transfer";
1.828     www      2188: # FIXME: this should flock
1.607     raeburn  2189:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2190:     my $remoteurl=subscribe($filename);
1.64      www      2191:     if ($remoteurl =~ /^con_lost by/) {
                   2192: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2193:            return 'unavailable';
1.8       www      2194:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2195: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2196: 	   return 'not_found';
1.64      www      2197:     } elsif ($remoteurl =~ /^rejected by/) {
                   2198: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2199:            return 'forbidden';
1.20      www      2200:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2201:            return 'ok';
1.8       www      2202:     } else {
1.290     www      2203:         my $author=$filename;
                   2204:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2205:         my ($udom,$uname)=split(/\//,$author);
                   2206:         my $home=homeserver($uname,$udom);
                   2207:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2208:            my @parts=split(/\//,$filename);
                   2209:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2210:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2211:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2212: 	       return 'bad_request';
1.8       www      2213:            }
                   2214:            my $count;
                   2215:            for ($count=5;$count<$#parts;$count++) {
                   2216:                $path.="/$parts[$count]";
                   2217:                if ((-e $path)!=1) {
                   2218: 		   mkdir($path,0777);
                   2219:                }
                   2220:            }
                   2221:            my $ua=new LWP::UserAgent;
                   2222:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2223:            my $response=$ua->request($request,$transname);
                   2224:            if ($response->is_error()) {
                   2225: 	       unlink($transname);
                   2226:                my $message=$response->status_line;
1.672     albertel 2227:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2228:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2229:                return 'unavailable';
1.8       www      2230:            } else {
1.16      www      2231: 	       if ($remoteurl!~/\.meta$/) {
                   2232:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2233:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2234:                   if ($mresponse->is_error()) {
                   2235: 		      unlink($filename.'.meta');
                   2236:                       &logthis(
1.672     albertel 2237:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2238:                   }
                   2239: 	       }
1.8       www      2240:                rename($transname,$filename);
1.607     raeburn  2241:                return 'ok';
1.8       www      2242:            }
1.290     www      2243:        }
1.8       www      2244:     }
1.330     www      2245: }
                   2246: 
                   2247: # ------------------------------------------------ Get server side include body
                   2248: sub ssi_body {
1.381     albertel 2249:     my ($filelink,%form)=@_;
1.606     matthew  2250:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2251:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2252:     }
1.953     www      2253:     my $output='';
                   2254:     my $response;
1.980     raeburn  2255:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2256:        ($output,$response)=&externalssi($filelink);
1.953     www      2257:     } else {
1.1004    droeschl 2258:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2259:        $filelink .= 'inhibitmenu=yes';
1.953     www      2260:        ($output,$response)=&ssi($filelink,%form);
                   2261:     }
1.778     albertel 2262:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2263:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2264:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2265:     if (wantarray) {
                   2266:         return ($output, $response);
                   2267:     } else {
                   2268:         return $output;
                   2269:     }
1.8       www      2270: }
                   2271: 
1.15      www      2272: # --------------------------------------------------------- Server Side Include
                   2273: 
1.782     albertel 2274: sub absolute_url {
                   2275:     my ($host_name) = @_;
                   2276:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2277:     if ($host_name eq '') {
                   2278: 	$host_name = $ENV{'SERVER_NAME'};
                   2279:     }
                   2280:     return $protocol.$host_name;
                   2281: }
                   2282: 
1.942     foxr     2283: #
                   2284: #   Server side include.
                   2285: # Parameters:
                   2286: #  fn     Possibly encrypted resource name/id.
                   2287: #  form   Hash that describes how the rendering should be done
                   2288: #         and other things.
1.944     foxr     2289: # Returns:
1.950     raeburn  2290: #   Scalar context: The content of the response.
                   2291: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2292: #     
1.15      www      2293: sub ssi {
                   2294: 
1.944     foxr     2295:     my ($fn,%form)=@_;
1.15      www      2296:     my $ua=new LWP::UserAgent;
1.23      www      2297:     my $request;
1.711     albertel 2298: 
                   2299:     $form{'no_update_last_known'}=1;
1.895     albertel 2300:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2301:     if (%form) {
1.782     albertel 2302:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2303:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2304:     } else {
1.782     albertel 2305:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2306:     }
                   2307: 
1.15      www      2308:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2309:     my $response=$ua->request($request);
                   2310: 
1.944     foxr     2311:     if (wantarray) {
                   2312: 	return ($response->content, $response);
                   2313:     } else {
                   2314: 	return $response->content;
1.942     foxr     2315:     }
1.324     www      2316: }
                   2317: 
                   2318: sub externalssi {
                   2319:     my ($url)=@_;
                   2320:     my $ua=new LWP::UserAgent;
                   2321:     my $request=new HTTP::Request('GET',$url);
                   2322:     my $response=$ua->request($request);
1.954     raeburn  2323:     if (wantarray) {
                   2324:         return ($response->content, $response);
                   2325:     } else {
                   2326:         return $response->content;
                   2327:     }
1.15      www      2328: }
1.254     www      2329: 
1.492     albertel 2330: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2331: 
                   2332: sub allowuploaded {
                   2333:     my ($srcurl,$url)=@_;
                   2334:     $url=&clutter(&declutter($url));
                   2335:     my $dir=$url;
                   2336:     $dir=~s/\/[^\/]+$//;
                   2337:     my %httpref=();
                   2338:     my $httpurl=&hreflocation('',$url);
                   2339:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2340:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2341: }
1.477     raeburn  2342: 
1.478     albertel 2343: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2344: # input: action, courseID, current domain, intended
1.637     raeburn  2345: #        path to file, source of file, instruction to parse file for objects,
                   2346: #        ref to hash for embedded objects,
                   2347: #        ref to hash for codebase of java objects.
1.1095    raeburn  2348: #        reference to scalar to accommodate mime type determined
                   2349: #          from File::MMagic if $parser = parse.
1.637     raeburn  2350: #
1.485     raeburn  2351: # output: url to file (if action was uploaddoc), 
                   2352: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2353: #
1.478     albertel 2354: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2355: # course.
1.477     raeburn  2356: #
1.478     albertel 2357: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2358: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2359: #          course's home server.
1.477     raeburn  2360: #
1.478     albertel 2361: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2362: #          be copied from $source (current location) to 
                   2363: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2364: #         and will then be copied to
                   2365: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2366: #         course's home server.
1.485     raeburn  2367: #
1.481     raeburn  2368: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2369: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2370: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2371: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2372: #         in course's home server.
1.637     raeburn  2373: #
1.477     raeburn  2374: 
                   2375: sub process_coursefile {
1.1095    raeburn  2376:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2377:         $mimetype)=@_;
1.477     raeburn  2378:     my $fetchresult;
1.638     albertel 2379:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2380:     if ($action eq 'propagate') {
1.638     albertel 2381:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2382: 			     $home);
1.481     raeburn  2383:     } else {
1.477     raeburn  2384:         my $fpath = '';
                   2385:         my $fname = $file;
1.478     albertel 2386:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2387:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2388:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2389:         if ($action eq 'copy') {
                   2390:             if ($source eq '') {
                   2391:                 $fetchresult = 'no source file';
                   2392:                 return $fetchresult;
                   2393:             } else {
                   2394:                 my $destination = $filepath.'/'.$fname;
                   2395:                 rename($source,$destination);
                   2396:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2397:                                  $home);
1.481     raeburn  2398:             }
                   2399:         } elsif ($action eq 'uploaddoc') {
                   2400:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2401:             print $fh $env{'form.'.$source};
1.481     raeburn  2402:             close($fh);
1.637     raeburn  2403:             if ($parser eq 'parse') {
1.1024    raeburn  2404:                 my $mm = new File::MMagic;
1.1095    raeburn  2405:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2406:                 if ($type eq 'text/html') {
1.1024    raeburn  2407:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2408:                     unless ($parse_result eq 'ok') {
                   2409:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2410:                     }
1.637     raeburn  2411:                 }
1.1095    raeburn  2412:                 if (ref($mimetype)) {
                   2413:                     $$mimetype = $type;
                   2414:                 } 
1.637     raeburn  2415:             }
1.477     raeburn  2416:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2417:                                  $home);
1.481     raeburn  2418:             if ($fetchresult eq 'ok') {
                   2419:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2420:             } else {
                   2421:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2422:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2423:                 return '/adm/notfound.html';
                   2424:             }
1.477     raeburn  2425:         }
                   2426:     }
1.485     raeburn  2427:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2428:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2429:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2430:     }
                   2431:     return $fetchresult;
                   2432: }
                   2433: 
1.637     raeburn  2434: sub build_filepath {
                   2435:     my ($fpath) = @_;
                   2436:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2437:     unless ($fpath eq '') {
                   2438:         my @parts=split('/',$fpath);
                   2439:         foreach my $part (@parts) {
                   2440:             $filepath.= '/'.$part;
                   2441:             if ((-e $filepath)!=1) {
                   2442:                 mkdir($filepath,0777);
                   2443:             }
                   2444:         }
                   2445:     }
                   2446:     return $filepath;
                   2447: }
                   2448: 
                   2449: sub store_edited_file {
1.638     albertel 2450:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2451:     my $file = $primary_url;
                   2452:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2453:     my $fpath = '';
                   2454:     my $fname = $file;
                   2455:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2456:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2457:     my $filepath = &build_filepath($fpath);
                   2458:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2459:     print $fh $content;
                   2460:     close($fh);
1.638     albertel 2461:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2462:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2463: 			  $home);
1.637     raeburn  2464:     if ($$fetchresult eq 'ok') {
                   2465:         return '/uploaded/'.$fpath.'/'.$fname;
                   2466:     } else {
1.638     albertel 2467:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2468: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2469:         return '/adm/notfound.html';
                   2470:     }
                   2471: }
                   2472: 
1.531     albertel 2473: sub clean_filename {
1.831     albertel 2474:     my ($fname,$args)=@_;
1.315     www      2475: # Replace Windows backslashes by forward slashes
1.257     www      2476:     $fname=~s/\\/\//g;
1.831     albertel 2477:     if (!$args->{'keep_path'}) {
                   2478:         # Get rid of everything but the actual filename
                   2479: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2480:     }
1.315     www      2481: # Replace spaces by underscores
                   2482:     $fname=~s/\s+/\_/g;
                   2483: # Replace all other weird characters by nothing
1.831     albertel 2484:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2485: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2486: # numbers
                   2487:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2488:     return $fname;
                   2489: }
1.1051    raeburn  2490: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2491: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2492: # image with the same aspect ratio as the original, but with dimensions which do 
                   2493: # not exceed $resizewidth and $resizeheight.
                   2494:  
1.984     neumanie 2495: sub resizeImage {
1.1051    raeburn  2496:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2497:     my $ima = Image::Magick->new;
                   2498:     my $resized;
                   2499:     if (-e $img_path) {
                   2500:         $ima->Read($img_path);
                   2501:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2502:             my $width = $ima->Get('width');
                   2503:             my $height = $ima->Get('height');
                   2504:             if ($width > $resizewidth) {
                   2505: 	        my $factor = $width/$resizewidth;
                   2506:                 my $newheight = $height/$factor;
                   2507:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2508:                 $resized = 1;
                   2509:             }
                   2510:         }
                   2511:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2512:             my $width = $ima->Get('width');
                   2513:             my $height = $ima->Get('height');
                   2514:             if ($height > $resizeheight) {
                   2515:                 my $factor = $height/$resizeheight;
                   2516:                 my $newwidth = $width/$factor;
                   2517:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2518:                 $resized = 1;
                   2519:             }
                   2520:         }
                   2521:         if ($resized) {
                   2522:             $ima->Write($img_path);
                   2523:         }
                   2524:     }
                   2525:     return;
1.977     amueller 2526: }
                   2527: 
1.608     albertel 2528: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2529: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2530: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2531: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2532: #                                    canceloverwrite, or ''. 
                   2533: #                   if 'coursedoc': upload to the current course
                   2534: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2535: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2536: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2537: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2538: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2539: #        $allfiles - reference to hash for embedded objects
                   2540: #        $codebase - reference to hash for codebase of java objects
                   2541: #        $desuname - username for permanent storage of uploaded file
                   2542: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2543: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2544: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2545: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2546: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2547: #        $mimetype - reference to scalar to accommodate mime type determined
                   2548: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2549: # 
1.686     albertel 2550: # output: url of file in userspace, or error: <message> 
                   2551: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2552: 
1.531     albertel 2553: sub userfileupload {
1.1090    raeburn  2554:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2555:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2556:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2557:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2558:     $fname=&clean_filename($fname);
1.1090    raeburn  2559:     # See if there is anything left
1.257     www      2560:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2561:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2562:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2563:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2564:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2565:         my $now = time;
1.1090    raeburn  2566:         my $filepath;
1.1095    raeburn  2567:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2568:              $filepath = 'tmp/helprequests/'.$now;
                   2569:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2570:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2571:                          '_'.$env{'user.domain'}.'/pending';
                   2572:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2573:             my ($docuname,$docudom);
                   2574:             if ($destudom) {
                   2575:                 $docudom = $destudom;
                   2576:             } else {
                   2577:                 $docudom = $env{'user.domain'};
                   2578:             }
                   2579:             if ($destuname) {
                   2580:                 $docuname = $destuname;
                   2581:             } else {
                   2582:                 $docuname = $env{'user.name'};
                   2583:             }
                   2584:             if (exists($env{'form.group'})) {
                   2585:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2586:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2587:             }
                   2588:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2589:             if ($context eq 'canceloverwrite') {
                   2590:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2591:                 if (-e  $tempfile) {
                   2592:                     my @info = stat($tempfile);
                   2593:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2594:                         unlink($tempfile);
                   2595:                     }
                   2596:                 }
                   2597:                 return;
1.523     raeburn  2598:             }
                   2599:         }
1.1090    raeburn  2600:         # Create the directory if not present
1.741     raeburn  2601:         my @parts=split(/\//,$filepath);
                   2602:         my $fullpath = $perlvar{'lonDaemons'};
                   2603:         for (my $i=0;$i<@parts;$i++) {
                   2604:             $fullpath .= '/'.$parts[$i];
                   2605:             if ((-e $fullpath)!=1) {
                   2606:                 mkdir($fullpath,0777);
                   2607:             }
                   2608:         }
                   2609:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2610:         print $fh $env{'form.'.$formname};
                   2611:         close($fh);
1.1090    raeburn  2612:         if ($context eq 'existingfile') {
                   2613:             my @info = stat($fullpath.'/'.$fname);
                   2614:             return ($fullpath.'/'.$fname,$info[9]);
                   2615:         } else {
                   2616:             return $fullpath.'/'.$fname;
                   2617:         }
1.523     raeburn  2618:     }
1.995     raeburn  2619:     if ($subdir eq 'scantron') {
                   2620:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2621:     } else {
1.995     raeburn  2622:         $fname="$subdir/$fname";
                   2623:     }
1.1090    raeburn  2624:     if ($context eq 'coursedoc') {
1.638     albertel 2625: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2626: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2627:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2628:             return &finishuserfileupload($docuname,$docudom,
                   2629: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2630: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2631:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2632:         } else {
1.620     albertel 2633:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2634:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2635: 				       $fname,$formname,$parser,
1.1095    raeburn  2636: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2637:         }
1.719     banghart 2638:     } elsif (defined($destuname)) {
                   2639:         my $docuname=$destuname;
                   2640:         my $docudom=$destudom;
1.860     raeburn  2641: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2642: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2643:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2644:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2645:     } else {
1.638     albertel 2646:         my $docuname=$env{'user.name'};
                   2647:         my $docudom=$env{'user.domain'};
1.714     raeburn  2648:         if (exists($env{'form.group'})) {
                   2649:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2650:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2651:         }
1.860     raeburn  2652: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2653: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2654:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2655:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2656:     }
1.271     www      2657: }
                   2658: 
                   2659: sub finishuserfileupload {
1.860     raeburn  2660:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2661:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2662:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2663:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2664:   
1.860     raeburn  2665:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2666:     $file=$fname;
                   2667:     if ($fname=~m|/|) {
                   2668:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2669: 	$path.=$fnamepath.'/';
                   2670:     }
1.259     www      2671:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2672:     my $count;
                   2673:     for ($count=4;$count<=$#parts;$count++) {
                   2674:         $filepath.="/$parts[$count]";
                   2675:         if ((-e $filepath)!=1) {
                   2676: 	    mkdir($filepath,0777);
                   2677:         }
                   2678:     }
1.984     neumanie 2679: 
1.258     www      2680: # Save the file
                   2681:     {
1.701     albertel 2682: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2683: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2684: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2685: 	    return '/adm/notfound.html';
                   2686: 	}
1.1090    raeburn  2687:         if ($context eq 'overwrite') {
1.1117    foxr     2688:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2689:             my $target = $filepath.'/'.$file;
                   2690:             if (-e $source) {
                   2691:                 my @info = stat($source);
                   2692:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2693:                     unless (&File::Copy::move($source,$target)) {
                   2694:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2695:                         return "Moving from $source failed";
                   2696:                     }
                   2697:                 } else {
                   2698:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2699:                 }
                   2700:             } else {
                   2701:                 return "Temporary file: $source missing";
                   2702:             }
                   2703:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2704: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2705: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2706: 	    return '/adm/notfound.html';
                   2707: 	}
1.570     albertel 2708: 	close(FH);
1.1051    raeburn  2709:         if ($resizewidth && $resizeheight) {
                   2710:             my $mm = new File::MMagic;
                   2711:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2712:             if ($mime_type =~ m{^image/}) {
                   2713: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2714:             }  
1.977     amueller 2715: 	}
1.258     www      2716:     }
1.637     raeburn  2717:     if ($parser eq 'parse') {
1.1024    raeburn  2718:         my $mm = new File::MMagic;
1.1095    raeburn  2719:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2720:         if ($type eq 'text/html') {
1.1024    raeburn  2721:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2722:                                                        $allfiles,$codebase);
                   2723:             unless ($parse_result eq 'ok') {
                   2724:                 &logthis('Failed to parse '.$filepath.$file.
                   2725: 	   	         ' for embedded media: '.$parse_result); 
                   2726:             }
1.637     raeburn  2727:         }
1.1095    raeburn  2728:         if (ref($mimetype)) {
                   2729:             $$mimetype = $type;
                   2730:         }
1.637     raeburn  2731:     }
1.860     raeburn  2732:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2733:         my $input = $filepath.'/'.$file;
                   2734:         my $output = $filepath.'/'.'tn-'.$file;
                   2735:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2736:         system("convert -sample $thumbsize $input $output");
                   2737:         if (-e $filepath.'/'.'tn-'.$file) {
                   2738:             $fetchthumb  = 1; 
                   2739:         }
                   2740:     }
1.858     raeburn  2741:  
1.259     www      2742: # Notify homeserver to grep it
                   2743: #
1.984     neumanie 2744:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2745:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2746:     if ($fetchresult eq 'ok') {
1.860     raeburn  2747:         if ($fetchthumb) {
                   2748:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2749:             if ($thumbresult ne 'ok') {
                   2750:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2751:                          $docuhome.': '.$thumbresult);
                   2752:             }
                   2753:         }
1.259     www      2754: #
1.258     www      2755: # Return the URL to it
1.494     albertel 2756:         return '/uploaded/'.$path.$file;
1.263     www      2757:     } else {
1.494     albertel 2758:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2759: 		 ': '.$fetchresult);
1.263     www      2760:         return '/adm/notfound.html';
1.858     raeburn  2761:     }
1.493     albertel 2762: }
                   2763: 
1.637     raeburn  2764: sub extract_embedded_items {
1.961     raeburn  2765:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2766:     my @state = ();
                   2767:     my %javafiles = (
                   2768:                       codebase => '',
                   2769:                       code => '',
                   2770:                       archive => ''
                   2771:                     );
                   2772:     my %mediafiles = (
                   2773:                       src => '',
                   2774:                       movie => '',
                   2775:                      );
1.648     raeburn  2776:     my $p;
                   2777:     if ($content) {
                   2778:         $p = HTML::LCParser->new($content);
                   2779:     } else {
1.961     raeburn  2780:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2781:     }
1.641     albertel 2782:     while (my $t=$p->get_token()) {
1.640     albertel 2783: 	if ($t->[0] eq 'S') {
                   2784: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2785: 	    push(@state, $tagname);
1.648     raeburn  2786:             if (lc($tagname) eq 'allow') {
                   2787:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2788:             }
1.640     albertel 2789: 	    if (lc($tagname) eq 'img') {
                   2790: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2791: 	    }
1.886     albertel 2792: 	    if (lc($tagname) eq 'a') {
                   2793: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2794: 	    }
1.645     raeburn  2795:             if (lc($tagname) eq 'script') {
                   2796:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2797:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2798:                 } else {
                   2799:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2800:                 }
                   2801:             }
                   2802:             if (lc($tagname) eq 'link') {
                   2803:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2804:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2805:                 }
                   2806:             }
1.640     albertel 2807: 	    if (lc($tagname) eq 'object' ||
                   2808: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2809: 		foreach my $item (keys(%javafiles)) {
                   2810: 		    $javafiles{$item} = '';
                   2811: 		}
                   2812: 	    }
                   2813: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2814: 		my $name = lc($attr->{'name'});
                   2815: 		foreach my $item (keys(%javafiles)) {
                   2816: 		    if ($name eq $item) {
                   2817: 			$javafiles{$item} = $attr->{'value'};
                   2818: 			last;
                   2819: 		    }
                   2820: 		}
                   2821: 		foreach my $item (keys(%mediafiles)) {
                   2822: 		    if ($name eq $item) {
                   2823: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2824: 			last;
                   2825: 		    }
                   2826: 		}
                   2827: 	    }
                   2828: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2829: 		foreach my $item (keys(%javafiles)) {
                   2830: 		    if ($attr->{$item}) {
                   2831: 			$javafiles{$item} = $attr->{$item};
                   2832: 			last;
                   2833: 		    }
                   2834: 		}
                   2835: 		foreach my $item (keys(%mediafiles)) {
                   2836: 		    if ($attr->{$item}) {
                   2837: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2838: 			last;
                   2839: 		    }
                   2840: 		}
                   2841: 	    }
                   2842: 	} elsif ($t->[0] eq 'E') {
                   2843: 	    my ($tagname) = ($t->[1]);
                   2844: 	    if ($javafiles{'codebase'} ne '') {
                   2845: 		$javafiles{'codebase'} .= '/';
                   2846: 	    }  
                   2847: 	    if (lc($tagname) eq 'applet' ||
                   2848: 		lc($tagname) eq 'object' ||
                   2849: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2850: 		) {
                   2851: 		foreach my $item (keys(%javafiles)) {
                   2852: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2853: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2854: 			&add_filetype($allfiles,$file,$item);
                   2855: 		    }
                   2856: 		}
                   2857: 	    } 
                   2858: 	    pop @state;
                   2859: 	}
                   2860:     }
1.637     raeburn  2861:     return 'ok';
                   2862: }
                   2863: 
1.639     albertel 2864: sub add_filetype {
                   2865:     my ($allfiles,$file,$type)=@_;
                   2866:     if (exists($allfiles->{$file})) {
                   2867: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2868: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2869: 	}
                   2870:     } else {
                   2871: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2872:     }
                   2873: }
                   2874: 
1.493     albertel 2875: sub removeuploadedurl {
1.984     neumanie 2876:     my ($url)=@_;	
                   2877:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2878:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2879: }
                   2880: 
                   2881: sub removeuserfile {
                   2882:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2883:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2884:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2885:     if ($result eq 'ok') {	
1.798     raeburn  2886:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2887:             my $metafile = $fname.'.meta';
                   2888:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2889: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2890:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2891:             my $sqlresult = 
1.823     albertel 2892:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2893:                                         'portfolio_metadata',$group,
                   2894:                                         'delete');
1.798     raeburn  2895:         }
                   2896:     }
                   2897:     return $result;
1.257     www      2898: }
1.15      www      2899: 
1.530     albertel 2900: sub mkdiruserfile {
                   2901:     my ($docuname,$docudom,$dir)=@_;
                   2902:     my $home=&homeserver($docuname,$docudom);
                   2903:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2904: }
                   2905: 
1.531     albertel 2906: sub renameuserfile {
                   2907:     my ($docuname,$docudom,$old,$new)=@_;
                   2908:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2909:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2910:                         &escape("$old").':'.&escape("$new"),$home);
                   2911:     if ($result eq 'ok') {
                   2912:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2913:             my $oldmeta = $old.'.meta';
                   2914:             my $newmeta = $new.'.meta';
                   2915:             my $metaresult = 
                   2916:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2917: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2918:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2919:             my $sqlresult = 
1.823     albertel 2920:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2921:                                         'portfolio_metadata',$group,
                   2922:                                         'delete');
1.798     raeburn  2923:         }
                   2924:     }
                   2925:     return $result;
1.531     albertel 2926: }
                   2927: 
1.14      www      2928: # ------------------------------------------------------------------------- Log
                   2929: 
                   2930: sub log {
                   2931:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2932:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2933: }
                   2934: 
                   2935: # ------------------------------------------------------------------ Course Log
1.352     www      2936: #
                   2937: # This routine flushes several buffers of non-mission-critical nature
                   2938: #
1.157     www      2939: 
                   2940: sub flushcourselogs {
1.352     www      2941:     &logthis('Flushing log buffers');
                   2942: #
                   2943: # course logs
                   2944: # This is a log of all transactions in a course, which can be used
                   2945: # for data mining purposes
                   2946: #
                   2947: # It also collects the courseid database, which lists last transaction
                   2948: # times and course titles for all courseids
                   2949: #
                   2950:     my %courseidbuffer=();
1.921     raeburn  2951:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2952:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2953: 		          &escape($courselogs{$crsid}),
                   2954: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2955: 	    delete $courselogs{$crsid};
                   2956:         } else {
                   2957:             &logthis('Failed to flush log buffer for '.$crsid);
                   2958:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2959:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2960:                         " exceeded maximum size, deleting.</font>");
                   2961:                delete $courselogs{$crsid};
                   2962:             }
1.352     www      2963:         }
1.920     raeburn  2964:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2965:             'description' => $coursedescrbuf{$crsid},
                   2966:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2967:             'type'        => $coursetypebuf{$crsid},
                   2968:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2969:         };
1.191     harris41 2970:     }
1.352     www      2971: #
                   2972: # Write course id database (reverse lookup) to homeserver of courses 
                   2973: # Is used in pickcourse
                   2974: #
1.840     albertel 2975:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2976:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2977:                                     $courseidbuffer{$crs_home},
                   2978:                                     $crs_home,'timeonly');
1.352     www      2979:     }
                   2980: #
                   2981: # File accesses
                   2982: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2983: #
1.449     matthew  2984:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2985:         if ($entry =~ /___count$/) {
                   2986:             my ($dom,$name);
1.807     albertel 2987:             ($dom,$name,undef)=
1.811     albertel 2988: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2989:             if (! defined($dom) || $dom eq '' || 
                   2990:                 ! defined($name) || $name eq '') {
1.620     albertel 2991:                 my $cid = $env{'request.course.id'};
                   2992:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2993:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2994:             }
1.450     matthew  2995:             my $value = $accesshash{$entry};
                   2996:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2997:             my %temphash=($url => $value);
1.449     matthew  2998:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2999:             if ($result eq 'ok') {
                   3000:                 delete $accesshash{$entry};
                   3001:             } elsif ($result eq 'unknown_cmd') {
                   3002:                 # Target server has old code running on it.
1.450     matthew  3003:                 my %temphash=($entry => $value);
1.449     matthew  3004:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3005:                     delete $accesshash{$entry};
                   3006:                 }
                   3007:             }
                   3008:         } else {
1.811     albertel 3009:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3010:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3011:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3012:                 delete $accesshash{$entry};
                   3013:             }
1.185     www      3014:         }
1.191     harris41 3015:     }
1.352     www      3016: #
                   3017: # Roles
                   3018: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3019: #
1.800     albertel 3020:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3021:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3022: 	    split(/\:/,$entry);
                   3023:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3024:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3025:                 $rudom,$runame) eq 'ok') {
                   3026: 	    delete $userrolehash{$entry};
                   3027:         }
                   3028:     }
1.662     raeburn  3029: #
                   3030: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3031: #
                   3032:     my %domrolebuffer = ();
1.1000    raeburn  3033:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3034:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3035:         if ($domrolebuffer{$rudom}) {
                   3036:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3037:                       '='.&escape($domainrolehash{$entry});
                   3038:         } else {
                   3039:             $domrolebuffer{$rudom}.=&escape($entry).
                   3040:                       '='.&escape($domainrolehash{$entry});
                   3041:         }
                   3042:         delete $domainrolehash{$entry};
                   3043:     }
                   3044:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3045: 	my %servers = &get_servers($dom,'library');
                   3046: 	foreach my $tryserver (keys(%servers)) {
                   3047: 	    unless (&reply('domroleput:'.$dom.':'.
                   3048: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3049: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3050: 	    }
1.662     raeburn  3051:         }
                   3052:     }
1.186     www      3053:     $dumpcount++;
1.157     www      3054: }
                   3055: 
                   3056: sub courselog {
                   3057:     my $what=shift;
1.158     www      3058:     $what=time.':'.$what;
1.620     albertel 3059:     unless ($env{'request.course.id'}) { return ''; }
                   3060:     $coursedombuf{$env{'request.course.id'}}=
                   3061:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3062:     $coursenumbuf{$env{'request.course.id'}}=
                   3063:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3064:     $coursehombuf{$env{'request.course.id'}}=
                   3065:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3066:     $coursedescrbuf{$env{'request.course.id'}}=
                   3067:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3068:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3069:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3070:     $courseownerbuf{$env{'request.course.id'}}=
                   3071:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3072:     $coursetypebuf{$env{'request.course.id'}}=
                   3073:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3074:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3075: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3076:     } else {
1.620     albertel 3077: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3078:     }
1.620     albertel 3079:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3080: 	&flushcourselogs();
                   3081:     }
1.158     www      3082: }
                   3083: 
                   3084: sub courseacclog {
                   3085:     my $fnsymb=shift;
1.620     albertel 3086:     unless ($env{'request.course.id'}) { return ''; }
                   3087:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3088:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3089:         $what.=':POST';
1.583     matthew  3090:         # FIXME: Probably ought to escape things....
1.800     albertel 3091: 	foreach my $key (keys(%env)) {
                   3092:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3093:                 my $formitem = $1;
                   3094:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3095:                     $what.=':'.$formitem.'='.$env{$key};
                   3096:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3097:                     $what.=':'.$formitem.'='.$env{$key};
                   3098:                 }
1.158     www      3099:             }
1.191     harris41 3100:         }
1.583     matthew  3101:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3102:         # FIXME: We should not be depending on a form parameter that someone
                   3103:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3104:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3105:             $what.= ':POST';
                   3106:             # FIXME: Probably ought to escape things....
                   3107:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3108:                                  'crsdiscuss') {
1.620     albertel 3109:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3110:             }
                   3111:         }
1.158     www      3112:     }
                   3113:     &courselog($what);
1.149     www      3114: }
                   3115: 
1.185     www      3116: sub countacc {
                   3117:     my $url=&declutter(shift);
1.458     matthew  3118:     return if (! defined($url) || $url eq '');
1.620     albertel 3119:     unless ($env{'request.course.id'}) { return ''; }
                   3120:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3121:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3122:     $accesshash{$key}++;
1.185     www      3123: }
1.349     www      3124: 
1.361     www      3125: sub linklog {
                   3126:     my ($from,$to)=@_;
                   3127:     $from=&declutter($from);
                   3128:     $to=&declutter($to);
                   3129:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3130:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3131: }
                   3132:   
1.349     www      3133: sub userrolelog {
                   3134:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3135:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3136:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3137:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3138:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3139:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3140:        $userrolehash
                   3141:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3142:                     =$tend.':'.$tstart;
1.662     raeburn  3143:     }
1.898     albertel 3144:     if (($env{'request.role'} =~ /dc\./) &&
                   3145: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3146: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3147: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3148:          ($trole=~/^co/))) {
1.898     albertel 3149:        $userrolehash
                   3150:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3151:                     =$tend.':'.$tstart;
                   3152:     }
1.662     raeburn  3153:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3154:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3155:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3156:         ($trole=~/^sc/)) {
                   3157:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3158:        $domainrolehash
                   3159:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3160:                     = $tend.':'.$tstart;
                   3161:     }
1.351     www      3162: }
                   3163: 
1.957     raeburn  3164: sub courserolelog {
                   3165:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3166:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3167:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3168:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3169:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3170:         ($trole eq 'co')) {
1.957     raeburn  3171:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3172:             my $cdom = $1;
                   3173:             my $cnum = $2;
                   3174:             my $sec = $3;
                   3175:             my $namespace = 'rolelog';
                   3176:             my %storehash = (
                   3177:                                role    => $trole,
                   3178:                                start   => $tstart,
                   3179:                                end     => $tend,
                   3180:                                selfenroll => $selfenroll,
                   3181:                                context    => $context,
                   3182:                             );
                   3183:             if ($trole eq 'gr') {
                   3184:                 $namespace = 'groupslog';
                   3185:                 $storehash{'group'} = $sec;
                   3186:             } else {
                   3187:                 $storehash{'section'} = $sec;
                   3188:             }
                   3189:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3190:             if (($trole ne 'st') || ($sec ne '')) {
                   3191:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3192:             }
1.957     raeburn  3193:         }
                   3194:     }
                   3195:     return;
                   3196: }
                   3197: 
1.351     www      3198: sub get_course_adv_roles {
1.948     raeburn  3199:     my ($cid,$codes) = @_;
1.620     albertel 3200:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3201:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3202:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3203:     my %nothide=();
1.800     albertel 3204:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3205:         if ($user !~ /:/) {
                   3206: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3207:         } else {
                   3208:             $nothide{$user}=1;
                   3209:         }
1.470     www      3210:     }
1.351     www      3211:     my %returnhash=();
                   3212:     my %dumphash=
                   3213:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3214:     my $now=time;
1.997     raeburn  3215:     my %privileged;
1.1000    raeburn  3216:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3217: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3218:         if (($tstart) && ($tstart<0)) { next; }
                   3219:         if (($tend) && ($tend<$now)) { next; }
                   3220:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3221:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3222: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3223:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3224:             my %dompersonnel =
1.998     raeburn  3225:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3226:             $privileged{$domain} = {};
                   3227:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3228:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3229:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3230:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3231:                         $privileged{$udom}{$uname} = 1;
                   3232:                     }
                   3233:                 }
                   3234:             }
                   3235:         }
                   3236:         if ((exists($privileged{$domain}{$username})) && 
                   3237:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3238: 	if ($role eq 'cr') { next; }
1.948     raeburn  3239:         if ($codes) {
                   3240:             if ($section) { $role .= ':'.$section; }
                   3241:             if ($returnhash{$role}) {
                   3242:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3243:             } else {
                   3244:                 $returnhash{$role}=$username.':'.$domain;
                   3245:             }
1.351     www      3246:         } else {
1.988     raeburn  3247:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3248:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3249:             if ($returnhash{$key}) {
                   3250: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3251:             } else {
                   3252:                 $returnhash{$key}=$username.':'.$domain;
                   3253:             }
1.351     www      3254:         }
1.948     raeburn  3255:     }
1.400     www      3256:     return %returnhash;
                   3257: }
                   3258: 
                   3259: sub get_my_roles {
1.937     raeburn  3260:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3261:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3262:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3263:     my (%dumphash,%nothide);
1.1086    raeburn  3264:     if ($context eq 'userroles') {
                   3265:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3266:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3267:     } else {
                   3268:         %dumphash=
1.400     www      3269:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3270:         if ($hidepriv) {
                   3271:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3272:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3273:                 if ($user !~ /:/) {
                   3274:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3275:                 } else {
                   3276:                     $nothide{$user} = 1;
                   3277:                 }
                   3278:             }
                   3279:         }
1.858     raeburn  3280:     }
1.400     www      3281:     my %returnhash=();
                   3282:     my $now=time;
1.999     raeburn  3283:     my %privileged;
1.800     albertel 3284:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3285:         my ($role,$tend,$tstart);
                   3286:         if ($context eq 'userroles') {
                   3287: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3288:         } else {
                   3289:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3290:         }
1.400     www      3291:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3292:         my $status = 'active';
1.939     raeburn  3293:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3294:             $status = 'previous';
                   3295:         } 
                   3296:         if (($tstart) && ($now<$tstart)) {
                   3297:             $status = 'future';
                   3298:         }
                   3299:         if (ref($types) eq 'ARRAY') {
                   3300:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3301:                 next;
                   3302:             } 
                   3303:         } else {
                   3304:             if ($status ne 'active') {
                   3305:                 next;
                   3306:             }
                   3307:         }
1.867     raeburn  3308:         my ($rolecode,$username,$domain,$section,$area);
                   3309:         if ($context eq 'userroles') {
                   3310:             ($area,$rolecode) = split(/_/,$entry);
                   3311:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3312:         } else {
                   3313:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3314:         }
1.832     raeburn  3315:         if (ref($roledoms) eq 'ARRAY') {
                   3316:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3317:                 next;
                   3318:             }
                   3319:         }
                   3320:         if (ref($roles) eq 'ARRAY') {
                   3321:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3322:                 if ($role =~ /^cr\//) {
                   3323:                     if (!grep(/^cr$/,@{$roles})) {
                   3324:                         next;
                   3325:                     }
1.1104    raeburn  3326:                 } elsif ($role =~ /^gr\//) {
                   3327:                     if (!grep(/^gr$/,@{$roles})) {
                   3328:                         next;
                   3329:                     }
1.922     raeburn  3330:                 } else {
                   3331:                     next;
                   3332:                 }
1.832     raeburn  3333:             }
1.867     raeburn  3334:         }
1.937     raeburn  3335:         if ($hidepriv) {
1.999     raeburn  3336:             if ($context eq 'userroles') {
                   3337:                 if ((&privileged($username,$domain)) &&
                   3338:                     (!$nothide{$username.':'.$domain})) {
                   3339:                     next;
                   3340:                 }
                   3341:             } else {
                   3342:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3343:                     my %dompersonnel =
                   3344:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3345:                     $privileged{$domain} = {};
                   3346:                     if (keys(%dompersonnel)) {
                   3347:                         foreach my $server (keys(%dompersonnel)) {
                   3348:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3349:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3350:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3351:                                     $privileged{$udom}{$uname} = $trole;
                   3352:                                 }
                   3353:                             }
                   3354:                         }
                   3355:                     }
                   3356:                 }
                   3357:                 if (exists($privileged{$domain}{$username})) {
                   3358:                     if (!$nothide{$username.':'.$domain}) {
                   3359:                         next;
                   3360:                     }
                   3361:                 }
1.937     raeburn  3362:             }
                   3363:         }
1.933     raeburn  3364:         if ($withsec) {
                   3365:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3366:                 $tstart.':'.$tend;
                   3367:         } else {
                   3368:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3369:         }
1.832     raeburn  3370:     }
1.373     www      3371:     return %returnhash;
1.399     www      3372: }
                   3373: 
                   3374: # ----------------------------------------------------- Frontpage Announcements
                   3375: #
                   3376: #
                   3377: 
                   3378: sub postannounce {
                   3379:     my ($server,$text)=@_;
1.844     albertel 3380:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3381:     unless ($text=~/\w/) { $text=''; }
                   3382:     return &reply('setannounce:'.&escape($text),$server);
                   3383: }
                   3384: 
                   3385: sub getannounce {
1.448     albertel 3386: 
                   3387:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3388: 	my $announcement='';
1.800     albertel 3389: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3390: 	close($fh);
1.399     www      3391: 	if ($announcement=~/\w/) { 
                   3392: 	    return 
                   3393:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3394:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3395: 	} else {
                   3396: 	    return '';
                   3397: 	}
                   3398:     } else {
                   3399: 	return '';
                   3400:     }
1.351     www      3401: }
1.353     www      3402: 
                   3403: # ---------------------------------------------------------- Course ID routines
                   3404: # Deal with domain's nohist_courseid.db files
                   3405: #
                   3406: 
                   3407: sub courseidput {
1.921     raeburn  3408:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3409:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3410:     my $outcome;
                   3411:     if ($caller eq 'timeonly') {
                   3412:         my $cids = '';
                   3413:         foreach my $item (keys(%$storehash)) {
                   3414:             $cids.=&escape($item).'&';
                   3415:         }
                   3416:         $cids=~s/\&$//;
                   3417:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3418:                           $coursehome);       
                   3419:     } else {
                   3420:         my $items = '';
                   3421:         foreach my $item (keys(%$storehash)) {
                   3422:             $items.= &escape($item).'='.
                   3423:                      &freeze_escape($$storehash{$item}).'&';
                   3424:         }
                   3425:         $items=~s/\&$//;
                   3426:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3427:                           $coursehome);
1.918     raeburn  3428:     }
                   3429:     if ($outcome eq 'unknown_cmd') {
                   3430:         my $what;
                   3431:         foreach my $cid (keys(%$storehash)) {
                   3432:             $what .= &escape($cid).'=';
1.921     raeburn  3433:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3434:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3435:             }
                   3436:             $what =~ s/\:$/&/;
                   3437:         }
                   3438:         $what =~ s/\&$//;  
                   3439:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3440:     } else {
                   3441:         return $outcome;
                   3442:     }
1.353     www      3443: }
                   3444: 
                   3445: sub courseiddump {
1.921     raeburn  3446:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3447:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3448:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3449:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3450:     my $as_hash = 1;
                   3451:     my %returnhash;
                   3452:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3453:     my %libserv = &all_library();
                   3454:     foreach my $tryserver (keys(%libserv)) {
                   3455:         if ( (  $hostidflag == 1 
                   3456: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3457: 	     || (!defined($hostidflag)) ) {
                   3458: 
1.918     raeburn  3459: 	    if (($domfilter eq '') ||
                   3460: 		(&host_domain($tryserver) eq $domfilter)) {
                   3461:                 my $rep = 
                   3462:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3463:                          $sincefilter.':'.&escape($descfilter).':'.
                   3464:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3465:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3466:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3467:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3468:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3469:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3470:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3471:                          &escape($creationcontext).':'.$domcloner,
                   3472:                          $tryserver);
1.918     raeburn  3473:                 my @pairs=split(/\&/,$rep);
                   3474:                 foreach my $item (@pairs) {
                   3475:                     my ($key,$value)=split(/\=/,$item,2);
                   3476:                     $key = &unescape($key);
                   3477:                     next if ($key =~ /^error: 2 /);
                   3478:                     my $result = &thaw_unescape($value);
                   3479:                     if (ref($result) eq 'HASH') {
                   3480:                         $returnhash{$key}=$result;
                   3481:                     } else {
1.921     raeburn  3482:                         my @responses = split(/:/,$value);
                   3483:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3484:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3485:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3486:                         }
1.1008    raeburn  3487:                     }
1.353     www      3488:                 }
                   3489:             }
                   3490:         }
                   3491:     }
                   3492:     return %returnhash;
                   3493: }
                   3494: 
1.1055    raeburn  3495: sub courselastaccess {
                   3496:     my ($cdom,$cnum,$hostidref) = @_;
                   3497:     my %returnhash;
                   3498:     if ($cdom && $cnum) {
                   3499:         my $chome = &homeserver($cnum,$cdom);
                   3500:         if ($chome ne 'no_host') {
                   3501:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3502:             &extract_lastaccess(\%returnhash,$rep);
                   3503:         }
                   3504:     } else {
                   3505:         if (!$cdom) { $cdom=''; }
                   3506:         my %libserv = &all_library();
                   3507:         foreach my $tryserver (keys(%libserv)) {
                   3508:             if (ref($hostidref) eq 'ARRAY') {
                   3509:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3510:             } 
                   3511:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3512:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3513:                 &extract_lastaccess(\%returnhash,$rep);
                   3514:             }
                   3515:         }
                   3516:     }
                   3517:     return %returnhash;
                   3518: }
                   3519: 
                   3520: sub extract_lastaccess {
                   3521:     my ($returnhash,$rep) = @_;
                   3522:     if (ref($returnhash) eq 'HASH') {
                   3523:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3524:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3525:                  $rep eq '') {
                   3526:             my @pairs=split(/\&/,$rep);
                   3527:             foreach my $item (@pairs) {
                   3528:                 my ($key,$value)=split(/\=/,$item,2);
                   3529:                 $key = &unescape($key);
                   3530:                 next if ($key =~ /^error: 2 /);
                   3531:                 $returnhash->{$key} = &thaw_unescape($value);
                   3532:             }
                   3533:         }
                   3534:     }
                   3535:     return;
                   3536: }
                   3537: 
1.658     raeburn  3538: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3539: 
                   3540: sub dcmailput {
1.685     raeburn  3541:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3542:     my $status = &Apache::lonnet::critical(
1.740     www      3543:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3544:        &escape($message),$server);
1.662     raeburn  3545:     return $status;
                   3546: }
                   3547: 
1.658     raeburn  3548: sub dcmaildump {
                   3549:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3550:     my %returnhash=();
1.846     albertel 3551: 
                   3552:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3553:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3554:                                                          &escape($enddate).':';
                   3555: 	my @esc_senders=map { &escape($_)} @$senders;
                   3556: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3557: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3558:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3559:             if (($key) && ($value)) {
                   3560:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3561:             }
                   3562:         }
                   3563:     }
                   3564:     return %returnhash;
                   3565: }
1.662     raeburn  3566: # ---------------------------------------------------------- Domain roles
                   3567: 
                   3568: sub get_domain_roles {
                   3569:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3570:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3571:         $startdate = '.';
                   3572:     }
1.1018    raeburn  3573:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3574:         $enddate = '.';
                   3575:     }
1.922     raeburn  3576:     my $rolelist;
                   3577:     if (ref($roles) eq 'ARRAY') {
                   3578:         $rolelist = join(':',@{$roles});
                   3579:     }
1.662     raeburn  3580:     my %personnel = ();
1.841     albertel 3581: 
                   3582:     my %servers = &get_servers($dom,'library');
                   3583:     foreach my $tryserver (keys(%servers)) {
                   3584: 	%{$personnel{$tryserver}}=();
                   3585: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3586: 					    &escape($startdate).':'.
                   3587: 					    &escape($enddate).':'.
                   3588: 					    &escape($rolelist), $tryserver))) {
                   3589: 	    my ($key,$value) = split(/\=/,$line,2);
                   3590: 	    if (($key) && ($value)) {
                   3591: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3592: 	    }
                   3593: 	}
1.662     raeburn  3594:     }
                   3595:     return %personnel;
                   3596: }
1.658     raeburn  3597: 
1.1057    www      3598: # ----------------------------------------------------------- Interval timing 
1.149     www      3599: 
1.504     albertel 3600: sub get_first_access {
                   3601:     my ($type,$argsymb)=@_;
1.790     albertel 3602:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3603:     if ($argsymb) { $symb=$argsymb; }
                   3604:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3605:     if ($type eq 'course') {
                   3606: 	$res='course';
                   3607:     } elsif ($type eq 'map') {
1.588     albertel 3608: 	$res=&symbread($map);
                   3609:     } else {
                   3610: 	$res=$symb;
                   3611:     }
                   3612:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3613:     return $times{"$courseid\0$res"};
1.504     albertel 3614: }
                   3615: 
                   3616: sub set_first_access {
                   3617:     my ($type)=@_;
1.790     albertel 3618:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3619:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3620:     if ($type eq 'course') {
                   3621: 	$res='course';
                   3622:     } elsif ($type eq 'map') {
1.588     albertel 3623: 	$res=&symbread($map);
                   3624:     } else {
                   3625: 	$res=$symb;
                   3626:     }
                   3627:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3628:     if (!$firstaccess) {
1.588     albertel 3629: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3630:     }
                   3631:     return 'already_set';
1.504     albertel 3632: }
                   3633: 
1.110     www      3634: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3635: 
                   3636: sub expirespread {
                   3637:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3638:     my $cid=$env{'request.course.id'}; 
1.110     www      3639:     if ($cid) {
                   3640:        my $now=time;
                   3641:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3642:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3643:                             $env{'course.'.$cid.'.num'}.
1.110     www      3644: 	        	    ':nohist_expirationdates:'.
                   3645:                             &escape($key).'='.$now,
1.620     albertel 3646:                             $env{'course.'.$cid.'.home'})
1.110     www      3647:     }
                   3648:     return 'ok';
1.14      www      3649: }
                   3650: 
1.109     www      3651: # ----------------------------------------------------- Devalidate Spreadsheets
                   3652: 
                   3653: sub devalidate {
1.325     www      3654:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3655:     my $cid=$env{'request.course.id'}; 
1.109     www      3656:     if ($cid) {
1.391     matthew  3657:         # delete the stored spreadsheets for
                   3658:         # - the student level sheet of this user in course's homespace
                   3659:         # - the assessment level sheet for this resource 
                   3660:         #   for this user in user's homespace
1.553     albertel 3661: 	# - current conditional state info
1.325     www      3662: 	my $key=$uname.':'.$udom.':';
1.109     www      3663:         my $status=
1.299     matthew  3664: 	    &del('nohist_calculatedsheets',
1.391     matthew  3665: 		 [$key.'studentcalc:'],
1.620     albertel 3666: 		 $env{'course.'.$cid.'.domain'},
                   3667: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3668: 		.' '.
                   3669: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3670: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3671:         unless ($status eq 'ok ok') {
                   3672:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3673:                     $uname.' at '.$udom.' for '.
1.109     www      3674: 		    $symb.': '.$status);
1.133     albertel 3675:         }
1.553     albertel 3676: 	&delenv('user.state.'.$cid);
1.109     www      3677:     }
                   3678: }
                   3679: 
1.265     albertel 3680: sub get_scalar {
                   3681:     my ($string,$end) = @_;
                   3682:     my $value;
                   3683:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3684: 	$value = $1;
                   3685:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3686: 	$value = $1;
                   3687:     }
                   3688:     return &unescape($value);
                   3689: }
                   3690: 
                   3691: sub array2str {
                   3692:   my (@array) = @_;
                   3693:   my $result=&arrayref2str(\@array);
                   3694:   $result=~s/^__ARRAY_REF__//;
                   3695:   $result=~s/__END_ARRAY_REF__$//;
                   3696:   return $result;
                   3697: }
                   3698: 
1.204     albertel 3699: sub arrayref2str {
                   3700:   my ($arrayref) = @_;
1.265     albertel 3701:   my $result='__ARRAY_REF__';
1.204     albertel 3702:   foreach my $elem (@$arrayref) {
1.265     albertel 3703:     if(ref($elem) eq 'ARRAY') {
                   3704:       $result.=&arrayref2str($elem).'&';
                   3705:     } elsif(ref($elem) eq 'HASH') {
                   3706:       $result.=&hashref2str($elem).'&';
                   3707:     } elsif(ref($elem)) {
                   3708:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3709:     } else {
                   3710:       $result.=&escape($elem).'&';
                   3711:     }
                   3712:   }
                   3713:   $result=~s/\&$//;
1.265     albertel 3714:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3715:   return $result;
                   3716: }
                   3717: 
1.168     albertel 3718: sub hash2str {
1.204     albertel 3719:   my (%hash) = @_;
                   3720:   my $result=&hashref2str(\%hash);
1.265     albertel 3721:   $result=~s/^__HASH_REF__//;
                   3722:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3723:   return $result;
                   3724: }
                   3725: 
                   3726: sub hashref2str {
                   3727:   my ($hashref)=@_;
1.265     albertel 3728:   my $result='__HASH_REF__';
1.800     albertel 3729:   foreach my $key (sort(keys(%$hashref))) {
                   3730:     if (ref($key) eq 'ARRAY') {
                   3731:       $result.=&arrayref2str($key).'=';
                   3732:     } elsif (ref($key) eq 'HASH') {
                   3733:       $result.=&hashref2str($key).'=';
                   3734:     } elsif (ref($key)) {
1.265     albertel 3735:       $result.='=';
1.800     albertel 3736:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3737:     } else {
1.800     albertel 3738: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3739:     }
                   3740: 
1.800     albertel 3741:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3742:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3743:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3744:       $result.=&hashref2str($hashref->{$key}).'&';
                   3745:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3746:        $result.='&';
1.800     albertel 3747:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3748:     } else {
1.800     albertel 3749:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3750:     }
                   3751:   }
1.168     albertel 3752:   $result=~s/\&$//;
1.265     albertel 3753:   $result .= '__END_HASH_REF__';
1.168     albertel 3754:   return $result;
                   3755: }
                   3756: 
                   3757: sub str2hash {
1.265     albertel 3758:     my ($string)=@_;
                   3759:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3760:     return %$hash;
                   3761: }
                   3762: 
                   3763: sub str2hashref {
1.168     albertel 3764:   my ($string) = @_;
1.265     albertel 3765: 
                   3766:   my %hash;
                   3767: 
                   3768:   if($string !~ /^__HASH_REF__/) {
                   3769:       if (! ($string eq '' || !defined($string))) {
                   3770: 	  $hash{'error'}='Not hash reference';
                   3771:       }
                   3772:       return (\%hash, $string);
                   3773:   }
                   3774: 
                   3775:   $string =~ s/^__HASH_REF__//;
                   3776: 
                   3777:   while($string !~ /^__END_HASH_REF__/) {
                   3778:       #key
                   3779:       my $key='';
                   3780:       if($string =~ /^__HASH_REF__/) {
                   3781:           ($key, $string)=&str2hashref($string);
                   3782:           if(defined($key->{'error'})) {
                   3783:               $hash{'error'}='Bad data';
                   3784:               return (\%hash, $string);
                   3785:           }
                   3786:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3787:           ($key, $string)=&str2arrayref($string);
                   3788:           if($key->[0] eq 'Array reference error') {
                   3789:               $hash{'error'}='Bad data';
                   3790:               return (\%hash, $string);
                   3791:           }
                   3792:       } else {
                   3793:           $string =~ s/^(.*?)=//;
1.267     albertel 3794: 	  $key=&unescape($1);
1.265     albertel 3795:       }
                   3796:       $string =~ s/^=//;
                   3797: 
                   3798:       #value
                   3799:       my $value='';
                   3800:       if($string =~ /^__HASH_REF__/) {
                   3801:           ($value, $string)=&str2hashref($string);
                   3802:           if(defined($value->{'error'})) {
                   3803:               $hash{'error'}='Bad data';
                   3804:               return (\%hash, $string);
                   3805:           }
                   3806:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3807:           ($value, $string)=&str2arrayref($string);
                   3808:           if($value->[0] eq 'Array reference error') {
                   3809:               $hash{'error'}='Bad data';
                   3810:               return (\%hash, $string);
                   3811:           }
                   3812:       } else {
                   3813: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3814:       }
                   3815:       $string =~ s/^&//;
                   3816: 
                   3817:       $hash{$key}=$value;
1.204     albertel 3818:   }
1.265     albertel 3819: 
                   3820:   $string =~ s/^__END_HASH_REF__//;
                   3821: 
                   3822:   return (\%hash, $string);
1.204     albertel 3823: }
                   3824: 
                   3825: sub str2array {
1.265     albertel 3826:     my ($string)=@_;
                   3827:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3828:     return @$array;
                   3829: }
                   3830: 
                   3831: sub str2arrayref {
1.204     albertel 3832:   my ($string) = @_;
1.265     albertel 3833:   my @array;
                   3834: 
                   3835:   if($string !~ /^__ARRAY_REF__/) {
                   3836:       if (! ($string eq '' || !defined($string))) {
                   3837: 	  $array[0]='Array reference error';
                   3838:       }
                   3839:       return (\@array, $string);
                   3840:   }
                   3841: 
                   3842:   $string =~ s/^__ARRAY_REF__//;
                   3843: 
                   3844:   while($string !~ /^__END_ARRAY_REF__/) {
                   3845:       my $value='';
                   3846:       if($string =~ /^__HASH_REF__/) {
                   3847:           ($value, $string)=&str2hashref($string);
                   3848:           if(defined($value->{'error'})) {
                   3849:               $array[0] ='Array reference error';
                   3850:               return (\@array, $string);
                   3851:           }
                   3852:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3853:           ($value, $string)=&str2arrayref($string);
                   3854:           if($value->[0] eq 'Array reference error') {
                   3855:               $array[0] ='Array reference error';
                   3856:               return (\@array, $string);
                   3857:           }
                   3858:       } else {
                   3859: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3860:       }
                   3861:       $string =~ s/^&//;
                   3862: 
                   3863:       push(@array, $value);
1.191     harris41 3864:   }
1.265     albertel 3865: 
                   3866:   $string =~ s/^__END_ARRAY_REF__//;
                   3867: 
                   3868:   return (\@array, $string);
1.168     albertel 3869: }
                   3870: 
1.167     albertel 3871: # -------------------------------------------------------------------Temp Store
                   3872: 
1.168     albertel 3873: sub tmpreset {
                   3874:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3875:   if (!$symb) {
                   3876:     $symb=&symbread();
1.620     albertel 3877:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3878:   }
                   3879:   $symb=escape($symb);
                   3880: 
1.620     albertel 3881:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3882:   $namespace=~s/\//\_/g;
                   3883:   $namespace=~s/\W//g;
                   3884: 
1.620     albertel 3885:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3886:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3887:   if ($domain eq 'public' && $stuname eq 'public') {
                   3888:       $stuname=$ENV{'REMOTE_ADDR'};
                   3889:   }
1.1117    foxr     3890:   my $path=LONCAPA::tempdir();
1.168     albertel 3891:   my %hash;
                   3892:   if (tie(%hash,'GDBM_File',
                   3893: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3894: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3895:     foreach my $key (keys(%hash)) {
1.180     albertel 3896:       if ($key=~ /:$symb/) {
1.168     albertel 3897: 	delete($hash{$key});
                   3898:       }
                   3899:     }
                   3900:   }
                   3901: }
                   3902: 
1.167     albertel 3903: sub tmpstore {
1.168     albertel 3904:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3905: 
                   3906:   if (!$symb) {
                   3907:     $symb=&symbread();
1.620     albertel 3908:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3909:   }
                   3910:   $symb=escape($symb);
                   3911: 
                   3912:   if (!$namespace) {
                   3913:     # I don't think we would ever want to store this for a course.
                   3914:     # it seems this will only be used if we don't have a course.
1.620     albertel 3915:     #$namespace=$env{'request.course.id'};
1.168     albertel 3916:     #if (!$namespace) {
1.620     albertel 3917:       $namespace=$env{'request.state'};
1.168     albertel 3918:     #}
                   3919:   }
                   3920:   $namespace=~s/\//\_/g;
                   3921:   $namespace=~s/\W//g;
1.620     albertel 3922:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3923:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3924:   if ($domain eq 'public' && $stuname eq 'public') {
                   3925:       $stuname=$ENV{'REMOTE_ADDR'};
                   3926:   }
1.168     albertel 3927:   my $now=time;
                   3928:   my %hash;
1.1117    foxr     3929:   my $path=LONCAPA::tempdir();
1.168     albertel 3930:   if (tie(%hash,'GDBM_File',
                   3931: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3932: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3933:     $hash{"version:$symb"}++;
                   3934:     my $version=$hash{"version:$symb"};
                   3935:     my $allkeys=''; 
                   3936:     foreach my $key (keys(%$storehash)) {
                   3937:       $allkeys.=$key.':';
1.591     albertel 3938:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3939:     }
                   3940:     $hash{"$version:$symb:timestamp"}=$now;
                   3941:     $allkeys.='timestamp';
                   3942:     $hash{"$version:keys:$symb"}=$allkeys;
                   3943:     if (untie(%hash)) {
                   3944:       return 'ok';
                   3945:     } else {
                   3946:       return "error:$!";
                   3947:     }
                   3948:   } else {
                   3949:     return "error:$!";
                   3950:   }
                   3951: }
1.167     albertel 3952: 
1.168     albertel 3953: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3954: 
1.168     albertel 3955: sub tmprestore {
                   3956:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3957: 
1.168     albertel 3958:   if (!$symb) {
                   3959:     $symb=&symbread();
1.620     albertel 3960:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3961:   }
                   3962:   $symb=escape($symb);
                   3963: 
1.620     albertel 3964:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3965: 
1.620     albertel 3966:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3967:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3968:   if ($domain eq 'public' && $stuname eq 'public') {
                   3969:       $stuname=$ENV{'REMOTE_ADDR'};
                   3970:   }
1.168     albertel 3971:   my %returnhash;
                   3972:   $namespace=~s/\//\_/g;
                   3973:   $namespace=~s/\W//g;
                   3974:   my %hash;
1.1117    foxr     3975:   my $path=LONCAPA::tempdir();
1.168     albertel 3976:   if (tie(%hash,'GDBM_File',
                   3977: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3978: 	  &GDBM_READER(),0640)) {
1.168     albertel 3979:     my $version=$hash{"version:$symb"};
                   3980:     $returnhash{'version'}=$version;
                   3981:     my $scope;
                   3982:     for ($scope=1;$scope<=$version;$scope++) {
                   3983:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3984:       my @keys=split(/:/,$vkeys);
                   3985:       my $key;
                   3986:       $returnhash{"$scope:keys"}=$vkeys;
                   3987:       foreach $key (@keys) {
1.591     albertel 3988: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3989: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3990:       }
                   3991:     }
1.168     albertel 3992:     if (!(untie(%hash))) {
                   3993:       return "error:$!";
                   3994:     }
                   3995:   } else {
                   3996:     return "error:$!";
                   3997:   }
                   3998:   return %returnhash;
1.167     albertel 3999: }
                   4000: 
1.9       www      4001: # ----------------------------------------------------------------------- Store
                   4002: 
                   4003: sub store {
1.124     www      4004:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4005:     my $home='';
                   4006: 
1.168     albertel 4007:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4008: 
1.213     www      4009:     $symb=&symbclean($symb);
1.122     albertel 4010:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4011: 
1.620     albertel 4012:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4013:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4014: 
                   4015:     &devalidate($symb,$stuname,$domain);
1.109     www      4016: 
                   4017:     $symb=escape($symb);
1.187     www      4018:     if (!$namespace) { 
1.620     albertel 4019:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4020:           return ''; 
                   4021:        } 
                   4022:     }
1.620     albertel 4023:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4024: 
                   4025:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4026:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4027: 
1.12      www      4028:     my $namevalue='';
1.800     albertel 4029:     foreach my $key (keys(%$storehash)) {
                   4030:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4031:     }
1.12      www      4032:     $namevalue=~s/\&$//;
1.187     www      4033:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4034:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4035: }
                   4036: 
1.47      www      4037: # -------------------------------------------------------------- Critical Store
                   4038: 
                   4039: sub cstore {
1.124     www      4040:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4041:     my $home='';
                   4042: 
1.168     albertel 4043:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4044: 
1.213     www      4045:     $symb=&symbclean($symb);
1.122     albertel 4046:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4047: 
1.620     albertel 4048:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4049:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4050: 
                   4051:     &devalidate($symb,$stuname,$domain);
1.109     www      4052: 
                   4053:     $symb=escape($symb);
1.187     www      4054:     if (!$namespace) { 
1.620     albertel 4055:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4056:           return ''; 
                   4057:        } 
                   4058:     }
1.620     albertel 4059:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4060: 
                   4061:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4062:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4063: 
1.47      www      4064:     my $namevalue='';
1.800     albertel 4065:     foreach my $key (keys(%$storehash)) {
                   4066:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4067:     }
1.47      www      4068:     $namevalue=~s/\&$//;
1.187     www      4069:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4070:     return critical
                   4071:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4072: }
                   4073: 
1.9       www      4074: # --------------------------------------------------------------------- Restore
                   4075: 
                   4076: sub restore {
1.124     www      4077:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4078:     my $home='';
                   4079: 
1.168     albertel 4080:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4081: 
1.122     albertel 4082:     if (!$symb) {
                   4083:       unless ($symb=escape(&symbread())) { return ''; }
                   4084:     } else {
1.213     www      4085:       $symb=&escape(&symbclean($symb));
1.122     albertel 4086:     }
1.188     www      4087:     if (!$namespace) { 
1.620     albertel 4088:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4089:           return ''; 
                   4090:        } 
                   4091:     }
1.620     albertel 4092:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4093:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4094:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4095:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4096: 
1.12      www      4097:     my %returnhash=();
1.800     albertel 4098:     foreach my $line (split(/\&/,$answer)) {
                   4099: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4100:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4101:     }
1.75      www      4102:     my $version;
                   4103:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4104:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4105:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4106:        }
1.75      www      4107:     }
1.13      www      4108:     return %returnhash;
1.34      www      4109: }
                   4110: 
                   4111: # ---------------------------------------------------------- Course Description
1.1118    foxr     4112: #
                   4113: #  
1.34      www      4114: 
                   4115: sub coursedescription {
1.731     albertel 4116:     my ($courseid,$args)=@_;
1.34      www      4117:     $courseid=~s/^\///;
1.49      www      4118:     $courseid=~s/\_/\//g;
1.34      www      4119:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4120:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4121:     my $normalid=$cdomain.'_'.$cnum;
                   4122:     # need to always cache even if we get errors otherwise we keep 
                   4123:     # trying and trying and trying to get the course description.
                   4124:     my %envhash=();
                   4125:     my %returnhash=();
1.731     albertel 4126:     
                   4127:     my $expiretime=600;
                   4128:     if ($env{'request.course.id'} eq $normalid) {
                   4129: 	$expiretime=120;
                   4130:     }
                   4131: 
                   4132:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4133:     if (!$args->{'freshen_cache'}
                   4134: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4135: 	foreach my $key (keys(%env)) {
                   4136: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4137: 	    my ($setting) = $1;
                   4138: 	    $returnhash{$setting} = $env{$key};
                   4139: 	}
                   4140: 	return %returnhash;
                   4141:     }
                   4142: 
1.1118    foxr     4143:     # get the data again
                   4144: 
1.731     albertel 4145:     if (!$args->{'one_time'}) {
                   4146: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4147:     }
1.811     albertel 4148: 
1.34      www      4149:     if ($chome ne 'no_host') {
1.302     albertel 4150:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4151:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4152: 	   my $username = $env{'user.name'}; # Defult username
                   4153: 	   if(defined $args->{'user'}) {
                   4154: 	       $username = $args->{'user'};
                   4155: 	   }
1.129     albertel 4156:            $returnhash{'home'}= $chome;
                   4157: 	   $returnhash{'domain'} = $cdomain;
                   4158: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4159:            if (!defined($returnhash{'type'})) {
                   4160:                $returnhash{'type'} = 'Course';
                   4161:            }
1.130     albertel 4162:            while (my ($name,$value) = each %returnhash) {
1.53      www      4163:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4164:            }
1.270     www      4165:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4166:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4167: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4168:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4169:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4170:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4171:        }
                   4172:     }
1.731     albertel 4173:     if (!$args->{'one_time'}) {
1.949     raeburn  4174: 	&appenv(\%envhash);
1.731     albertel 4175:     }
1.302     albertel 4176:     return %returnhash;
1.461     www      4177: }
                   4178: 
1.1080    raeburn  4179: sub update_released_required {
                   4180:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4181:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4182:         $cid = $env{'request.course.id'};
                   4183:         $cdom = $env{'course.'.$cid.'.domain'};
                   4184:         $cnum = $env{'course.'.$cid.'.num'};
                   4185:         $chome = $env{'course.'.$cid.'.home'};
                   4186:     }
                   4187:     if ($needsrelease) {
                   4188:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4189:         my $needsupdate;
                   4190:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4191:             $needsupdate = 1;
                   4192:         } else {
                   4193:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4194:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4195:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4196:                 $needsupdate = 1;
                   4197:             }
                   4198:         }
                   4199:         if ($needsupdate) {
                   4200:             my %needshash = (
                   4201:                              'internal.releaserequired' => $needsrelease,
                   4202:                             );
                   4203:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4204:             if ($putresult eq 'ok') {
                   4205:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4206:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4207:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4208:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4209:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4210:                 }
                   4211:             }
                   4212:         }
                   4213:     }
                   4214:     return;
                   4215: }
                   4216: 
1.461     www      4217: # -------------------------------------------------See if a user is privileged
                   4218: 
                   4219: sub privileged {
                   4220:     my ($username,$domain)=@_;
                   4221:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4222: 			&homeserver($username,$domain));
1.1033    raeburn  4223:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4224:         ($rolesdump =~ /^error:/)) {
                   4225:         return 0;
                   4226:     }
1.461     www      4227:     my $now=time;
                   4228:     if ($rolesdump ne '') {
1.800     albertel 4229:         foreach my $entry (split(/&/,$rolesdump)) {
                   4230: 	    if ($entry!~/^rolesdef_/) {
                   4231: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4232: 		$area=~s/\_\w\w$//;
                   4233: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4234: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4235: 		    my $active=1;
                   4236: 		    if ($tend) {
                   4237: 			if ($tend<$now) { $active=0; }
                   4238: 		    }
                   4239: 		    if ($tstart) {
                   4240: 			if ($tstart>$now) { $active=0; }
                   4241: 		    }
                   4242: 		    if ($active) { return 1; }
                   4243: 		}
                   4244: 	    }
                   4245: 	}
                   4246:     }
                   4247:     return 0;
1.9       www      4248: }
1.1       albertel 4249: 
1.103     harris41 4250: # -------------------------------------------------------- Get user privileges
1.11      www      4251: 
                   4252: sub rolesinit {
                   4253:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4254:     my $now=time;
                   4255:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4256:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4257:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4258:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4259:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4260:         return \%userroles;
                   4261:     }
1.11      www      4262:     my %allroles=();
1.678     raeburn  4263:     my %allgroups=();   
1.11      www      4264: 
                   4265:     if ($rolesdump ne '') {
1.800     albertel 4266:         foreach my $entry (split(/&/,$rolesdump)) {
                   4267: 	  if ($entry!~/^rolesdef_/) {
                   4268:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4269: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4270:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4271: 	    if ($role=~/^cr/) { 
1.807     albertel 4272: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4273: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4274: 		    ($tend,$tstart)=split('_',$trest);
                   4275: 		} else {
                   4276: 		    $trole=$role;
                   4277: 		}
1.678     raeburn  4278:             } elsif ($role =~ m|^gr/|) {
                   4279:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4280:                 next if ($tstart eq '-1');
1.678     raeburn  4281:                 ($trole,$group_privs) = split(/\//,$trole);
                   4282:                 $group_privs = &unescape($group_privs);
1.587     albertel 4283: 	    } else {
                   4284: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4285: 	    }
1.743     albertel 4286: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4287: 					 $username);
                   4288: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4289:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4290:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4291:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4292: 		my $spec=$trole.'.'.$area;
                   4293: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4294: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4295:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4296:                 } elsif ($trole eq 'gr') {
                   4297:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4298: 		} else {
1.567     raeburn  4299:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4300: 		}
1.12      www      4301:             }
1.662     raeburn  4302:           }
1.191     harris41 4303:         }
1.743     albertel 4304:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4305:         $userroles{'user.adv'}    = $adv;
                   4306: 	$userroles{'user.author'} = $author;
1.620     albertel 4307:         $env{'user.adv'}=$adv;
1.11      www      4308:     }
1.743     albertel 4309:     return \%userroles;  
1.11      www      4310: }
                   4311: 
1.567     raeburn  4312: sub set_arearole {
                   4313:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4314: # log the associated role with the area
                   4315:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4316:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4317: }
                   4318: 
                   4319: sub custom_roleprivs {
                   4320:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4321:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4322:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4323:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4324:         my ($rdummy,$roledef)=
                   4325:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4326:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4327:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4328:             if (defined($syspriv)) {
1.1043    raeburn  4329:                 if ($trest =~ /^$match_community$/) {
                   4330:                     $syspriv =~ s/bre\&S//; 
                   4331:                 }
1.567     raeburn  4332:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4333:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4334:             }
                   4335:             if ($tdomain ne '') {
                   4336:                 if (defined($dompriv)) {
                   4337:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4338:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4339:                 }
                   4340:                 if (($trest ne '') && (defined($coursepriv))) {
                   4341:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4342:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4343:                 }
                   4344:             }
                   4345:         }
                   4346:     }
                   4347: }
                   4348: 
1.678     raeburn  4349: sub group_roleprivs {
                   4350:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4351:     my $access = 1;
                   4352:     my $now = time;
                   4353:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4354:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4355:     if ($access) {
1.811     albertel 4356:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4357:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4358:     }
                   4359: }
1.567     raeburn  4360: 
                   4361: sub standard_roleprivs {
                   4362:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4363:     if (defined($pr{$trole.':s'})) {
                   4364:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4365:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4366:     }
                   4367:     if ($tdomain ne '') {
                   4368:         if (defined($pr{$trole.':d'})) {
                   4369:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4370:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4371:         }
                   4372:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4373:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4374:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4375:         }
                   4376:     }
                   4377: }
                   4378: 
                   4379: sub set_userprivs {
1.1064    raeburn  4380:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4381:     my $author=0;
                   4382:     my $adv=0;
1.678     raeburn  4383:     my %grouproles = ();
                   4384:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4385:         my @groupkeys; 
1.1000    raeburn  4386:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4387:             push(@groupkeys,$role);
                   4388:         }
                   4389:         if (ref($groups_roles) eq 'HASH') {
                   4390:             foreach my $key (keys(%{$groups_roles})) {
                   4391:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4392:                     push(@groupkeys,$key);
                   4393:                 }
                   4394:             }
                   4395:         }
                   4396:         if (@groupkeys > 0) {
                   4397:             foreach my $role (@groupkeys) {
                   4398:                 my ($trole,$area,$sec,$extendedarea);
                   4399:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4400:                     $trole = $1;
                   4401:                     $area = $2;
                   4402:                     $sec = $3;
                   4403:                     $extendedarea = $area.$sec;
                   4404:                     if (exists($$allgroups{$area})) {
                   4405:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4406:                             my $spec = $trole.'.'.$extendedarea;
                   4407:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4408:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4409:                         }
1.678     raeburn  4410:                     }
                   4411:                 }
                   4412:             }
                   4413:         }
                   4414:     }
1.800     albertel 4415:     foreach my $group (keys(%grouproles)) {
                   4416:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4417:     }
1.800     albertel 4418:     foreach my $role (keys(%{$allroles})) {
                   4419:         my %thesepriv;
1.941     raeburn  4420:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4421:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4422:             if ($item ne '') {
                   4423:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4424:                 if ($restrictions eq '') {
                   4425:                     $thesepriv{$privilege}='F';
                   4426:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4427:                     $thesepriv{$privilege}.=$restrictions;
                   4428:                 }
                   4429:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4430:             }
                   4431:         }
                   4432:         my $thesestr='';
1.1104    raeburn  4433:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4434: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4435: 	}
                   4436:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4437:     }
                   4438:     return ($author,$adv);
                   4439: }
                   4440: 
1.994     raeburn  4441: sub role_status {
1.1104    raeburn  4442:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4443:     my @pwhere = ();
                   4444:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4445:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4446:         unless (!defined($$role) || $$role eq '') {
                   4447:             $$where=join('.',@pwhere);
                   4448:             $$trolecode=$$role.'.'.$$where;
                   4449:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4450:             $$tstatus='is';
1.1104    raeburn  4451:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4452:                 $$tstatus='future';
1.1034    raeburn  4453:                 if ($$tstart<$now) {
                   4454:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4455:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4456:                             my (%allroles,%allgroups,$group_privs,
                   4457:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4458:                             my %userroles = (
                   4459:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4460:                             );
1.1064    raeburn  4461:                             @rolecodes = ('cm'); 
1.1002    raeburn  4462:                             my $spec=$$role.'.'.$$where;
                   4463:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4464:                             if ($$role =~ /^cr\//) {
                   4465:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4466:                                 push(@rolecodes,'cr');
1.1002    raeburn  4467:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4468:                                 push(@rolecodes,$$role);
1.1002    raeburn  4469:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4470:                                                     $env{'user.name'});
1.1064    raeburn  4471:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4472:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4473:                                 $group_privs = &unescape($group_privs);
                   4474:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4475:                                 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  4476:                                 &get_groups_roles($tdomain,$trest,
                   4477:                                                   \%course_roles,\@rolecodes,
                   4478:                                                   \%groups_roles);
1.1002    raeburn  4479:                             } else {
1.1064    raeburn  4480:                                 push(@rolecodes,$$role);
1.1002    raeburn  4481:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4482:                             }
1.1064    raeburn  4483:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4484:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4485:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4486:                         }
                   4487:                     }
1.1034    raeburn  4488:                     $$tstatus = 'is';
1.1002    raeburn  4489:                 }
1.994     raeburn  4490:             }
                   4491:             if ($$tend) {
1.1104    raeburn  4492:                 if ($$tend<$update) {
1.994     raeburn  4493:                     $$tstatus='expired';
                   4494:                 } elsif ($$tend<$now) {
                   4495:                     $$tstatus='will_not';
                   4496:                 }
                   4497:             }
                   4498:         }
                   4499:     }
                   4500: }
                   4501: 
1.1104    raeburn  4502: sub get_groups_roles {
                   4503:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4504:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4505:                   (ref($rolecodes) eq 'ARRAY') && 
                   4506:                   (ref($groups_roles) eq 'HASH')); 
                   4507:     if (keys(%{$cdom_courseroles}) > 0) {
                   4508:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4509:         if ($cdom ne '' && $cnum ne '') {
                   4510:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4511:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4512:                     my $crsrole = $1;
                   4513:                     my $crssec = $2;
                   4514:                     if ($crsrole =~ /^cr/) {
                   4515:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4516:                             push(@{$rolecodes},'cr');
                   4517:                         }
                   4518:                     } else {
                   4519:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4520:                             push(@{$rolecodes},$crsrole);
                   4521:                         }
                   4522:                     }
                   4523:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4524:                     if ($crssec ne '') {
                   4525:                         $rolekey .= "/$crssec";
                   4526:                     }
                   4527:                     $rolekey .= './';
                   4528:                     $groups_roles->{$rolekey} = $rolecodes;
                   4529:                 }
                   4530:             }
                   4531:         }
                   4532:     }
                   4533:     return;
                   4534: }
                   4535: 
                   4536: sub delete_env_groupprivs {
                   4537:     my ($where,$courseroles,$possroles) = @_;
                   4538:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4539:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4540:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4541:         %{$courseroles->{$udom}} =
                   4542:             &get_my_roles('','','userroles',['active'],
                   4543:                           $possroles,[$udom],1);
                   4544:     }
                   4545:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4546:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4547:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4548:             my $area = '/'.$cdom.'/'.$cnum;
                   4549:             my $privkey = "user.priv.$crsrole.$area";
                   4550:             if ($crssec ne '') {
                   4551:                 $privkey .= '/'.$crssec;
                   4552:             }
                   4553:             $privkey .= ".$area/$group";
                   4554:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4555:         }
                   4556:     }
                   4557:     return;
                   4558: }
                   4559: 
1.994     raeburn  4560: sub check_adhoc_privs {
1.1104    raeburn  4561:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4562:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4563:     if ($env{$cckey}) {
                   4564:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4565:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4566:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4567:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4568:         }
                   4569:     } else {
1.1088    raeburn  4570:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4571:     }
                   4572: }
                   4573: 
                   4574: sub set_adhoc_privileges {
                   4575: # role can be cc or ca
1.1088    raeburn  4576:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4577:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4578:     my $spec = $role.'.'.$area;
                   4579:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4580:                                   $env{'user.name'});
                   4581:     my %ccrole = ();
                   4582:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4583:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4584:     &appenv(\%userroles,[$role,'cm']);
                   4585:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4586:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4587:         &appenv( {'request.role'        => $spec,
                   4588:                   'request.role.domain' => $dcdom,
                   4589:                   'request.course.sec'  => ''
                   4590:                  }
                   4591:                );
                   4592:         my $tadv=0;
                   4593:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4594:         &appenv({'request.role.adv'    => $tadv});
                   4595:     }
1.994     raeburn  4596: }
                   4597: 
1.12      www      4598: # --------------------------------------------------------------- get interface
                   4599: 
                   4600: sub get {
1.131     albertel 4601:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4602:    my $items='';
1.800     albertel 4603:    foreach my $item (@$storearr) {
                   4604:        $items.=&escape($item).'&';
1.191     harris41 4605:    }
1.12      www      4606:    $items=~s/\&$//;
1.620     albertel 4607:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4608:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4609:    my $uhome=&homeserver($uname,$udomain);
                   4610: 
1.133     albertel 4611:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4612:    my @pairs=split(/\&/,$rep);
1.273     albertel 4613:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4614:      return @pairs;
                   4615:    }
1.15      www      4616:    my %returnhash=();
1.42      www      4617:    my $i=0;
1.800     albertel 4618:    foreach my $item (@$storearr) {
                   4619:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4620:       $i++;
1.191     harris41 4621:    }
1.15      www      4622:    return %returnhash;
1.27      www      4623: }
                   4624: 
                   4625: # --------------------------------------------------------------- del interface
                   4626: 
                   4627: sub del {
1.133     albertel 4628:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4629:    my $items='';
1.800     albertel 4630:    foreach my $item (@$storearr) {
                   4631:        $items.=&escape($item).'&';
1.191     harris41 4632:    }
1.984     neumanie 4633: 
1.27      www      4634:    $items=~s/\&$//;
1.620     albertel 4635:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4636:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4637:    my $uhome=&homeserver($uname,$udomain);
                   4638:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4639: }
                   4640: 
                   4641: # -------------------------------------------------------------- dump interface
                   4642: 
                   4643: sub dump {
1.1086    raeburn  4644:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4645:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4646:     if (!$uname) { $uname=$env{'user.name'}; }
                   4647:     my $uhome=&homeserver($uname,$udomain);
                   4648:     if ($regexp) {
                   4649: 	$regexp=&escape($regexp);
                   4650:     } else {
                   4651: 	$regexp='.';
                   4652:     }
1.1086    raeburn  4653:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4654:     my @pairs=split(/\&/,$rep);
                   4655:     my %returnhash=();
1.1098    foxr     4656:     if (!($rep =~ /^error/ )) {
                   4657: 	foreach my $item (@pairs) {
                   4658: 	    my ($key,$value)=split(/=/,$item,2);
                   4659: 	    $key = &unescape($key);
                   4660: 	    next if ($key =~ /^error: 2 /);
                   4661: 	    $returnhash{$key}=&thaw_unescape($value);
                   4662: 	}
1.755     albertel 4663:     }
                   4664:     return %returnhash;
1.407     www      4665: }
                   4666: 
1.1098    foxr     4667: 
1.717     albertel 4668: # --------------------------------------------------------- dumpstore interface
                   4669: 
                   4670: sub dumpstore {
                   4671:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4672:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4673:    if (!$uname) { $uname=$env{'user.name'}; }
                   4674:    my $uhome=&homeserver($uname,$udomain);
                   4675:    if ($regexp) {
                   4676:        $regexp=&escape($regexp);
                   4677:    } else {
                   4678:        $regexp='.';
                   4679:    }
                   4680:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4681:    my @pairs=split(/\&/,$rep);
                   4682:    my %returnhash=();
                   4683:    foreach my $item (@pairs) {
                   4684:        my ($key,$value)=split(/=/,$item,2);
                   4685:        next if ($key =~ /^error: 2 /);
                   4686:        $returnhash{$key}=&thaw_unescape($value);
                   4687:    }
                   4688:    return %returnhash;
1.717     albertel 4689: }
                   4690: 
1.407     www      4691: # -------------------------------------------------------------- keys interface
                   4692: 
                   4693: sub getkeys {
                   4694:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4695:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4696:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4697:    my $uhome=&homeserver($uname,$udomain);
                   4698:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4699:    my @keyarray=();
1.800     albertel 4700:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4701:       next if ($key =~ /^error: 2 /);
1.800     albertel 4702:       push(@keyarray,&unescape($key));
1.407     www      4703:    }
                   4704:    return @keyarray;
1.318     matthew  4705: }
                   4706: 
1.319     matthew  4707: # --------------------------------------------------------------- currentdump
                   4708: sub currentdump {
1.328     matthew  4709:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4710:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4711:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4712:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4713:    my $uhome = &homeserver($sname,$sdom);
                   4714:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4715:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4716:    #
1.318     matthew  4717:    my %returnhash=();
1.319     matthew  4718:    #
                   4719:    if ($rep eq "unknown_cmd") { 
                   4720:        # an old lond will not know currentdump
                   4721:        # Do a dump and make it look like a currentdump
1.822     albertel 4722:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4723:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4724:        my %hash = @tmp;
                   4725:        @tmp=();
1.424     matthew  4726:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4727:    } else {
                   4728:        my @pairs=split(/\&/,$rep);
1.800     albertel 4729:        foreach my $pair (@pairs) {
                   4730:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4731:            my ($symb,$param) = split(/:/,$key);
                   4732:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4733:                                                         &thaw_unescape($value);
1.319     matthew  4734:        }
1.191     harris41 4735:    }
1.12      www      4736:    return %returnhash;
1.424     matthew  4737: }
                   4738: 
                   4739: sub convert_dump_to_currentdump{
                   4740:     my %hash = %{shift()};
                   4741:     my %returnhash;
                   4742:     # Code ripped from lond, essentially.  The only difference
                   4743:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4744:     # we might run in to problems with parameter names =~ /^v\./
                   4745:     while (my ($key,$value) = each(%hash)) {
                   4746:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4747: 	$symb  = &unescape($symb);
                   4748: 	$param = &unescape($param);
1.424     matthew  4749:         next if ($v eq 'version' || $symb eq 'keys');
                   4750:         next if (exists($returnhash{$symb}) &&
                   4751:                  exists($returnhash{$symb}->{$param}) &&
                   4752:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4753:         $returnhash{$symb}->{$param}=$value;
                   4754:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4755:     }
                   4756:     #
                   4757:     # Remove all of the keys in the hashes which keep track of
                   4758:     # the version of the parameter.
                   4759:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4760:         # use a foreach because we are going to delete from the hash.
                   4761:         foreach my $key (keys(%$param_hash)) {
                   4762:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4763:         }
                   4764:     }
                   4765:     return \%returnhash;
1.12      www      4766: }
                   4767: 
1.627     albertel 4768: # ------------------------------------------------------ critical inc interface
                   4769: 
                   4770: sub cinc {
                   4771:     return &inc(@_,'critical');
                   4772: }
                   4773: 
1.449     matthew  4774: # --------------------------------------------------------------- inc interface
                   4775: 
                   4776: sub inc {
1.627     albertel 4777:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4778:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4779:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4780:     my $uhome=&homeserver($uname,$udomain);
                   4781:     my $items='';
                   4782:     if (! ref($store)) {
                   4783:         # got a single value, so use that instead
                   4784:         $items = &escape($store).'=&';
                   4785:     } elsif (ref($store) eq 'SCALAR') {
                   4786:         $items = &escape($$store).'=&';        
                   4787:     } elsif (ref($store) eq 'ARRAY') {
                   4788:         $items = join('=&',map {&escape($_);} @{$store});
                   4789:     } elsif (ref($store) eq 'HASH') {
                   4790:         while (my($key,$value) = each(%{$store})) {
                   4791:             $items.= &escape($key).'='.&escape($value).'&';
                   4792:         }
                   4793:     }
                   4794:     $items=~s/\&$//;
1.627     albertel 4795:     if ($critical) {
                   4796: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4797:     } else {
                   4798: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4799:     }
1.449     matthew  4800: }
                   4801: 
1.12      www      4802: # --------------------------------------------------------------- put interface
                   4803: 
                   4804: sub put {
1.134     albertel 4805:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4806:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4807:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4808:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4809:    my $items='';
1.800     albertel 4810:    foreach my $item (keys(%$storehash)) {
                   4811:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4812:    }
1.12      www      4813:    $items=~s/\&$//;
1.134     albertel 4814:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4815: }
                   4816: 
1.631     albertel 4817: # ------------------------------------------------------------ newput interface
                   4818: 
                   4819: sub newput {
                   4820:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4821:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4822:    if (!$uname) { $uname=$env{'user.name'}; }
                   4823:    my $uhome=&homeserver($uname,$udomain);
                   4824:    my $items='';
                   4825:    foreach my $key (keys(%$storehash)) {
                   4826:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4827:    }
                   4828:    $items=~s/\&$//;
                   4829:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4830: }
                   4831: 
                   4832: # ---------------------------------------------------------  putstore interface
                   4833: 
1.524     raeburn  4834: sub putstore {
1.715     albertel 4835:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4836:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4837:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4838:    my $uhome=&homeserver($uname,$udomain);
                   4839:    my $items='';
1.715     albertel 4840:    foreach my $key (keys(%$storehash)) {
                   4841:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4842:    }
1.715     albertel 4843:    $items=~s/\&$//;
1.716     albertel 4844:    my $esc_symb=&escape($symb);
                   4845:    my $esc_v=&escape($version);
1.715     albertel 4846:    my $reply =
1.716     albertel 4847:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4848: 	      $uhome);
                   4849:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4850:        # gfall back to way things use to be done
1.715     albertel 4851:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4852: 			    $uname);
1.524     raeburn  4853:    }
1.715     albertel 4854:    return $reply;
                   4855: }
                   4856: 
                   4857: sub old_putstore {
1.716     albertel 4858:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4859:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4860:     if (!$uname) { $uname=$env{'user.name'}; }
                   4861:     my $uhome=&homeserver($uname,$udomain);
                   4862:     my %newstorehash;
1.800     albertel 4863:     foreach my $item (keys(%$storehash)) {
                   4864: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4865: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4866:     }
                   4867:     my $items='';
                   4868:     my %allitems = ();
1.800     albertel 4869:     foreach my $item (keys(%newstorehash)) {
                   4870: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4871: 	    my $key = $1.':keys:'.$2;
                   4872: 	    $allitems{$key} .= $3.':';
                   4873: 	}
1.800     albertel 4874: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4875:     }
1.800     albertel 4876:     foreach my $item (keys(%allitems)) {
                   4877: 	$allitems{$item} =~ s/\:$//;
                   4878: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4879:     }
                   4880:     $items=~s/\&$//;
                   4881:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4882: }
                   4883: 
1.47      www      4884: # ------------------------------------------------------ critical put interface
                   4885: 
                   4886: sub cput {
1.134     albertel 4887:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4888:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4889:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4890:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4891:    my $items='';
1.800     albertel 4892:    foreach my $item (keys(%$storehash)) {
                   4893:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4894:    }
1.47      www      4895:    $items=~s/\&$//;
1.134     albertel 4896:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4897: }
                   4898: 
                   4899: # -------------------------------------------------------------- eget interface
                   4900: 
                   4901: sub eget {
1.133     albertel 4902:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4903:    my $items='';
1.800     albertel 4904:    foreach my $item (@$storearr) {
                   4905:        $items.=&escape($item).'&';
1.191     harris41 4906:    }
1.12      www      4907:    $items=~s/\&$//;
1.620     albertel 4908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4909:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4910:    my $uhome=&homeserver($uname,$udomain);
                   4911:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4912:    my @pairs=split(/\&/,$rep);
                   4913:    my %returnhash=();
1.42      www      4914:    my $i=0;
1.800     albertel 4915:    foreach my $item (@$storearr) {
                   4916:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4917:       $i++;
1.191     harris41 4918:    }
1.12      www      4919:    return %returnhash;
                   4920: }
                   4921: 
1.667     albertel 4922: # ------------------------------------------------------------ tmpput interface
                   4923: sub tmpput {
1.802     raeburn  4924:     my ($storehash,$server,$context)=@_;
1.667     albertel 4925:     my $items='';
1.800     albertel 4926:     foreach my $item (keys(%$storehash)) {
                   4927: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4928:     }
                   4929:     $items=~s/\&$//;
1.802     raeburn  4930:     if (defined($context)) {
                   4931:         $items .= ':'.&escape($context);
                   4932:     }
1.667     albertel 4933:     return &reply("tmpput:$items",$server);
                   4934: }
                   4935: 
                   4936: # ------------------------------------------------------------ tmpget interface
                   4937: sub tmpget {
1.688     albertel 4938:     my ($token,$server)=@_;
                   4939:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4940:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4941:     my %returnhash;
                   4942:     foreach my $item (split(/\&/,$rep)) {
                   4943: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4944:         next if ($key =~ /^error: 2 /);
1.667     albertel 4945: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4946:     }
                   4947:     return %returnhash;
                   4948: }
                   4949: 
1.1113    raeburn  4950: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4951: sub tmpdel {
                   4952:     my ($token,$server)=@_;
                   4953:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4954:     return &reply("tmpdel:$token",$server);
                   4955: }
                   4956: 
1.765     albertel 4957: # -------------------------------------------------- portfolio access checking
                   4958: 
                   4959: sub portfolio_access {
1.766     albertel 4960:     my ($requrl) = @_;
1.765     albertel 4961:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4962:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4963:     if ($result) {
                   4964:         my %setters;
                   4965:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4966:             my ($startblock,$endblock) =
                   4967:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4968:             if ($startblock && $endblock) {
                   4969:                 return 'B';
                   4970:             }
                   4971:         } else {
                   4972:             my ($startblock,$endblock) =
                   4973:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4974:             if ($startblock && $endblock) {
                   4975:                 return 'B';
                   4976:             }
                   4977:         }
                   4978:     }
1.765     albertel 4979:     if ($result eq 'ok') {
1.766     albertel 4980:        return 'F';
1.765     albertel 4981:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4982:        return 'A';
1.765     albertel 4983:     }
1.766     albertel 4984:     return '';
1.765     albertel 4985: }
                   4986: 
                   4987: sub get_portfolio_access {
1.767     albertel 4988:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4989: 
                   4990:     if (!ref($access_hash)) {
                   4991: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4992: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4993: 						   $file_name);
                   4994: 	$access_hash = $access_controls{$file_name};
                   4995:     }
                   4996: 
1.765     albertel 4997:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4998:     my $now = time;
                   4999:     if (ref($access_hash) eq 'HASH') {
                   5000:         foreach my $key (keys(%{$access_hash})) {
                   5001:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5002:             if ($start > $now) {
                   5003:                 next;
                   5004:             }
                   5005:             if ($end && $end<$now) {
                   5006:                 next;
                   5007:             }
                   5008:             if ($scope eq 'public') {
                   5009:                 $public = $key;
                   5010:                 last;
                   5011:             } elsif ($scope eq 'guest') {
                   5012:                 $guest = $key;
                   5013:             } elsif ($scope eq 'domains') {
                   5014:                 push(@domains,$key);
                   5015:             } elsif ($scope eq 'users') {
                   5016:                 push(@users,$key);
                   5017:             } elsif ($scope eq 'course') {
                   5018:                 push(@courses,$key);
                   5019:             } elsif ($scope eq 'group') {
                   5020:                 push(@groups,$key);
                   5021:             }
                   5022:         }
                   5023:         if ($public) {
                   5024:             return 'ok';
                   5025:         }
                   5026:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5027:             if ($guest) {
                   5028:                 return $guest;
                   5029:             }
                   5030:         } else {
                   5031:             if (@domains > 0) {
                   5032:                 foreach my $domkey (@domains) {
                   5033:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5034:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5035:                             return 'ok';
                   5036:                         }
                   5037:                     }
                   5038:                 }
                   5039:             }
                   5040:             if (@users > 0) {
                   5041:                 foreach my $userkey (@users) {
1.865     raeburn  5042:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5043:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5044:                             if (ref($item) eq 'HASH') {
                   5045:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5046:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5047:                                     return 'ok';
                   5048:                                 }
                   5049:                             }
                   5050:                         }
                   5051:                     } 
1.765     albertel 5052:                 }
                   5053:             }
                   5054:             my %roleshash;
                   5055:             my @courses_and_groups = @courses;
                   5056:             push(@courses_and_groups,@groups); 
                   5057:             if (@courses_and_groups > 0) {
                   5058:                 my (%allgroups,%allroles); 
                   5059:                 my ($start,$end,$role,$sec,$group);
                   5060:                 foreach my $envkey (%env) {
1.1060    raeburn  5061:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5062:                         my $cid = $2.'_'.$3; 
                   5063:                         if ($1 eq 'gr') {
                   5064:                             $group = $4;
                   5065:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5066:                         } else {
                   5067:                             if ($4 eq '') {
                   5068:                                 $sec = 'none';
                   5069:                             } else {
                   5070:                                 $sec = $4;
                   5071:                             }
                   5072:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5073:                         }
1.811     albertel 5074:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5075:                         my $cid = $2.'_'.$3;
                   5076:                         if ($4 eq '') {
                   5077:                             $sec = 'none';
                   5078:                         } else {
                   5079:                             $sec = $4;
                   5080:                         }
                   5081:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5082:                     }
                   5083:                 }
                   5084:                 if (keys(%allroles) == 0) {
                   5085:                     return;
                   5086:                 }
                   5087:                 foreach my $key (@courses_and_groups) {
                   5088:                     my %content = %{$$access_hash{$key}};
                   5089:                     my $cnum = $content{'number'};
                   5090:                     my $cdom = $content{'domain'};
                   5091:                     my $cid = $cdom.'_'.$cnum;
                   5092:                     if (!exists($allroles{$cid})) {
                   5093:                         next;
                   5094:                     }    
                   5095:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5096:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5097:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5098:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5099:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5100:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5101:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5102:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5103:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5104:                                         if (grep/^all$/,@sections) {
                   5105:                                             return 'ok';
                   5106:                                         } else {
                   5107:                                             if (grep/^$sec$/,@sections) {
                   5108:                                                 return 'ok';
                   5109:                                             }
                   5110:                                         }
                   5111:                                     }
                   5112:                                 }
                   5113:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5114:                                     if (grep/^none$/,@groups) {
                   5115:                                         return 'ok';
                   5116:                                     }
                   5117:                                 } else {
                   5118:                                     if (grep/^all$/,@groups) {
                   5119:                                         return 'ok';
                   5120:                                     } 
                   5121:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5122:                                         if (grep/^$group$/,@groups) {
                   5123:                                             return 'ok';
                   5124:                                         }
                   5125:                                     }
                   5126:                                 } 
                   5127:                             }
                   5128:                         }
                   5129:                     }
                   5130:                 }
                   5131:             }
                   5132:             if ($guest) {
                   5133:                 return $guest;
                   5134:             }
                   5135:         }
                   5136:     }
                   5137:     return;
                   5138: }
                   5139: 
                   5140: sub course_group_datechecker {
                   5141:     my ($dates,$now,$status) = @_;
                   5142:     my ($start,$end) = split(/\./,$dates);
                   5143:     if (!$start && !$end) {
                   5144:         return 'ok';
                   5145:     }
                   5146:     if (grep/^active$/,@{$status}) {
                   5147:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5148:             return 'ok';
                   5149:         }
                   5150:     }
                   5151:     if (grep/^previous$/,@{$status}) {
                   5152:         if ($end > $now ) {
                   5153:             return 'ok';
                   5154:         }
                   5155:     }
                   5156:     if (grep/^future$/,@{$status}) {
                   5157:         if ($start > $now) {
                   5158:             return 'ok';
                   5159:         }
                   5160:     }
                   5161:     return; 
                   5162: }
                   5163: 
                   5164: sub parse_portfolio_url {
                   5165:     my ($url) = @_;
                   5166: 
                   5167:     my ($type,$udom,$unum,$group,$file_name);
                   5168:     
1.823     albertel 5169:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5170: 	$type = 1;
                   5171:         $udom = $1;
                   5172:         $unum = $2;
                   5173:         $file_name = $3;
1.823     albertel 5174:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5175: 	$type = 2;
                   5176:         $udom = $1;
                   5177:         $unum = $2;
                   5178:         $group = $3;
                   5179:         $file_name = $3.'/'.$4;
                   5180:     }
                   5181:     if (wantarray) {
                   5182: 	return ($type,$udom,$unum,$file_name,$group);
                   5183:     }
                   5184:     return $type;
                   5185: }
                   5186: 
                   5187: sub is_portfolio_url {
                   5188:     my ($url) = @_;
                   5189:     return scalar(&parse_portfolio_url($url));
                   5190: }
                   5191: 
1.798     raeburn  5192: sub is_portfolio_file {
                   5193:     my ($file) = @_;
1.820     raeburn  5194:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5195:         return 1;
                   5196:     }
                   5197:     return;
                   5198: }
                   5199: 
1.976     raeburn  5200: sub usertools_access {
1.1084    raeburn  5201:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5202:     my ($access,%tools);
                   5203:     if ($context eq '') {
                   5204:         $context = 'tools';
                   5205:     }
                   5206:     if ($context eq 'requestcourses') {
                   5207:         %tools = (
                   5208:                       official   => 1,
                   5209:                       unofficial => 1,
1.1006    raeburn  5210:                       community  => 1,
1.985     raeburn  5211:                  );
                   5212:     } else {
                   5213:         %tools = (
                   5214:                       aboutme   => 1,
                   5215:                       blog      => 1,
                   5216:                       portfolio => 1,
                   5217:                  );
                   5218:     }
1.976     raeburn  5219:     return if (!defined($tools{$tool}));
                   5220: 
                   5221:     if ((!defined($udom)) || (!defined($uname))) {
                   5222:         $udom = $env{'user.domain'};
                   5223:         $uname = $env{'user.name'};
                   5224:     }
                   5225: 
1.978     raeburn  5226:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5227:         if ($action ne 'reload') {
1.985     raeburn  5228:             if ($context eq 'requestcourses') {
                   5229:                 return $env{'environment.canrequest.'.$tool};
                   5230:             } else {
                   5231:                 return $env{'environment.availabletools.'.$tool};
                   5232:             }
                   5233:         }
1.976     raeburn  5234:     }
                   5235: 
                   5236:     my ($toolstatus,$inststatus);
                   5237: 
1.985     raeburn  5238:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5239:          ($action ne 'reload')) {
                   5240:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5241:         $inststatus = $env{'environment.inststatus'};
                   5242:     } else {
1.1084    raeburn  5243:         if (ref($userenvref) eq 'HASH') {
                   5244:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5245:             $inststatus = $userenvref->{'inststatus'};
                   5246:         } else {
                   5247:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5248:             $toolstatus = $userenv{$context.'.'.$tool};
                   5249:             $inststatus = $userenv{'inststatus'};
                   5250:         }
1.976     raeburn  5251:     }
                   5252: 
                   5253:     if ($toolstatus ne '') {
                   5254:         if ($toolstatus) {
                   5255:             $access = 1;
                   5256:         } else {
                   5257:             $access = 0;
                   5258:         }
                   5259:         return $access;
                   5260:     }
                   5261: 
1.1084    raeburn  5262:     my ($is_adv,%domdef);
                   5263:     if (ref($is_advref) eq 'HASH') {
                   5264:         $is_adv = $is_advref->{'is_adv'};
                   5265:     } else {
                   5266:         $is_adv = &is_advanced_user($udom,$uname);
                   5267:     }
                   5268:     if (ref($domdefref) eq 'HASH') {
                   5269:         %domdef = %{$domdefref};
                   5270:     } else {
                   5271:         %domdef = &get_domain_defaults($udom);
                   5272:     }
1.976     raeburn  5273:     if (ref($domdef{$tool}) eq 'HASH') {
                   5274:         if ($is_adv) {
                   5275:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5276:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5277:                     $access = 1;
                   5278:                 } else {
                   5279:                     $access = 0;
                   5280:                 }
                   5281:                 return $access;
                   5282:             }
                   5283:         }
                   5284:         if ($inststatus ne '') {
                   5285:             my ($hasaccess,$hasnoaccess);
                   5286:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5287:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5288:                     if ($domdef{$tool}{$affiliation}) {
                   5289:                         $hasaccess = 1;
                   5290:                     } else {
                   5291:                         $hasnoaccess = 1;
                   5292:                     }
                   5293:                 }
                   5294:             }
                   5295:             if ($hasaccess || $hasnoaccess) {
                   5296:                 if ($hasaccess) {
                   5297:                     $access = 1;
                   5298:                 } elsif ($hasnoaccess) {
                   5299:                     $access = 0; 
                   5300:                 }
                   5301:                 return $access;
                   5302:             }
                   5303:         } else {
                   5304:             if ($domdef{$tool}{'default'} ne '') {
                   5305:                 if ($domdef{$tool}{'default'}) {
                   5306:                     $access = 1;
                   5307:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5308:                     $access = 0;
                   5309:                 }
                   5310:                 return $access;
                   5311:             }
                   5312:         }
                   5313:     } else {
1.985     raeburn  5314:         if ($context eq 'tools') {
                   5315:             $access = 1;
                   5316:         } else {
                   5317:             $access = 0;
                   5318:         }
1.976     raeburn  5319:         return $access;
                   5320:     }
                   5321: }
                   5322: 
1.1050    raeburn  5323: sub is_course_owner {
                   5324:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5325:     if (($udom eq '') || ($uname eq '')) {
                   5326:         $udom = $env{'user.domain'};
                   5327:         $uname = $env{'user.name'};
                   5328:     }
                   5329:     unless (($udom eq '') || ($uname eq '')) {
                   5330:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5331:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5332:                 return 1;
                   5333:             } else {
                   5334:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5335:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5336:                     return 1;
                   5337:                 }
                   5338:             }
                   5339:         }
                   5340:     }
                   5341:     return;
                   5342: }
                   5343: 
1.976     raeburn  5344: sub is_advanced_user {
                   5345:     my ($udom,$uname) = @_;
1.1085    raeburn  5346:     if ($udom ne '' && $uname ne '') {
                   5347:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5348:             return $env{'user.adv'};  
                   5349:         }
                   5350:     }
1.976     raeburn  5351:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5352:     my %allroles;
                   5353:     my $is_adv;
                   5354:     foreach my $role (keys(%roleshash)) {
                   5355:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5356:         my $area = '/'.$tdomain.'/'.$trest;
                   5357:         if ($sec ne '') {
                   5358:             $area .= '/'.$sec;
                   5359:         }
                   5360:         if (($area ne '') && ($trole ne '')) {
                   5361:             my $spec=$trole.'.'.$area;
                   5362:             if ($trole =~ /^cr\//) {
                   5363:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5364:             } elsif ($trole ne 'gr') {
                   5365:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5366:             }
                   5367:         }
                   5368:     }
                   5369:     foreach my $role (keys(%allroles)) {
                   5370:         last if ($is_adv);
                   5371:         foreach my $item (split(/:/,$allroles{$role})) {
                   5372:             if ($item ne '') {
                   5373:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5374:                 if ($privilege eq 'adv') {
                   5375:                     $is_adv = 1;
                   5376:                     last;
                   5377:                 }
                   5378:             }
                   5379:         }
                   5380:     }
                   5381:     return $is_adv;
                   5382: }
1.798     raeburn  5383: 
1.1035    raeburn  5384: sub check_can_request {
1.1036    raeburn  5385:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5386:     my $canreq = 0;
                   5387:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5388:     my @options = ('approval','validate','autolimit');
                   5389:     my $optregex = join('|',@options);
                   5390:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5391:         foreach my $type (@{$types}) {
                   5392:             if (&usertools_access($env{'user.name'},
                   5393:                                   $env{'user.domain'},
                   5394:                                   $type,undef,'requestcourses')) {
                   5395:                 $canreq ++;
1.1036    raeburn  5396:                 if (ref($request_domains) eq 'HASH') {
                   5397:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5398:                 }
1.1035    raeburn  5399:                 if ($dom eq $env{'user.domain'}) {
                   5400:                     $can_request->{$type} = 1;
                   5401:                 }
                   5402:             }
                   5403:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5404:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5405:                 if (@curr > 0) {
1.1036    raeburn  5406:                     foreach my $item (@curr) {
                   5407:                         if (ref($request_domains) eq 'HASH') {
                   5408:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5409:                             if ($otherdom ne '') {
                   5410:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5411:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5412:                                         push(@{$request_domains->{$type}},$otherdom);
                   5413:                                     }
                   5414:                                 } else {
                   5415:                                     push(@{$request_domains->{$type}},$otherdom);
                   5416:                                 }
                   5417:                             }
                   5418:                         }
                   5419:                     }
                   5420:                     unless($dom eq $env{'user.domain'}) {
                   5421:                         $canreq ++;
1.1035    raeburn  5422:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5423:                             $can_request->{$type} = 1;
                   5424:                         }
                   5425:                     }
                   5426:                 }
                   5427:             }
                   5428:         }
                   5429:     }
                   5430:     return $canreq;
                   5431: }
                   5432: 
1.341     www      5433: # ---------------------------------------------- Custom access rule evaluation
                   5434: 
                   5435: sub customaccess {
                   5436:     my ($priv,$uri)=@_;
1.807     albertel 5437:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5438:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5439:     $udom = &LONCAPA::clean_domain($udom);
                   5440:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5441:     my $access=0;
1.800     albertel 5442:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5443: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5444: 	if ($type eq 'user') {
                   5445: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5446: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5447: 		if ($tdom) {
                   5448: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5449: 		}
1.896     albertel 5450: 		if ($tuname) {
                   5451: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5452: 		}
                   5453: 		$access=($effect eq 'allow');
                   5454: 		last;
                   5455: 	    }
                   5456: 	} else {
                   5457: 	    if ($role) {
                   5458: 		if ($role ne $urole) { next; }
                   5459: 	    }
                   5460: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5461: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5462: 		if ($tdom) {
                   5463: 		    if ($tdom ne $udom) { next; }
                   5464: 		}
                   5465: 		if ($tcrs) {
                   5466: 		    if ($tcrs ne $ucrs) { next; }
                   5467: 		}
                   5468: 		if ($tsec) {
                   5469: 		    if ($tsec ne $usec) { next; }
                   5470: 		}
                   5471: 		$access=($effect eq 'allow');
                   5472: 		last;
                   5473: 	    }
                   5474: 	    if ($realm eq '' && $role eq '') {
                   5475: 		$access=($effect eq 'allow');
                   5476: 	    }
1.402     bowersj2 5477: 	}
1.341     www      5478:     }
                   5479:     return $access;
                   5480: }
                   5481: 
1.103     harris41 5482: # ------------------------------------------------- Check for a user privilege
1.12      www      5483: 
                   5484: sub allowed {
1.810     raeburn  5485:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5486:     my $ver_orguri=$uri;
1.439     www      5487:     $uri=&deversion($uri);
1.152     www      5488:     my $orguri=$uri;
1.52      www      5489:     $uri=&declutter($uri);
1.809     raeburn  5490: 
1.810     raeburn  5491:     if ($priv eq 'evb') {
                   5492: # Evade communication block restrictions for specified role in a course
                   5493:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5494:             return $1;
                   5495:         } else {
                   5496:             return;
                   5497:         }
                   5498:     }
                   5499: 
1.620     albertel 5500:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5501: # Free bre access to adm and meta resources
1.775     albertel 5502:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5503: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5504: 	&& ($priv eq 'bre')) {
1.14      www      5505: 	return 'F';
1.159     www      5506:     }
                   5507: 
1.545     banghart 5508: # Free bre access to user's own portfolio contents
1.714     raeburn  5509:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5510:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5511: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5512:         my %setters;
                   5513:         my ($startblock,$endblock) = 
                   5514:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5515:         if ($startblock && $endblock) {
                   5516:             return 'B';
                   5517:         } else {
                   5518:             return 'F';
                   5519:         }
1.545     banghart 5520:     }
                   5521: 
1.762     raeburn  5522: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5523:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5524:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5525:         if (exists($env{'request.course.id'})) {
                   5526:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5527:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5528:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5529:                 my $courseprivid=$env{'request.course.id'};
                   5530:                 $courseprivid=~s/\_/\//;
                   5531:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5532:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5533:                     return $1; 
1.762     raeburn  5534:                 } else {
                   5535:                     if ($env{'request.course.sec'}) {
                   5536:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5537:                     }
                   5538:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5539:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5540:                         return $2;
                   5541:                     }
1.714     raeburn  5542:                 }
                   5543:             }
                   5544:         }
                   5545:     }
                   5546: 
1.159     www      5547: # Free bre to public access
                   5548: 
                   5549:     if ($priv eq 'bre') {
1.238     www      5550:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5551: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5552:            return 'F'; 
                   5553:         }
1.238     www      5554:         if ($copyright eq 'priv') {
                   5555:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5556: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5557: 		return '';
                   5558:             }
                   5559:         }
                   5560:         if ($copyright eq 'domain') {
                   5561:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5562: 	    unless (($env{'user.domain'} eq $1) ||
                   5563:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5564: 		return '';
                   5565:             }
1.262     matthew  5566:         }
1.620     albertel 5567:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5568:             # Library role, so allow browsing of resources in this domain.
                   5569:             return 'F';
1.238     www      5570:         }
1.341     www      5571:         if ($copyright eq 'custom') {
                   5572: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5573:         }
1.14      www      5574:     }
1.264     matthew  5575:     # Domain coordinator is trying to create a course
1.620     albertel 5576:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5577:         # uri is the requested domain in this case.
                   5578:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5579:         # a role of dc for the domain in question.
1.620     albertel 5580:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5581:     }
1.29      www      5582: 
1.52      www      5583:     my $thisallowed='';
                   5584:     my $statecond=0;
                   5585:     my $courseprivid='';
                   5586: 
1.1039    raeburn  5587:     my $ownaccess;
1.1043    raeburn  5588:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5589:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5590:         if ($uri eq '') {
                   5591:             $ownaccess = 1;
                   5592:         } else {
                   5593:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5594:                 my $udom = $env{'user.domain'};
                   5595:                 my $uname = $env{'user.name'};
                   5596:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5597:                     $ownaccess = 1;
1.1040    raeburn  5598:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5599:                     unless ($uri =~ m{\.\./}) {
                   5600:                         $ownaccess = 1;
                   5601:                     }
                   5602:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5603:                     my $now = time;
                   5604:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5605:                         my $adom = $1;
                   5606:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5607:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5608:                                 my ($start,$end) = split('.',$env{$key});
                   5609:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5610:                                     $ownaccess = 1;
                   5611:                                     last;
                   5612:                                 }
                   5613:                             }
                   5614:                         }
                   5615:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5616:                         my $adom = $1;
                   5617:                         my $aname = $2;
1.1042    raeburn  5618:                         foreach my $role ('ca','aa') { 
                   5619:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5620:                                 my ($start,$end) =
                   5621:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5622:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5623:                                     $ownaccess = 1;
                   5624:                                     last;
                   5625:                                 }
1.1039    raeburn  5626:                             }
                   5627:                         }
                   5628:                     }
                   5629:                 }
                   5630:             }
                   5631:         }
                   5632:     }
                   5633: 
1.52      www      5634: # Course
                   5635: 
1.620     albertel 5636:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5637:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5638:             $thisallowed.=$1;
                   5639:         }
1.52      www      5640:     }
1.29      www      5641: 
1.52      www      5642: # Domain
                   5643: 
1.620     albertel 5644:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5645:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5646:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5647:             $thisallowed.=$1;
                   5648:         }
1.12      www      5649:     }
1.52      www      5650: 
                   5651: # Course: uri itself is a course
1.66      www      5652:     my $courseuri=$uri;
                   5653:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5654:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5655: 
1.620     albertel 5656:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5657:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5658:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5659:             $thisallowed.=$1;
                   5660:         }
1.12      www      5661:     }
1.29      www      5662: 
1.665     albertel 5663: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5664: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5665:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5666: 	$thisallowed='';
1.671     raeburn  5667:         my ($match)=&is_on_map($uri);
                   5668:         if ($match) {
                   5669:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5670:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5671:                 $thisallowed.=$1;
                   5672:             }
                   5673:         } else {
1.705     albertel 5674:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5675:             if ($refuri) {
                   5676:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5677:                     $thisallowed='F';
1.671     raeburn  5678:                 } else {
                   5679:                     $refuri=&declutter($refuri);
                   5680:                     my ($match) = &is_on_map($refuri);
                   5681:                     if ($match) {
                   5682:                         $thisallowed='F';
                   5683:                     }
1.669     raeburn  5684:                 }
1.671     raeburn  5685:             }
                   5686:         }
1.314     www      5687:     }
1.492     albertel 5688: 
1.766     albertel 5689:     if ($priv eq 'bre'
                   5690: 	&& $thisallowed ne 'F' 
                   5691: 	&& $thisallowed ne '2'
                   5692: 	&& &is_portfolio_url($uri)) {
                   5693: 	$thisallowed = &portfolio_access($uri);
                   5694:     }
                   5695:     
1.52      www      5696: # Full access at system, domain or course-wide level? Exit.
1.29      www      5697:     if ($thisallowed=~/F/) {
                   5698: 	return 'F';
                   5699:     }
                   5700: 
1.52      www      5701: # If this is generating or modifying users, exit with special codes
1.29      www      5702: 
1.643     www      5703:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5704: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5705: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5706: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5707: 	    unless ($auname) { return $thisallowed; }
                   5708: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5709: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5710: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5711: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5712: 	}
1.52      www      5713: 	return $thisallowed;
                   5714:     }
                   5715: #
1.103     harris41 5716: # Gathered so far: system, domain and course wide privileges
1.52      www      5717: #
                   5718: # Course: See if uri or referer is an individual resource that is part of 
                   5719: # the course
                   5720: 
1.620     albertel 5721:     if ($env{'request.course.id'}) {
1.232     www      5722: 
1.620     albertel 5723:        $courseprivid=$env{'request.course.id'};
                   5724:        if ($env{'request.course.sec'}) {
                   5725:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5726:        }
                   5727:        $courseprivid=~s/\_/\//;
                   5728:        my $checkreferer=1;
1.232     www      5729:        my ($match,$cond)=&is_on_map($uri);
                   5730:        if ($match) {
                   5731:            $statecond=$cond;
1.620     albertel 5732:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5733:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5734:                $thisallowed.=$1;
                   5735:                $checkreferer=0;
                   5736:            }
1.29      www      5737:        }
1.83      www      5738:        
1.148     www      5739:        if ($checkreferer) {
1.620     albertel 5740: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5741:             unless ($refuri) {
1.800     albertel 5742:                 foreach my $key (keys(%env)) {
                   5743: 		    if ($key=~/^httpref\..*\*/) {
                   5744: 			my $pattern=$key;
1.156     www      5745:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5746:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5747:                         $pattern=~s/\//\\\//g;
1.152     www      5748:                         if ($orguri=~/$pattern/) {
1.800     albertel 5749: 			    $refuri=$env{$key};
1.148     www      5750:                         }
                   5751:                     }
1.191     harris41 5752:                 }
1.148     www      5753:             }
1.232     www      5754: 
1.148     www      5755:          if ($refuri) { 
1.152     www      5756: 	  $refuri=&declutter($refuri);
1.232     www      5757:           my ($match,$cond)=&is_on_map($refuri);
                   5758:             if ($match) {
                   5759:               my $refstatecond=$cond;
1.620     albertel 5760:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5761:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5762:                   $thisallowed.=$1;
1.53      www      5763:                   $uri=$refuri;
                   5764:                   $statecond=$refstatecond;
1.52      www      5765:               }
                   5766:           }
1.148     www      5767:         }
1.29      www      5768:        }
1.52      www      5769:    }
1.29      www      5770: 
1.52      www      5771: #
1.103     harris41 5772: # Gathered now: all privileges that could apply, and condition number
1.52      www      5773: # 
                   5774: #
                   5775: # Full or no access?
                   5776: #
1.29      www      5777: 
1.52      www      5778:     if ($thisallowed=~/F/) {
                   5779: 	return 'F';
                   5780:     }
1.29      www      5781: 
1.52      www      5782:     unless ($thisallowed) {
                   5783:         return '';
                   5784:     }
1.29      www      5785: 
1.52      www      5786: # Restrictions exist, deal with them
                   5787: #
                   5788: #   C:according to course preferences
                   5789: #   R:according to resource settings
                   5790: #   L:unless locked
                   5791: #   X:according to user session state
                   5792: #
                   5793: 
                   5794: # Possibly locked functionality, check all courses
1.54      www      5795: # Locks might take effect only after 10 minutes cache expiration for other
                   5796: # courses, and 2 minutes for current course
1.52      www      5797: 
                   5798:     my $envkey;
                   5799:     if ($thisallowed=~/L/) {
1.1000    raeburn  5800:         foreach $envkey (keys(%env)) {
1.54      www      5801:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5802:                my $courseid=$2;
                   5803:                my $roleid=$1.'.'.$2;
1.92      www      5804:                $courseid=~s/^\///;
1.54      www      5805:                my $expiretime=600;
1.620     albertel 5806:                if ($env{'request.role'} eq $roleid) {
1.54      www      5807: 		  $expiretime=120;
                   5808:                }
                   5809: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5810:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5811:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5812: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5813:                }
1.620     albertel 5814:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5815:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5816: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5817:                        &log($env{'user.domain'},$env{'user.name'},
                   5818:                             $env{'user.home'},
1.57      www      5819:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5820:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5821:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5822: 		       return '';
                   5823:                    }
                   5824:                }
1.620     albertel 5825:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5826:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5827: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5828:                        &log($env{'user.domain'},$env{'user.name'},
                   5829:                             $env{'user.home'},
1.57      www      5830:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5831:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5832:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5833: 		       return '';
                   5834:                    }
                   5835:                }
                   5836: 	   }
1.29      www      5837:        }
1.52      www      5838:     }
                   5839:    
                   5840: #
                   5841: # Rest of the restrictions depend on selected course
                   5842: #
                   5843: 
1.620     albertel 5844:     unless ($env{'request.course.id'}) {
1.766     albertel 5845: 	if ($thisallowed eq 'A') {
                   5846: 	    return 'A';
1.814     raeburn  5847:         } elsif ($thisallowed eq 'B') {
                   5848:             return 'B';
1.766     albertel 5849: 	} else {
                   5850: 	    return '1';
                   5851: 	}
1.52      www      5852:     }
1.29      www      5853: 
1.52      www      5854: #
                   5855: # Now user is definitely in a course
                   5856: #
1.53      www      5857: 
                   5858: 
                   5859: # Course preferences
                   5860: 
                   5861:    if ($thisallowed=~/C/) {
1.620     albertel 5862:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5863:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5864:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5865: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5866: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5867: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5868: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5869: 			$env{'request.course.id'});
                   5870: 	   }
1.237     www      5871:            return '';
                   5872:        }
                   5873: 
1.620     albertel 5874:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5875: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5876: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5877: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5878: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5879: 			$env{'request.course.id'});
                   5880: 	   }
1.54      www      5881:            return '';
                   5882:        }
1.53      www      5883:    }
                   5884: 
                   5885: # Resource preferences
                   5886: 
                   5887:    if ($thisallowed=~/R/) {
1.620     albertel 5888:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5889:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5890: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5891: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5892: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5893: 	   }
                   5894: 	   return '';
1.54      www      5895:        }
1.53      www      5896:    }
1.30      www      5897: 
1.246     www      5898: # Restricted by state or randomout?
1.30      www      5899: 
1.52      www      5900:    if ($thisallowed=~/X/) {
1.620     albertel 5901:       if ($env{'acc.randomout'}) {
1.579     albertel 5902: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5903:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5904:             return ''; 
                   5905:          }
1.247     www      5906:       }
                   5907:       if (&condval($statecond)) {
1.52      www      5908: 	 return '2';
                   5909:       } else {
                   5910:          return '';
                   5911:       }
                   5912:    }
1.30      www      5913: 
1.766     albertel 5914:     if ($thisallowed eq 'A') {
                   5915: 	return 'A';
1.814     raeburn  5916:     } elsif ($thisallowed eq 'B') {
                   5917:         return 'B';
1.766     albertel 5918:     }
1.52      www      5919:    return 'F';
1.232     www      5920: }
                   5921: 
1.710     albertel 5922: sub split_uri_for_cond {
                   5923:     my $uri=&deversion(&declutter(shift));
                   5924:     my @uriparts=split(/\//,$uri);
                   5925:     my $filename=pop(@uriparts);
                   5926:     my $pathname=join('/',@uriparts);
                   5927:     return ($pathname,$filename);
                   5928: }
1.232     www      5929: # --------------------------------------------------- Is a resource on the map?
                   5930: 
                   5931: sub is_on_map {
1.710     albertel 5932:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5933:     #Trying to find the conditional for the file
1.620     albertel 5934:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5935: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5936:     if ($match) {
1.289     bowersj2 5937: 	return (1,$1);
                   5938:     } else {
1.434     www      5939: 	return (0,0);
1.289     bowersj2 5940:     }
1.12      www      5941: }
                   5942: 
1.427     www      5943: # --------------------------------------------------------- Get symb from alias
                   5944: 
                   5945: sub get_symb_from_alias {
                   5946:     my $symb=shift;
                   5947:     my ($map,$resid,$url)=&decode_symb($symb);
                   5948: # Already is a symb
                   5949:     if ($url) { return $symb; }
                   5950: # Must be an alias
                   5951:     my $aliassymb='';
                   5952:     my %bighash;
1.620     albertel 5953:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5954:                             &GDBM_READER(),0640)) {
                   5955:         my $rid=$bighash{'mapalias_'.$symb};
                   5956: 	if ($rid) {
                   5957: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5958: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5959: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5960: 	}
                   5961:         untie %bighash;
                   5962:     }
                   5963:     return $aliassymb;
                   5964: }
                   5965: 
1.12      www      5966: # ----------------------------------------------------------------- Define Role
                   5967: 
                   5968: sub definerole {
                   5969:   if (allowed('mcr','/')) {
                   5970:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5971:     foreach my $role (split(':',$sysrole)) {
                   5972: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5973:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5974:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5975: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5976:                return "refused:s:$crole&$cqual"; 
                   5977:             }
                   5978:         }
1.191     harris41 5979:     }
1.800     albertel 5980:     foreach my $role (split(':',$domrole)) {
                   5981: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5982:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5983:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5984: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5985:                return "refused:d:$crole&$cqual"; 
                   5986:             }
                   5987:         }
1.191     harris41 5988:     }
1.800     albertel 5989:     foreach my $role (split(':',$courole)) {
                   5990: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5991:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5992:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5993: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5994:                return "refused:c:$crole&$cqual"; 
                   5995:             }
                   5996:         }
1.191     harris41 5997:     }
1.620     albertel 5998:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5999:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6000: 	        "rolesdef_$rolename=".
                   6001:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6002:     return reply($command,$env{'user.home'});
1.12      www      6003:   } else {
                   6004:     return 'refused';
                   6005:   }
1.105     harris41 6006: }
                   6007: 
                   6008: # ---------------- Make a metadata query against the network of library servers
                   6009: 
                   6010: sub metadata_query {
1.244     matthew  6011:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6012:     my %rhash;
1.845     albertel 6013:     my %libserv = &all_library();
1.244     matthew  6014:     my @server_list = (defined($server_array) ? @$server_array
                   6015:                                               : keys(%libserv) );
                   6016:     for my $server (@server_list) {
1.118     harris41 6017: 	unless ($custom or $customshow) {
                   6018: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6019: 	    $rhash{$server}=$reply;
                   6020: 	}
                   6021: 	else {
                   6022: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6023: 			     &escape($custom).':'.&escape($customshow),
                   6024: 			     $server);
                   6025: 	    $rhash{$server}=$reply;
                   6026: 	}
1.112     harris41 6027:     }
1.118     harris41 6028:     return \%rhash;
1.240     www      6029: }
                   6030: 
                   6031: # ----------------------------------------- Send log queries and wait for reply
                   6032: 
                   6033: sub log_query {
                   6034:     my ($uname,$udom,$query,%filters)=@_;
                   6035:     my $uhome=&homeserver($uname,$udom);
                   6036:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6037:     my $uhost=&hostname($uhome);
1.800     albertel 6038:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6039:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6040:                        $uhome);
1.479     albertel 6041:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6042:     return get_query_reply($queryid);
                   6043: }
                   6044: 
1.818     raeburn  6045: # -------------------------- Update MySQL table for portfolio file
                   6046: 
                   6047: sub update_portfolio_table {
1.821     raeburn  6048:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6049:     if ($group ne '') {
                   6050:         $file_name =~s /^\Q$group\E//;
                   6051:     }
1.818     raeburn  6052:     my $homeserver = &homeserver($uname,$udom);
                   6053:     my $queryid=
1.821     raeburn  6054:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6055:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6056:     my $reply = &get_query_reply($queryid);
                   6057:     return $reply;
                   6058: }
                   6059: 
1.899     raeburn  6060: # -------------------------- Update MySQL allusers table
                   6061: 
                   6062: sub update_allusers_table {
                   6063:     my ($uname,$udom,$names) = @_;
                   6064:     my $homeserver = &homeserver($uname,$udom);
                   6065:     my $queryid=
                   6066:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6067:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6068:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6069:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6070:                'generation='.&escape($names->{'generation'}).'%%'.
                   6071:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6072:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6073:     return;
1.899     raeburn  6074: }
                   6075: 
1.508     raeburn  6076: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6077: 
                   6078: sub fetch_enrollment_query {
1.511     raeburn  6079:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6080:     my $homeserver;
1.547     raeburn  6081:     my $maxtries = 1;
1.508     raeburn  6082:     if ($context eq 'automated') {
                   6083:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6084:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6085:     } else {
                   6086:         $homeserver = &homeserver($cnum,$dom);
                   6087:     }
1.838     albertel 6088:     my $host=&hostname($homeserver);
1.506     raeburn  6089:     my $cmd = '';
1.1000    raeburn  6090:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6091:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6092:     }
                   6093:     $cmd =~ s/%%$//;
                   6094:     $cmd = &escape($cmd);
                   6095:     my $query = 'fetchenrollment';
1.620     albertel 6096:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6097:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6098:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6099:         return 'error: '.$queryid;
                   6100:     }
1.506     raeburn  6101:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6102:     my $tries = 1;
                   6103:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6104:         $reply = &get_query_reply($queryid);
                   6105:         $tries ++;
                   6106:     }
1.526     raeburn  6107:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6108:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6109:     } else {
1.901     albertel 6110:         my @responses = split(/:/,$reply);
1.515     raeburn  6111:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6112:             foreach my $line (@responses) {
                   6113:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6114:                 $$replyref{$key} = $value;
                   6115:             }
                   6116:         } else {
1.1117    foxr     6117:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6118:             foreach my $line (@responses) {
                   6119:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6120:                 $$replyref{$key} = $value;
                   6121:                 if ($value > 0) {
1.800     albertel 6122:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6123:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6124:                         my $destname = $pathname.'/'.$filename;
                   6125:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6126:                         if ($xml_classlist =~ /^error/) {
                   6127:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6128:                         } else {
1.506     raeburn  6129:                             if ( open(FILE,">$destname") ) {
                   6130:                                 print FILE &unescape($xml_classlist);
                   6131:                                 close(FILE);
1.526     raeburn  6132:                             } else {
                   6133:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6134:                             }
                   6135:                         }
                   6136:                     }
                   6137:                 }
                   6138:             }
                   6139:         }
                   6140:         return 'ok';
                   6141:     }
                   6142:     return 'error';
                   6143: }
                   6144: 
1.242     www      6145: sub get_query_reply {
                   6146:     my $queryid=shift;
1.1117    foxr     6147:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6148:     my $reply='';
                   6149:     for (1..100) {
                   6150: 	sleep 2;
                   6151:         if (-e $replyfile.'.end') {
1.448     albertel 6152: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6153: 		$reply = join('',<$fh>);
                   6154: 		close($fh);
1.240     www      6155: 	   } else { return 'error: reply_file_error'; }
1.242     www      6156:            return &unescape($reply);
                   6157: 	}
1.240     www      6158:     }
1.242     www      6159:     return 'timeout:'.$queryid;
1.240     www      6160: }
                   6161: 
                   6162: sub courselog_query {
1.241     www      6163: #
                   6164: # possible filters:
                   6165: # url: url or symb
                   6166: # username
                   6167: # domain
                   6168: # action: view, submit, grade
                   6169: # start: timestamp
                   6170: # end: timestamp
                   6171: #
1.240     www      6172:     my (%filters)=@_;
1.620     albertel 6173:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6174:     if ($filters{'url'}) {
                   6175: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6176:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6177:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6178:     }
1.620     albertel 6179:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6180:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6181:     return &log_query($cname,$cdom,'courselog',%filters);
                   6182: }
                   6183: 
                   6184: sub userlog_query {
1.858     raeburn  6185: #
                   6186: # possible filters:
                   6187: # action: log check role
                   6188: # start: timestamp
                   6189: # end: timestamp
                   6190: #
1.240     www      6191:     my ($uname,$udom,%filters)=@_;
                   6192:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6193: }
                   6194: 
1.506     raeburn  6195: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6196: 
                   6197: sub auto_run {
1.508     raeburn  6198:     my ($cnum,$cdom) = @_;
1.876     raeburn  6199:     my $response = 0;
                   6200:     my $settings;
                   6201:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6202:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6203:         $settings = $domconfig{'autoenroll'};
                   6204:         if ($settings->{'run'} eq '1') {
                   6205:             $response = 1;
                   6206:         }
                   6207:     } else {
1.934     raeburn  6208:         my $homeserver;
                   6209:         if (&is_course($cdom,$cnum)) {
                   6210:             $homeserver = &homeserver($cnum,$cdom);
                   6211:         } else {
                   6212:             $homeserver = &domain($cdom,'primary');
                   6213:         }
                   6214:         if ($homeserver ne 'no_host') {
                   6215:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6216:         }
1.876     raeburn  6217:     }
1.506     raeburn  6218:     return $response;
                   6219: }
1.776     albertel 6220: 
1.506     raeburn  6221: sub auto_get_sections {
1.508     raeburn  6222:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6223:     my $homeserver;
                   6224:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6225:         $homeserver = &homeserver($cnum,$cdom);
                   6226:     }
                   6227:     if (!defined($homeserver)) { 
                   6228:         if ($cdom =~ /^$match_domain$/) {
                   6229:             $homeserver = &domain($cdom,'primary');
                   6230:         }
                   6231:     }
                   6232:     my @secs;
                   6233:     if (defined($homeserver)) {
                   6234:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6235:         unless ($response eq 'refused') {
                   6236:             @secs = split(/:/,$response);
                   6237:         }
1.506     raeburn  6238:     }
                   6239:     return @secs;
                   6240: }
1.776     albertel 6241: 
1.506     raeburn  6242: sub auto_new_course {
1.1099    raeburn  6243:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6244:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6245:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6246:     return $response;
                   6247: }
1.776     albertel 6248: 
1.506     raeburn  6249: sub auto_validate_courseID {
1.508     raeburn  6250:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6251:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6252:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6253:     return $response;
                   6254: }
1.776     albertel 6255: 
1.1007    raeburn  6256: sub auto_validate_instcode {
1.1020    raeburn  6257:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6258:     my ($homeserver,$response);
                   6259:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6260:         $homeserver = &homeserver($cnum,$cdom);
                   6261:     }
                   6262:     if (!defined($homeserver)) {
                   6263:         if ($cdom =~ /^$match_domain$/) {
                   6264:             $homeserver = &domain($cdom,'primary');
                   6265:         }
                   6266:     }
1.1065    raeburn  6267:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6268:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6269:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6270:     return ($outcome,$description);
1.1007    raeburn  6271: }
                   6272: 
1.506     raeburn  6273: sub auto_create_password {
1.873     raeburn  6274:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6275:     my ($homeserver,$response);
1.506     raeburn  6276:     my $create_passwd = 0;
                   6277:     my $authchk = '';
1.873     raeburn  6278:     if ($udom =~ /^$match_domain$/) {
                   6279:         $homeserver = &domain($udom,'primary');
                   6280:     }
                   6281:     if ($homeserver eq '') {
                   6282:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6283:             $homeserver = &homeserver($cnum,$cdom);
                   6284:         }
                   6285:     }
                   6286:     if ($homeserver eq '') {
                   6287:         $authchk = 'nodomain';
1.506     raeburn  6288:     } else {
1.873     raeburn  6289:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6290:         if ($response eq 'refused') {
                   6291:             $authchk = 'refused';
                   6292:         } else {
1.901     albertel 6293:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6294:         }
1.506     raeburn  6295:     }
                   6296:     return ($authparam,$create_passwd,$authchk);
                   6297: }
                   6298: 
1.706     raeburn  6299: sub auto_photo_permission {
                   6300:     my ($cnum,$cdom,$students) = @_;
                   6301:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6302:     my ($outcome,$perm_reqd,$conditions) = 
                   6303: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6304:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6305: 	return (undef,undef);
                   6306:     }
1.706     raeburn  6307:     return ($outcome,$perm_reqd,$conditions);
                   6308: }
                   6309: 
                   6310: sub auto_checkphotos {
                   6311:     my ($uname,$udom,$pid) = @_;
                   6312:     my $homeserver = &homeserver($uname,$udom);
                   6313:     my ($result,$resulttype);
                   6314:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6315: 				   &escape($uname).':'.&escape($pid),
                   6316: 				   $homeserver));
1.709     albertel 6317:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6318: 	return (undef,undef);
                   6319:     }
1.706     raeburn  6320:     if ($outcome) {
                   6321:         ($result,$resulttype) = split(/:/,$outcome);
                   6322:     } 
                   6323:     return ($result,$resulttype);
                   6324: }
                   6325: 
                   6326: sub auto_photochoice {
                   6327:     my ($cnum,$cdom) = @_;
                   6328:     my $homeserver = &homeserver($cnum,$cdom);
                   6329:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6330: 						       &escape($cdom),
                   6331: 						       $homeserver)));
1.709     albertel 6332:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6333: 	return (undef,undef);
                   6334:     }
1.706     raeburn  6335:     return ($update,$comment);
                   6336: }
                   6337: 
                   6338: sub auto_photoupdate {
                   6339:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6340:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6341:     my $host=&hostname($homeserver);
1.706     raeburn  6342:     my $cmd = '';
                   6343:     my $maxtries = 1;
1.800     albertel 6344:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6345:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6346:     }
                   6347:     $cmd =~ s/%%$//;
                   6348:     $cmd = &escape($cmd);
                   6349:     my $query = 'institutionalphotos';
                   6350:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6351:     unless ($queryid=~/^\Q$host\E\_/) {
                   6352:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6353:         return 'error: '.$queryid;
                   6354:     }
                   6355:     my $reply = &get_query_reply($queryid);
                   6356:     my $tries = 1;
                   6357:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6358:         $reply = &get_query_reply($queryid);
                   6359:         $tries ++;
                   6360:     }
                   6361:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6362:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6363:     } else {
                   6364:         my @responses = split(/:/,$reply);
                   6365:         my $outcome = shift(@responses); 
                   6366:         foreach my $item (@responses) {
                   6367:             my ($key,$value) = split(/=/,$item);
                   6368:             $$photo{$key} = $value;
                   6369:         }
                   6370:         return $outcome;
                   6371:     }
                   6372:     return 'error';
                   6373: }
                   6374: 
1.521     raeburn  6375: sub auto_instcode_format {
1.793     albertel 6376:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6377: 	$cat_order) = @_;
1.521     raeburn  6378:     my $courses = '';
1.772     raeburn  6379:     my @homeservers;
1.521     raeburn  6380:     if ($caller eq 'global') {
1.841     albertel 6381: 	my %servers = &get_servers($codedom,'library');
                   6382: 	foreach my $tryserver (keys(%servers)) {
                   6383: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6384: 		push(@homeservers,$tryserver);
                   6385: 	    }
1.584     raeburn  6386:         }
1.1022    raeburn  6387:     } elsif ($caller eq 'requests') {
                   6388:         if ($codedom =~ /^$match_domain$/) {
                   6389:             my $chome = &domain($codedom,'primary');
                   6390:             unless ($chome eq 'no_host') {
                   6391:                 push(@homeservers,$chome);
                   6392:             }
                   6393:         }
1.521     raeburn  6394:     } else {
1.772     raeburn  6395:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6396:     }
1.793     albertel 6397:     foreach my $code (keys(%{$instcodes})) {
                   6398:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6399:     }
                   6400:     chop($courses);
1.772     raeburn  6401:     my $ok_response = 0;
                   6402:     my $response;
                   6403:     while (@homeservers > 0 && $ok_response == 0) {
                   6404:         my $server = shift(@homeservers); 
                   6405:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6406:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6407:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6408: 		split(/:/,$response);
1.772     raeburn  6409:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6410:             push(@{$codetitles},&str2array($codetitles_str));
                   6411:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6412:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6413:             $ok_response = 1;
                   6414:         }
                   6415:     }
                   6416:     if ($ok_response) {
1.521     raeburn  6417:         return 'ok';
1.772     raeburn  6418:     } else {
                   6419:         return $response;
1.521     raeburn  6420:     }
                   6421: }
                   6422: 
1.792     raeburn  6423: sub auto_instcode_defaults {
                   6424:     my ($domain,$returnhash,$code_order) = @_;
                   6425:     my @homeservers;
1.841     albertel 6426: 
                   6427:     my %servers = &get_servers($domain,'library');
                   6428:     foreach my $tryserver (keys(%servers)) {
                   6429: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6430: 	    push(@homeservers,$tryserver);
                   6431: 	}
1.792     raeburn  6432:     }
1.841     albertel 6433: 
1.792     raeburn  6434:     my $response;
1.841     albertel 6435:     foreach my $server (@homeservers) {
1.792     raeburn  6436:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6437:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6438: 	
                   6439: 	foreach my $pair (split(/\&/,$response)) {
                   6440: 	    my ($name,$value)=split(/\=/,$pair);
                   6441: 	    if ($name eq 'code_order') {
                   6442: 		@{$code_order} = split(/\&/,&unescape($value));
                   6443: 	    } else {
                   6444: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6445: 	    }
                   6446: 	}
                   6447: 	return 'ok';
1.792     raeburn  6448:     }
1.841     albertel 6449: 
                   6450:     return $response;
1.1003    raeburn  6451: }
                   6452: 
                   6453: sub auto_possible_instcodes {
1.1007    raeburn  6454:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6455:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6456:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6457:         return;
                   6458:     }
1.1003    raeburn  6459:     my (@homeservers,$uhome);
                   6460:     if (defined(&domain($domain,'primary'))) {
                   6461:         $uhome=&domain($domain,'primary');
                   6462:         push(@homeservers,&domain($domain,'primary'));
                   6463:     } else {
                   6464:         my %servers = &get_servers($domain,'library');
                   6465:         foreach my $tryserver (keys(%servers)) {
                   6466:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6467:                 push(@homeservers,$tryserver);
                   6468:             }
                   6469:         }
                   6470:     }
                   6471:     my $response;
                   6472:     foreach my $server (@homeservers) {
                   6473:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6474:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6475:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6476:             split(':',$response);
                   6477:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6478:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6479:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6480:             my ($name,$value)=split('=',$item);
                   6481:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6482:         }
                   6483:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6484:             my ($name,$value)=split('=',$item);
                   6485:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6486:         }
                   6487:         return 'ok';
                   6488:     }
                   6489:     return $response;
                   6490: }
1.792     raeburn  6491: 
1.1010    raeburn  6492: sub auto_courserequest_checks {
                   6493:     my ($dom) = @_;
1.1020    raeburn  6494:     my ($homeserver,%validations);
                   6495:     if ($dom =~ /^$match_domain$/) {
                   6496:         $homeserver = &domain($dom,'primary');
                   6497:     }
                   6498:     unless ($homeserver eq 'no_host') {
                   6499:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6500:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6501:             my @items = split(/&/,$response);
                   6502:             foreach my $item (@items) {
                   6503:                 my ($key,$value) = split('=',$item);
                   6504:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6505:             }
                   6506:         }
                   6507:     }
1.1010    raeburn  6508:     return %validations; 
                   6509: }
                   6510: 
1.1020    raeburn  6511: sub auto_courserequest_validation {
                   6512:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6513:     my ($homeserver,$response);
                   6514:     if ($dom =~ /^$match_domain$/) {
                   6515:         $homeserver = &domain($dom,'primary');
                   6516:     }
                   6517:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6518:           
1.1020    raeburn  6519:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6520:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6521:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6522:                                     $homeserver));
                   6523:     }
                   6524:     return $response;
                   6525: }
                   6526: 
1.777     albertel 6527: sub auto_validate_class_sec {
1.918     raeburn  6528:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6529:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6530:     my $ownerlist;
                   6531:     if (ref($owners) eq 'ARRAY') {
                   6532:         $ownerlist = join(',',@{$owners});
                   6533:     } else {
                   6534:         $ownerlist = $owners;
                   6535:     }
1.773     raeburn  6536:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6537:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6538:     return $response;
                   6539: }
                   6540: 
1.679     raeburn  6541: # ------------------------------------------------------- Course Group routines
                   6542: 
                   6543: sub get_coursegroups {
1.809     raeburn  6544:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6545:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6546: }
                   6547: 
1.679     raeburn  6548: sub modify_coursegroup {
                   6549:     my ($cdom,$cnum,$groupsettings) = @_;
                   6550:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6551: }
                   6552: 
1.809     raeburn  6553: sub toggle_coursegroup_status {
                   6554:     my ($cdom,$cnum,$group,$action) = @_;
                   6555:     my ($from_namespace,$to_namespace);
                   6556:     if ($action eq 'delete') {
                   6557:         $from_namespace = 'coursegroups';
                   6558:         $to_namespace = 'deleted_groups';
                   6559:     } else {
                   6560:         $from_namespace = 'deleted_groups';
                   6561:         $to_namespace = 'coursegroups';
                   6562:     }
                   6563:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6564:     if (my $tmp = &error(%curr_group)) {
                   6565:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6566:         return ('read error',$tmp);
                   6567:     } else {
                   6568:         my %savedsettings = %curr_group; 
1.809     raeburn  6569:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6570:         my $deloutcome;
                   6571:         if ($result eq 'ok') {
1.809     raeburn  6572:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6573:         } else {
                   6574:             return ('write error',$result);
                   6575:         }
                   6576:         if ($deloutcome eq 'ok') {
                   6577:             return 'ok';
                   6578:         } else {
                   6579:             return ('delete error',$deloutcome);
                   6580:         }
                   6581:     }
                   6582: }
                   6583: 
1.679     raeburn  6584: sub modify_group_roles {
1.957     raeburn  6585:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6586:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6587:     my $role = 'gr/'.&escape($userprivs);
                   6588:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6589:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6590:     if ($result eq 'ok') {
                   6591:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6592:     }
1.679     raeburn  6593:     return $result;
                   6594: }
                   6595: 
                   6596: sub modify_coursegroup_membership {
                   6597:     my ($cdom,$cnum,$membership) = @_;
                   6598:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6599:     return $result;
                   6600: }
                   6601: 
1.682     raeburn  6602: sub get_active_groups {
                   6603:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6604:     my $now = time;
                   6605:     my %groups = ();
                   6606:     foreach my $key (keys(%env)) {
1.811     albertel 6607:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6608:             my ($start,$end) = split(/\./,$env{$key});
                   6609:             if (($end!=0) && ($end<$now)) { next; }
                   6610:             if (($start!=0) && ($start>$now)) { next; }
                   6611:             if ($1 eq $cdom && $2 eq $cnum) {
                   6612:                 $groups{$3} = $env{$key} ;
                   6613:             }
                   6614:         }
                   6615:     }
                   6616:     return %groups;
                   6617: }
                   6618: 
1.683     raeburn  6619: sub get_group_membership {
                   6620:     my ($cdom,$cnum,$group) = @_;
                   6621:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6622: }
                   6623: 
                   6624: sub get_users_groups {
                   6625:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6626:     my @usersgroups;
1.683     raeburn  6627:     my $cachetime=1800;
                   6628: 
                   6629:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6630:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6631:     if (defined($cached)) {
1.734     albertel 6632:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6633:     } else {  
                   6634:         $grouplist = '';
1.816     raeburn  6635:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6636:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6637:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6638:         my $access_end = $env{'course.'.$courseid.
                   6639:                               '.default_enrollment_end_date'};
                   6640:         my $now = time;
                   6641:         foreach my $key (keys(%roleshash)) {
                   6642:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6643:                 my $group = $1;
                   6644:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6645:                     my $start = $2;
                   6646:                     my $end = $1;
                   6647:                     if ($start == -1) { next; } # deleted from group
                   6648:                     if (($start!=0) && ($start>$now)) { next; }
                   6649:                     if (($end!=0) && ($end<$now)) {
                   6650:                         if ($access_end && $access_end < $now) {
                   6651:                             if ($access_end - $end < 86400) {
                   6652:                                 push(@usersgroups,$group);
1.733     raeburn  6653:                             }
                   6654:                         }
1.817     raeburn  6655:                         next;
1.733     raeburn  6656:                     }
1.817     raeburn  6657:                     push(@usersgroups,$group);
1.683     raeburn  6658:                 }
                   6659:             }
                   6660:         }
1.817     raeburn  6661:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6662:         $grouplist = join(':',@usersgroups);
                   6663:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6664:     }
1.733     raeburn  6665:     return @usersgroups;
1.683     raeburn  6666: }
                   6667: 
                   6668: sub devalidate_getgroups_cache {
                   6669:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6670:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6671: 
1.683     raeburn  6672:     my $hashid="$udom:$uname:$courseid";
                   6673:     &devalidate_cache_new('getgroups',$hashid);
                   6674: }
                   6675: 
1.12      www      6676: # ------------------------------------------------------------------ Plain Text
                   6677: 
                   6678: sub plaintext {
1.988     raeburn  6679:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6680:     if ($short =~ m{^cr/}) {
1.758     albertel 6681: 	return (split('/',$short))[-1];
                   6682:     }
1.742     raeburn  6683:     if (!defined($cid)) {
                   6684:         $cid = $env{'request.course.id'};
                   6685:     }
                   6686:     my %rolenames = (
1.1008    raeburn  6687:                       Course    => 'std',
                   6688:                       Community => 'alt1',
1.742     raeburn  6689:                     );
1.1037    raeburn  6690:     if ($cid ne '') {
                   6691:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6692:             unless ($forcedefault) {
                   6693:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6694:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6695:                 return &Apache::lonlocal::mt($roletext);
                   6696:             }
                   6697:         }
                   6698:     }
                   6699:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6700:         (defined($rolenames{$type})) && 
                   6701:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6702:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6703:     } elsif ($cid ne '') {
                   6704:         my $crstype = $env{'course.'.$cid.'.type'};
                   6705:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6706:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6707:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6708:         }
1.742     raeburn  6709:     }
1.1037    raeburn  6710:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6711: }
                   6712: 
                   6713: # ----------------------------------------------------------------- Assign Role
                   6714: 
                   6715: sub assignrole {
1.957     raeburn  6716:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6717:         $context)=@_;
1.21      www      6718:     my $mrole;
                   6719:     if ($role =~ /^cr\//) {
1.393     www      6720:         my $cwosec=$url;
1.811     albertel 6721:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6722: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6723:            my $refused = 1;
                   6724:            if ($context eq 'requestcourses') {
                   6725:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6726:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6727:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6728:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6729:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6730:                            if ($crsenv{'internal.courseowner'} eq
                   6731:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6732:                                $refused = '';
                   6733:                            }
                   6734:                        }
                   6735:                    }
                   6736:                }
                   6737:            }
                   6738:            if ($refused) {
                   6739:                &logthis('Refused custom assignrole: '.
                   6740:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6741:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6742:                return 'refused';
                   6743:            }
1.104     www      6744:         }
1.21      www      6745:         $mrole='cr';
1.678     raeburn  6746:     } elsif ($role =~ /^gr\//) {
                   6747:         my $cwogrp=$url;
1.811     albertel 6748:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6749:         unless (&allowed('mdg',$cwogrp)) {
                   6750:             &logthis('Refused group assignrole: '.
                   6751:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6752:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6753:             return 'refused';
                   6754:         }
                   6755:         $mrole='gr';
1.21      www      6756:     } else {
1.82      www      6757:         my $cwosec=$url;
1.811     albertel 6758:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6759:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6760:             my $refused;
                   6761:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6762:                 if (!(&allowed('c'.$role,$url))) {
                   6763:                     $refused = 1;
                   6764:                 }
                   6765:             } else {
                   6766:                 $refused = 1;
                   6767:             }
1.947     raeburn  6768:             if ($refused) {
1.1045    raeburn  6769:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6770:                 if (!$selfenroll && $context eq 'course') {
                   6771:                     my %crsenv;
                   6772:                     if ($role eq 'cc' || $role eq 'co') {
                   6773:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6774:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6775:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6776:                                 if ($crsenv{'internal.courseowner'} eq 
                   6777:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6778:                                     $refused = '';
                   6779:                                 }
                   6780:                             }
                   6781:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6782:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6783:                                 if ($crsenv{'internal.courseowner'} eq 
                   6784:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6785:                                     $refused = '';
                   6786:                                 }
                   6787:                             }
                   6788:                         }
                   6789:                     }
                   6790:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6791:                     $refused = '';
1.1017    raeburn  6792:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6793:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6794:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6795:                         my $wrongcc;
                   6796:                         if ($cnum =~ /^$match_community$/) {
                   6797:                             $wrongcc = 1 if ($role eq 'cc');
                   6798:                         } else {
                   6799:                             $wrongcc = 1 if ($role eq 'co');
                   6800:                         }
                   6801:                         unless ($wrongcc) {
                   6802:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6803:                             if ($crsenv{'internal.courseowner'} eq 
                   6804:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6805:                                 $refused = '';
                   6806:                             }
1.1017    raeburn  6807:                         }
                   6808:                     }
                   6809:                 }
                   6810:                 if ($refused) {
1.947     raeburn  6811:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6812:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6813: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6814:                     return 'refused';
                   6815:                 }
1.932     raeburn  6816:             }
1.104     www      6817:         }
1.21      www      6818:         $mrole=$role;
                   6819:     }
1.620     albertel 6820:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6821:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6822:     if ($end) { $command.='_'.$end; }
1.21      www      6823:     if ($start) {
                   6824: 	if ($end) { 
1.81      www      6825:            $command.='_'.$start; 
1.21      www      6826:         } else {
1.81      www      6827:            $command.='_0_'.$start;
1.21      www      6828:         }
                   6829:     }
1.739     raeburn  6830:     my $origstart = $start;
                   6831:     my $origend = $end;
1.957     raeburn  6832:     my $delflag;
1.357     www      6833: # actually delete
                   6834:     if ($deleteflag) {
1.373     www      6835: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6836: # modify command to delete the role
1.620     albertel 6837:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6838:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6839: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6840: # set start and finish to negative values for userrolelog
                   6841:            $start=-1;
                   6842:            $end=-1;
1.957     raeburn  6843:            $delflag = 1;
1.357     www      6844:         }
                   6845:     }
                   6846: # send command
1.349     www      6847:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6848: # log new user role if status is ok
1.349     www      6849:     if ($answer eq 'ok') {
1.663     raeburn  6850: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6851: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6852:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6853:         unless ($role =~ /^gr/) {
                   6854:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6855:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6856:         }
1.1053    raeburn  6857:         if ($role eq 'cc') {
                   6858:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6859:         }
1.349     www      6860:     }
                   6861:     return $answer;
1.169     harris41 6862: }
                   6863: 
1.1053    raeburn  6864: sub autoupdate_coowners {
                   6865:     my ($url,$end,$start,$uname,$udom) = @_;
                   6866:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6867:     if (($cdom ne '') && ($cnum ne '')) {
                   6868:         my $now = time;
                   6869:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6870:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6871:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6872:             my $instcode = $coursehash{'internal.coursecode'};
                   6873:             if ($instcode ne '') {
1.1056    raeburn  6874:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6875:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6876:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6877:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6878:                         if ($result eq 'valid') {
                   6879:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6880:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6881:                                     push(@newcoowners,$coowner);
                   6882:                                 }
                   6883:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6884:                                     push(@newcoowners,$uname.':'.$udom);
                   6885:                                 }
                   6886:                                 @newcoowners = sort(@newcoowners);
                   6887:                             } else {
                   6888:                                 push(@newcoowners,$uname.':'.$udom);
                   6889:                             }
                   6890:                         } else {
                   6891:                             if ($coursehash{'internal.co-owners'}) {
                   6892:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6893:                                     unless ($coowner eq $uname.':'.$udom) {
                   6894:                                         push(@newcoowners,$coowner);
                   6895:                                     }
                   6896:                                 }
                   6897:                                 unless (@newcoowners > 0) {
                   6898:                                     $delcoowners = 1;
                   6899:                                     $coowners = '';
                   6900:                                 }
                   6901:                             }
                   6902:                         }
                   6903:                         if (@newcoowners || $delcoowners) {
                   6904:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6905:                                             $delcoowners,@newcoowners);
                   6906:                         }
                   6907:                     }
                   6908:                 }
                   6909:             }
                   6910:         }
                   6911:     }
                   6912: }
                   6913: 
                   6914: sub store_coowners {
                   6915:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6916:     my $cid = $cdom.'_'.$cnum;
                   6917:     my ($coowners,$delresult,$putresult);
                   6918:     if (@newcoowners) {
                   6919:         $coowners = join(',',@newcoowners);
                   6920:         my %coownershash = (
                   6921:                             'internal.co-owners' => $coowners,
                   6922:                            );
                   6923:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6924:         if ($putresult eq 'ok') {
                   6925:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6926:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6927:             }
                   6928:         }
                   6929:     }
                   6930:     if ($delcoowners) {
                   6931:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6932:         if ($delresult eq 'ok') {
                   6933:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6934:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6935:             }
                   6936:         }
                   6937:     }
                   6938:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6939:         my %crsinfo =
                   6940:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6941:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6942:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6943:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6944:         }
                   6945:     }
                   6946: }
                   6947: 
1.169     harris41 6948: # -------------------------------------------------- Modify user authentication
1.197     www      6949: # Overrides without validation
                   6950: 
1.169     harris41 6951: sub modifyuserauth {
                   6952:     my ($udom,$uname,$umode,$upass)=@_;
                   6953:     my $uhome=&homeserver($uname,$udom);
1.197     www      6954:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6955:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6956:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6957:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6958:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6959: 		     &escape($upass),$uhome);
1.620     albertel 6960:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6961:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6962:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6963:     &log($udom,,$uname,$uhome,
1.620     albertel 6964:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6965:                                      $env{'user.name'}.', '.$umode.
1.197     www      6966:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6967:     unless ($reply eq 'ok') {
1.197     www      6968:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6969: 	return 'error: '.$reply;
                   6970:     }   
1.170     harris41 6971:     return 'ok';
1.80      www      6972: }
                   6973: 
1.81      www      6974: # --------------------------------------------------------------- Modify a user
1.80      www      6975: 
1.81      www      6976: sub modifyuser {
1.206     matthew  6977:     my ($udom,    $uname, $uid,
                   6978:         $umode,   $upass, $first,
                   6979:         $middle,  $last,  $gene,
1.1058    raeburn  6980:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6981:     $udom= &LONCAPA::clean_domain($udom);
                   6982:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6983:     my $showcandelete = 'none';
                   6984:     if (ref($candelete) eq 'ARRAY') {
                   6985:         if (@{$candelete} > 0) {
                   6986:             $showcandelete = join(', ',@{$candelete});
                   6987:         }
                   6988:     }
1.81      www      6989:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6990:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6991: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6992:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6993:                                      ' desiredhome not specified'). 
1.620     albertel 6994:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6995:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6996:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6997:     my $newuser;
                   6998:     if ($uhome eq 'no_host') {
                   6999:         $newuser = 1;
                   7000:     }
1.80      www      7001: # ----------------------------------------------------------------- Create User
1.406     albertel 7002:     if (($uhome eq 'no_host') && 
                   7003: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7004:         my $unhome='';
1.844     albertel 7005:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7006:             $unhome = $desiredhome;
1.620     albertel 7007: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7008: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7009:         } else { # load balancing routine for determining $unhome
1.81      www      7010:             my $loadm=10000000;
1.841     albertel 7011: 	    my %servers = &get_servers($udom,'library');
                   7012: 	    foreach my $tryserver (keys(%servers)) {
                   7013: 		my $answer=reply('load',$tryserver);
                   7014: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7015: 		    $loadm=$answer;
                   7016: 		    $unhome=$tryserver;
                   7017: 		}
1.80      www      7018: 	    }
                   7019:         }
                   7020:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7021: 	    return 'error: unable to find a home server for '.$uname.
                   7022:                    ' in domain '.$udom;
1.80      www      7023:         }
                   7024:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7025:                          &escape($upass),$unhome);
                   7026: 	unless ($reply eq 'ok') {
                   7027:             return 'error: '.$reply;
                   7028:         }   
1.230     stredwic 7029:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7030:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7031: 	    return 'error: unable verify users home machine.';
1.80      www      7032:         }
1.209     matthew  7033:     }   # End of creation of new user
1.80      www      7034: # ---------------------------------------------------------------------- Add ID
                   7035:     if ($uid) {
                   7036:        $uid=~tr/A-Z/a-z/;
                   7037:        my %uidhash=&idrget($udom,$uname);
1.196     www      7038:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7039:          && (!$forceid)) {
1.80      www      7040: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7041: 	      return 'error: user id "'.$uid.'" does not match '.
                   7042:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7043:           }
                   7044:        } else {
                   7045: 	  &idput($udom,($uname => $uid));
                   7046:        }
                   7047:     }
                   7048: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7049:     my @tmp=&get('environment',
1.899     raeburn  7050: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7051:                     'permanentemail','inststatus'],
1.134     albertel 7052: 		   $udom,$uname);
1.1075    raeburn  7053:     my (%names,%oldnames);
1.313     matthew  7054:     if ($tmp[0] =~ m/^error:.*/) { 
                   7055:         %names=(); 
                   7056:     } else {
                   7057:         %names = @tmp;
1.1075    raeburn  7058:         %oldnames = %names;
1.313     matthew  7059:     }
1.388     www      7060: #
1.1058    raeburn  7061: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7062: # of users did not contain them), do not overwrite existing values
                   7063: # unless field is in $candelete array ref.  
                   7064: #
                   7065: 
                   7066:     my @fields = ('firstname','middlename','lastname','generation',
                   7067:                   'permanentemail','id');
                   7068:     my %newvalues;
                   7069:     if (ref($candelete) eq 'ARRAY') {
                   7070:         foreach my $field (@fields) {
                   7071:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7072:                 if ($field eq 'firstname') {
                   7073:                     $names{$field} = $first;
                   7074:                 } elsif ($field eq 'middlename') {
                   7075:                     $names{$field} = $middle;
                   7076:                 } elsif ($field eq 'lastname') {
                   7077:                     $names{$field} = $last;
                   7078:                 } elsif ($field eq 'generation') { 
                   7079:                     $names{$field} = $gene;
                   7080:                 } elsif ($field eq 'permanentemail') {
                   7081:                     $names{$field} = $email;
                   7082:                 } elsif ($field eq 'id') {
                   7083:                     $names{$field}  = $uid;
                   7084:                 }
                   7085:             }
                   7086:         }
                   7087:     }
1.388     www      7088:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7089:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7090:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7091:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7092:     if ($email) {
                   7093:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7094:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7095:     }
1.899     raeburn  7096:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7097:     if (defined($inststatus)) {
                   7098:         $names{'inststatus'} = '';
                   7099:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7100:         if (ref($usertypes) eq 'HASH') {
                   7101:             my @okstatuses; 
                   7102:             foreach my $item (split(/:/,$inststatus)) {
                   7103:                 if (defined($usertypes->{$item})) {
                   7104:                     push(@okstatuses,$item);  
                   7105:                 }
                   7106:             }
                   7107:             if (@okstatuses) {
                   7108:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7109:             }
                   7110:         }
                   7111:     }
1.1075    raeburn  7112:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7113:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7114:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7115:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7116:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7117:     } else {
                   7118:         $logmsg .= ' during self creation';
                   7119:     }
1.1075    raeburn  7120:     my $changed;
                   7121:     if ($newuser) {
                   7122:         $changed = 1;
                   7123:     } else {
                   7124:         foreach my $field (@fields) {
                   7125:             if ($names{$field} ne $oldnames{$field}) {
                   7126:                 $changed = 1;
                   7127:                 last;
                   7128:             }
                   7129:         }
                   7130:     }
                   7131:     unless ($changed) {
                   7132:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7133:         &logthis($logmsg);
                   7134:         return 'ok';
                   7135:     }
                   7136:     my $reply = &put('environment', \%names, $udom,$uname);
                   7137:     if ($reply ne 'ok') { 
                   7138:         return 'error: '.$reply;
                   7139:     }
1.1087    raeburn  7140:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7141:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7142:     }
1.1075    raeburn  7143:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7144:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7145:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7146:     &logthis($logmsg);
1.134     albertel 7147:     return 'ok';
1.80      www      7148: }
                   7149: 
1.81      www      7150: # -------------------------------------------------------------- Modify student
1.80      www      7151: 
1.81      www      7152: sub modifystudent {
                   7153:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7154:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7155:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7156:     if (!$cid) {
1.620     albertel 7157: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7158: 	    return 'not_in_class';
                   7159: 	}
1.80      www      7160:     }
                   7161: # --------------------------------------------------------------- Make the user
1.81      www      7162:     my $reply=&modifyuser
1.209     matthew  7163: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7164:          $desiredhome,$email,$inststatus);
1.80      www      7165:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7166:     # This will cause &modify_student_enrollment to get the uid from the
                   7167:     # students environment
                   7168:     $uid = undef if (!$forceid);
1.455     albertel 7169:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7170: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7171:     return $reply;
                   7172: }
                   7173: 
                   7174: sub modify_student_enrollment {
1.957     raeburn  7175:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7176:     my ($cdom,$cnum,$chome);
                   7177:     if (!$cid) {
1.620     albertel 7178: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7179: 	    return 'not_in_class';
                   7180: 	}
1.620     albertel 7181: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7182: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7183:     } else {
                   7184: 	($cdom,$cnum)=split(/_/,$cid);
                   7185:     }
1.620     albertel 7186:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7187:     if (!$chome) {
1.457     raeburn  7188: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7189:     }
1.455     albertel 7190:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7191:     # Make sure the user exists
1.81      www      7192:     my $uhome=&homeserver($uname,$udom);
                   7193:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7194: 	return 'error: no such user';
                   7195:     }
1.297     matthew  7196:     # Get student data if we were not given enough information
                   7197:     if (!defined($first)  || $first  eq '' || 
                   7198:         !defined($last)   || $last   eq '' || 
                   7199:         !defined($uid)    || $uid    eq '' || 
                   7200:         !defined($middle) || $middle eq '' || 
                   7201:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7202:         # They did not supply us with enough data to enroll the student, so
                   7203:         # we need to pick up more information.
1.297     matthew  7204:         my %tmp = &get('environment',
1.294     matthew  7205:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7206:                        ,$udom,$uname);
                   7207: 
1.800     albertel 7208:         #foreach my $key (keys(%tmp)) {
                   7209:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7210:         #}
1.294     matthew  7211:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7212:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7213:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7214:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7215:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7216:     }
1.556     albertel 7217:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7218:     my $reply=cput('classlist',
                   7219: 		   {"$uname:$udom" => 
1.515     raeburn  7220: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7221: 		   $cdom,$cnum);
1.81      www      7222:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7223: 	return 'error: '.$reply;
1.652     albertel 7224:     } else {
                   7225: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7226:     }
1.297     matthew  7227:     # Add student role to user
1.83      www      7228:     my $uurl='/'.$cid;
1.81      www      7229:     $uurl=~s/\_/\//g;
                   7230:     if ($usec) {
                   7231: 	$uurl.='/'.$usec;
                   7232:     }
1.957     raeburn  7233:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7234: }
                   7235: 
1.556     albertel 7236: sub format_name {
                   7237:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7238:     my $name;
                   7239:     if ($first ne 'lastname') {
                   7240: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7241:     } else {
                   7242: 	if ($lastname=~/\S/) {
                   7243: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7244: 	    $name=~s/\s+,/,/;
                   7245: 	} else {
                   7246: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7247: 	}
                   7248:     }
                   7249:     $name=~s/^\s+//;
                   7250:     $name=~s/\s+$//;
                   7251:     $name=~s/\s+/ /g;
                   7252:     return $name;
                   7253: }
                   7254: 
1.84      www      7255: # ------------------------------------------------- Write to course preferences
                   7256: 
                   7257: sub writecoursepref {
                   7258:     my ($courseid,%prefs)=@_;
                   7259:     $courseid=~s/^\///;
                   7260:     $courseid=~s/\_/\//g;
                   7261:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7262:     my $chome=homeserver($cnum,$cdomain);
                   7263:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7264: 	return 'error: no such course';
                   7265:     }
                   7266:     my $cstring='';
1.800     albertel 7267:     foreach my $pref (keys(%prefs)) {
                   7268: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7269:     }
1.84      www      7270:     $cstring=~s/\&$//;
                   7271:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7272: }
                   7273: 
                   7274: # ---------------------------------------------------------- Make/modify course
                   7275: 
                   7276: sub createcourse {
1.741     raeburn  7277:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7278:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7279:     $url=&declutter($url);
                   7280:     my $cid='';
1.1028    raeburn  7281:     if ($context eq 'requestcourses') {
                   7282:         my $can_create = 0;
                   7283:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7284:         if ($udom eq $ownerdom) {
                   7285:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7286:                                   $context)) {
                   7287:                 $can_create = 1;
                   7288:             }
                   7289:         } else {
                   7290:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7291:                                            $category);
                   7292:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7293:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7294:                 if (@curr > 0) {
                   7295:                     my @options = qw(approval validate autolimit);
                   7296:                     my $optregex = join('|',@options);
                   7297:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7298:                         $can_create = 1;
                   7299:                     }
                   7300:                 }
                   7301:             }
                   7302:         }
                   7303:         if ($can_create) {
                   7304:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7305:                 unless (&allowed('ccc',$udom)) {
                   7306:                     return 'refused'; 
                   7307:                 }
1.1017    raeburn  7308:             }
                   7309:         } else {
                   7310:             return 'refused';
                   7311:         }
1.1028    raeburn  7312:     } elsif (!&allowed('ccc',$udom)) {
                   7313:         return 'refused';
1.84      www      7314:     }
1.1011    raeburn  7315: # --------------------------------------------------------------- Get Unique ID
                   7316:     my $uname;
                   7317:     if ($cnum =~ /^$match_courseid$/) {
                   7318:         my $chome=&homeserver($cnum,$udom,'true');
                   7319:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7320:             $uname = $cnum;
                   7321:         } else {
1.1038    raeburn  7322:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7323:         }
                   7324:     } else {
1.1038    raeburn  7325:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7326:     }
                   7327:     return $uname if ($uname =~ /^error/);
                   7328: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7329:     if (!defined($course_server)) {
                   7330:         if (defined(&domain($udom,'primary'))) {
                   7331:             $course_server = &domain($udom,'primary');
                   7332:         } else {
                   7333:             $course_server = $env{'user.home'}; 
                   7334:         }
                   7335:     }
                   7336:     my %host_servers =
                   7337:         &Apache::lonnet::get_servers($udom,'library');
                   7338:     unless ($host_servers{$course_server}) {
                   7339:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7340:     }
1.84      www      7341: # ------------------------------------------------------------- Make the course
                   7342:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7343:                       $course_server);
1.84      www      7344:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7345:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7346:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7347: 	return 'error: no such course';
                   7348:     }
1.271     www      7349: # ----------------------------------------------------------------- Course made
1.516     raeburn  7350: # log existence
1.1029    raeburn  7351:     my $now = time;
1.918     raeburn  7352:     my $newcourse = {
                   7353:                     $udom.'_'.$uname => {
1.921     raeburn  7354:                                      description => $description,
                   7355:                                      inst_code   => $inst_code,
                   7356:                                      owner       => $course_owner,
                   7357:                                      type        => $crstype,
1.1029    raeburn  7358:                                      creator     => $env{'user.name'}.':'.
                   7359:                                                     $env{'user.domain'},
                   7360:                                      created     => $now,
                   7361:                                      context     => $context,
1.918     raeburn  7362:                                                 },
                   7363:                     };
1.921     raeburn  7364:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7365: # set toplevel url
1.271     www      7366:     my $topurl=$url;
                   7367:     unless ($nonstandard) {
                   7368: # ------------------------------------------ For standard courses, make top url
                   7369:         my $mapurl=&clutter($url);
1.278     www      7370:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7371:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7372: <map>
                   7373: <resource id="1" type="start"></resource>
                   7374: <resource id="2" src="$mapurl"></resource>
                   7375: <resource id="3" type="finish"></resource>
                   7376: <link index="1" from="1" to="2"></link>
                   7377: <link index="2" from="2" to="3"></link>
                   7378: </map>
                   7379: ENDINITMAP
                   7380:         $topurl=&declutter(
1.638     albertel 7381:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7382:                           );
                   7383:     }
                   7384: # ----------------------------------------------------------- Write preferences
1.84      www      7385:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7386:                      ('description'              => $description,
                   7387:                       'url'                      => $topurl,
                   7388:                       'internal.creator'         => $env{'user.name'}.':'.
                   7389:                                                     $env{'user.domain'},
                   7390:                       'internal.created'         => $now,
                   7391:                       'internal.creationcontext' => $context)
                   7392:                     );
1.84      www      7393:     return '/'.$udom.'/'.$uname;
                   7394: }
                   7395: 
1.1011    raeburn  7396: # ------------------------------------------------------------------- Create ID
                   7397: sub generate_coursenum {
1.1038    raeburn  7398:     my ($udom,$crstype) = @_;
1.1011    raeburn  7399:     my $domdesc = &domain($udom);
                   7400:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7401:     my $first;
                   7402:     if ($crstype eq 'Community') {
                   7403:         $first = '0';
                   7404:     } else {
                   7405:         $first = int(1+rand(9)); 
                   7406:     } 
                   7407:     my $uname=$first.
1.1011    raeburn  7408:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7409:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7410:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7411: # ----------------------------------------------- Make sure that does not exist
                   7412:     my $uhome=&homeserver($uname,$udom,'true');
                   7413:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7414:         if ($crstype eq 'Community') {
                   7415:             $first = '0';
                   7416:         } else {
                   7417:             $first = int(1+rand(9));
                   7418:         }
                   7419:         $uname=$first.
1.1011    raeburn  7420:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7421:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7422:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7423:         $uhome=&homeserver($uname,$udom,'true');
                   7424:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7425:             return 'error: unable to generate unique course-ID';
                   7426:         }
                   7427:     }
                   7428:     return $uname;
                   7429: }
                   7430: 
1.813     albertel 7431: sub is_course {
                   7432:     my ($cdom,$cnum) = @_;
                   7433:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7434: 				undef,'.');
1.813     albertel 7435:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7436:         return 1;
                   7437:     }
                   7438:     return 0;
                   7439: }
                   7440: 
1.1015    raeburn  7441: sub store_userdata {
                   7442:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7443:     my $result;
1.1016    raeburn  7444:     if ($datakey ne '') {
1.1013    raeburn  7445:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7446:             if ($udom eq '' || $uname eq '') {
                   7447:                 $udom = $env{'user.domain'};
                   7448:                 $uname = $env{'user.name'};
                   7449:             }
                   7450:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7451:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7452:                 $result = 'error: no_host';
                   7453:             } else {
                   7454:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7455:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7456: 
                   7457:                 my $namevalue='';
                   7458:                 foreach my $key (keys(%{$storehash})) {
                   7459:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7460:                 }
                   7461:                 $namevalue=~s/\&$//;
1.1105    raeburn  7462:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7463:                                   $namevalue,$uhome);
1.1013    raeburn  7464:             }
                   7465:         } else {
                   7466:             $result = 'error: data to store was not a hash reference'; 
                   7467:         }
                   7468:     } else {
                   7469:         $result= 'error: invalid requestkey'; 
                   7470:     }
                   7471:     return $result;
                   7472: }
                   7473: 
1.21      www      7474: # ---------------------------------------------------------- Assign Custom Role
                   7475: 
                   7476: sub assigncustomrole {
1.957     raeburn  7477:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7478:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7479:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7480: }
                   7481: 
                   7482: # ----------------------------------------------------------------- Revoke Role
                   7483: 
                   7484: sub revokerole {
1.957     raeburn  7485:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7486:     my $now=time;
1.965     raeburn  7487:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7488: }
                   7489: 
                   7490: # ---------------------------------------------------------- Revoke Custom Role
                   7491: 
                   7492: sub revokecustomrole {
1.957     raeburn  7493:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7494:     my $now=time;
1.357     www      7495:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7496:            $deleteflag,$selfenroll,$context);
1.17      www      7497: }
                   7498: 
1.533     banghart 7499: # ------------------------------------------------------------ Disk usage
1.535     albertel 7500: sub diskusage {
1.955     raeburn  7501:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7502:     $directorypath =~ s/\/$//;
                   7503:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7504:                        .&escape($getpropath).':'.&escape($uname).':'
                   7505:                        .&escape($udom),homeserver($uname,$udom));
                   7506:     if ($listing eq 'unknown_cmd') {
                   7507:         if ($getpropath) {
                   7508:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7509:         }
                   7510:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7511:     }
1.514     albertel 7512:     return $listing;
1.512     banghart 7513: }
                   7514: 
1.566     banghart 7515: sub is_locked {
1.1096    raeburn  7516:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7517:     my @check;
                   7518:     my $is_locked;
1.1093    raeburn  7519:     push (@check,$file_name);
1.613     albertel 7520:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7521: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7522:     my ($tmp)=keys(%locked);
                   7523:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7524:     
1.566     banghart 7525:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7526:         $is_locked = 'false';
                   7527:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7528:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7529:                $is_locked = 'true';
1.1096    raeburn  7530:                if (ref($which) eq 'ARRAY') {
                   7531:                    push(@{$which},$entry);
                   7532:                } else {
                   7533:                    last;
                   7534:                }
1.745     raeburn  7535:            }
                   7536:        }
1.566     banghart 7537:     } else {
                   7538:         $is_locked = 'false';
                   7539:     }
1.1093    raeburn  7540:     return $is_locked;
1.566     banghart 7541: }
                   7542: 
1.759     albertel 7543: sub declutter_portfile {
                   7544:     my ($file) = @_;
1.833     albertel 7545:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7546:     return $file;
                   7547: }
                   7548: 
1.559     banghart 7549: # ------------------------------------------------------------- Mark as Read Only
                   7550: 
                   7551: sub mark_as_readonly {
                   7552:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7553:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7554:     my ($tmp)=keys(%current_permissions);
                   7555:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7556:     foreach my $file (@{$files}) {
1.759     albertel 7557: 	$file = &declutter_portfile($file);
1.561     banghart 7558:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7559:     }
1.613     albertel 7560:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7561:     return;
                   7562: }
                   7563: 
1.572     banghart 7564: # ------------------------------------------------------------Save Selected Files
                   7565: 
                   7566: sub save_selected_files {
                   7567:     my ($user, $path, @files) = @_;
                   7568:     my $filename = $user."savedfiles";
1.573     banghart 7569:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7570:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7571:     foreach my $file (@files) {
1.620     albertel 7572:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7573:     }
                   7574:     foreach my $file (@other_files) {
1.574     banghart 7575:         print (OUT $file."\n");
1.572     banghart 7576:     }
1.574     banghart 7577:     close (OUT);
1.572     banghart 7578:     return 'ok';
                   7579: }
                   7580: 
1.574     banghart 7581: sub clear_selected_files {
                   7582:     my ($user) = @_;
                   7583:     my $filename = $user."savedfiles";
1.1117    foxr     7584:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7585:     print (OUT undef);
                   7586:     close (OUT);
                   7587:     return ("ok");    
                   7588: }
                   7589: 
1.572     banghart 7590: sub files_in_path {
                   7591:     my ($user, $path) = @_;
                   7592:     my $filename = $user."savedfiles";
                   7593:     my %return_files;
1.1117    foxr     7594:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7595:     while (my $line_in = <IN>) {
1.574     banghart 7596:         chomp ($line_in);
                   7597:         my @paths_and_file = split (m!/!, $line_in);
                   7598:         my $file_part = pop (@paths_and_file);
                   7599:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7600:         $path_part.='/';
                   7601:         my $path_and_file = $path_part.$file_part;
                   7602:         if ($path_part eq $path) {
                   7603:             $return_files{$file_part}= 'selected';
                   7604:         }
                   7605:     }
1.574     banghart 7606:     close (IN);
                   7607:     return (\%return_files);
1.572     banghart 7608: }
                   7609: 
                   7610: # called in portfolio select mode, to show files selected NOT in current directory
                   7611: sub files_not_in_path {
                   7612:     my ($user, $path) = @_;
                   7613:     my $filename = $user."savedfiles";
                   7614:     my @return_files;
                   7615:     my $path_part;
1.1117    foxr     7616:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7617:     while (my $line = <IN>) {
1.572     banghart 7618:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7619:         my @paths_and_file = split(m|/|, $line);
                   7620:         my $file_part = pop(@paths_and_file);
                   7621:         chomp($file_part);
                   7622:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7623:         $path_part .= '/';
                   7624:         my $path_and_file = $path_part.$file_part;
                   7625:         if ($path_part ne $path) {
1.800     albertel 7626:             push(@return_files, ($path_and_file));
1.572     banghart 7627:         }
                   7628:     }
1.800     albertel 7629:     close(OUT);
1.574     banghart 7630:     return (@return_files);
1.572     banghart 7631: }
                   7632: 
1.745     raeburn  7633: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7634: 
1.745     raeburn  7635: sub get_portfile_permissions {
                   7636:     my ($domain,$user) = @_;
1.613     albertel 7637:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7638:     my ($tmp)=keys(%current_permissions);
                   7639:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7640:     return \%current_permissions;
                   7641: }
                   7642: 
                   7643: #---------------------------------------------Get portfolio file access controls
                   7644: 
1.749     raeburn  7645: sub get_access_controls {
1.745     raeburn  7646:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7647:     my %access;
                   7648:     my $real_file = $file;
                   7649:     $file =~ s/\.meta$//;
1.745     raeburn  7650:     if (defined($file)) {
1.749     raeburn  7651:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7652:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7653:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7654:             }
                   7655:         }
1.745     raeburn  7656:     } else {
1.749     raeburn  7657:         foreach my $key (keys(%{$current_permissions})) {
                   7658:             if ($key =~ /\0accesscontrol$/) {
                   7659:                 if (defined($group)) {
                   7660:                     if ($key !~ m-^\Q$group\E/-) {
                   7661:                         next;
                   7662:                     }
                   7663:                 }
                   7664:                 my ($fullpath) = split(/\0/,$key);
                   7665:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7666:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7667:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7668:                     }
                   7669:                 }
                   7670:             }
                   7671:         }
                   7672:     }
                   7673:     return %access;
                   7674: }
                   7675: 
                   7676: sub modify_access_controls {
                   7677:     my ($file_name,$changes,$domain,$user)=@_;
                   7678:     my ($outcome,$deloutcome);
                   7679:     my %store_permissions;
                   7680:     my %new_values;
                   7681:     my %new_control;
                   7682:     my %translation;
                   7683:     my @deletions = ();
                   7684:     my $now = time;
                   7685:     if (exists($$changes{'activate'})) {
                   7686:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7687:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7688:             my $numnew = scalar(@newitems);
                   7689:             for (my $i=0; $i<$numnew; $i++) {
                   7690:                 my $newkey = $newitems[$i];
                   7691:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7692:                 if ($newkey =~ /^\d+:/) { 
                   7693:                     $newkey =~ s/^(\d+)/$newid/;
                   7694:                     $translation{$1} = $newid;
                   7695:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7696:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7697:                     $translation{$1} = $newid;
                   7698:                 }
1.749     raeburn  7699:                 $new_values{$file_name."\0".$newkey} = 
                   7700:                                           $$changes{'activate'}{$newitems[$i]};
                   7701:                 $new_control{$newkey} = $now;
                   7702:             }
                   7703:         }
                   7704:     }
                   7705:     my %todelete;
                   7706:     my %changed_items;
                   7707:     foreach my $action ('delete','update') {
                   7708:         if (exists($$changes{$action})) {
                   7709:             if (ref($$changes{$action}) eq 'HASH') {
                   7710:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7711:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7712:                     if ($action eq 'delete') { 
                   7713:                         $todelete{$itemnum} = 1;
                   7714:                     } else {
                   7715:                         $changed_items{$itemnum} = $key;
                   7716:                     }
                   7717:                 }
1.745     raeburn  7718:             }
                   7719:         }
1.749     raeburn  7720:     }
                   7721:     # get lock on access controls for file.
                   7722:     my $lockhash = {
                   7723:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7724:                                                        ':'.$env{'user.domain'},
                   7725:                    }; 
                   7726:     my $tries = 0;
                   7727:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7728:    
                   7729:     while (($gotlock ne 'ok') && $tries <3) {
                   7730:         $tries ++;
                   7731:         sleep 1;
                   7732:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7733:     }
                   7734:     if ($gotlock eq 'ok') {
                   7735:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7736:         my ($tmp)=keys(%curr_permissions);
                   7737:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7738:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7739:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7740:             if (ref($curr_controls) eq 'HASH') {
                   7741:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7742:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7743:                     if (defined($todelete{$itemnum})) {
                   7744:                         push(@deletions,$file_name."\0".$control_item);
                   7745:                     } else {
                   7746:                         if (defined($changed_items{$itemnum})) {
                   7747:                             $new_control{$changed_items{$itemnum}} = $now;
                   7748:                             push(@deletions,$file_name."\0".$control_item);
                   7749:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7750:                         } else {
                   7751:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7752:                         }
                   7753:                     }
1.745     raeburn  7754:                 }
                   7755:             }
                   7756:         }
1.970     raeburn  7757:         my ($group);
                   7758:         if (&is_course($domain,$user)) {
                   7759:             ($group,my $file) = split(/\//,$file_name,2);
                   7760:         }
1.749     raeburn  7761:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7762:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7763:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7764:         #  remove lock
                   7765:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7766:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7767:         my $sqlresult =
1.970     raeburn  7768:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7769:                                     $group);
1.749     raeburn  7770:     } else {
                   7771:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7772:     }
1.749     raeburn  7773:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7774: }
                   7775: 
1.827     raeburn  7776: sub make_public_indefinitely {
                   7777:     my ($requrl) = @_;
                   7778:     my $now = time;
                   7779:     my $action = 'activate';
                   7780:     my $aclnum = 0;
                   7781:     if (&is_portfolio_url($requrl)) {
                   7782:         my (undef,$udom,$unum,$file_name,$group) =
                   7783:             &parse_portfolio_url($requrl);
                   7784:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7785:         my %access_controls = &get_access_controls($current_perms,
                   7786:                                                    $group,$file_name);
                   7787:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7788:             my ($num,$scope,$end,$start) = 
                   7789:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7790:             if ($scope eq 'public') {
                   7791:                 if ($start <= $now && $end == 0) {
                   7792:                     $action = 'none';
                   7793:                 } else {
                   7794:                     $action = 'update';
                   7795:                     $aclnum = $num;
                   7796:                 }
                   7797:                 last;
                   7798:             }
                   7799:         }
                   7800:         if ($action eq 'none') {
                   7801:              return 'ok';
                   7802:         } else {
                   7803:             my %changes;
                   7804:             my $newend = 0;
                   7805:             my $newstart = $now;
                   7806:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7807:             $changes{$action}{$newkey} = {
                   7808:                 type => 'public',
                   7809:                 time => {
                   7810:                     start => $newstart,
                   7811:                     end   => $newend,
                   7812:                 },
                   7813:             };
                   7814:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7815:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7816:             return $outcome;
                   7817:         }
                   7818:     } else {
                   7819:         return 'invalid';
                   7820:     }
                   7821: }
                   7822: 
1.745     raeburn  7823: #------------------------------------------------------Get Marked as Read Only
                   7824: 
                   7825: sub get_marked_as_readonly {
                   7826:     my ($domain,$user,$what,$group) = @_;
                   7827:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7828:     my @readonly_files;
1.629     banghart 7829:     my $cmp1=$what;
                   7830:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7831:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7832:         if (defined($group)) {
                   7833:             if ($file_name !~ m-^\Q$group\E/-) {
                   7834:                 next;
                   7835:             }
                   7836:         }
1.561     banghart 7837:         if (ref($value) eq "ARRAY"){
                   7838:             foreach my $stored_what (@{$value}) {
1.629     banghart 7839:                 my $cmp2=$stored_what;
1.759     albertel 7840:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7841:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7842:                 }
1.629     banghart 7843:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7844:                     push(@readonly_files, $file_name);
1.745     raeburn  7845:                     last;
1.563     banghart 7846:                 } elsif (!defined($what)) {
                   7847:                     push(@readonly_files, $file_name);
1.745     raeburn  7848:                     last;
1.561     banghart 7849:                 }
                   7850:             }
1.745     raeburn  7851:         }
1.561     banghart 7852:     }
                   7853:     return @readonly_files;
                   7854: }
1.577     banghart 7855: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7856: 
1.577     banghart 7857: sub get_marked_as_readonly_hash {
1.745     raeburn  7858:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7859:     my %readonly_files;
1.745     raeburn  7860:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7861:         if (defined($group)) {
                   7862:             if ($file_name !~ m-^\Q$group\E/-) {
                   7863:                 next;
                   7864:             }
                   7865:         }
1.577     banghart 7866:         if (ref($value) eq "ARRAY"){
                   7867:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7868:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7869:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7870:                         if ($lock_descriptor eq 'graded') {
                   7871:                             $readonly_files{$file_name} = 'graded';
                   7872:                         } elsif ($lock_descriptor eq 'handback') {
                   7873:                             $readonly_files{$file_name} = 'handback';
                   7874:                         } else {
                   7875:                             if (!exists($readonly_files{$file_name})) {
                   7876:                                 $readonly_files{$file_name} = 'locked';
                   7877:                             }
                   7878:                         }
1.745     raeburn  7879:                     }
1.750     banghart 7880:                 } 
1.577     banghart 7881:             }
                   7882:         } 
                   7883:     }
                   7884:     return %readonly_files;
                   7885: }
1.559     banghart 7886: # ------------------------------------------------------------ Unmark as Read Only
                   7887: 
                   7888: sub unmark_as_readonly {
1.629     banghart 7889:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7890:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7891:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7892:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7893:     my $symb_crs = $what;
                   7894:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7895:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7896:     my ($tmp)=keys(%current_permissions);
                   7897:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7898:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7899:     foreach my $file (@readonly_files) {
1.759     albertel 7900: 	my $clean_file = &declutter_portfile($file);
                   7901: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7902: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7903:         my @new_locks;
                   7904:         my @del_keys;
                   7905:         if (ref($current_locks) eq "ARRAY"){
                   7906:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7907:                 my $compare=$locker;
1.749     raeburn  7908:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7909:                     $compare=join('',@{$locker});
1.746     raeburn  7910:                     if ($compare ne $symb_crs) {
                   7911:                         push(@new_locks, $locker);
                   7912:                     }
1.563     banghart 7913:                 }
                   7914:             }
1.650     albertel 7915:             if (scalar(@new_locks) > 0) {
1.563     banghart 7916:                 $current_permissions{$file} = \@new_locks;
                   7917:             } else {
                   7918:                 push(@del_keys, $file);
1.613     albertel 7919:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7920:                 delete($current_permissions{$file});
1.563     banghart 7921:             }
                   7922:         }
1.561     banghart 7923:     }
1.613     albertel 7924:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7925:     return;
                   7926: }
1.512     banghart 7927: 
1.17      www      7928: # ------------------------------------------------------------ Directory lister
                   7929: 
                   7930: sub dirlist {
1.955     raeburn  7931:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7932:     $uri=~s/^\///;
                   7933:     $uri=~s/\/$//;
1.253     stredwic 7934:     my ($udom, $uname);
1.955     raeburn  7935:     if ($getuserdir) {
1.253     stredwic 7936:         $udom = $userdomain;
                   7937:         $uname = $username;
1.955     raeburn  7938:     } else {
                   7939:         (undef,$udom,$uname)=split(/\//,$uri);
                   7940:         if(defined($userdomain)) {
                   7941:             $udom = $userdomain;
                   7942:         }
                   7943:         if(defined($username)) {
                   7944:             $uname = $username;
                   7945:         }
1.253     stredwic 7946:     }
1.955     raeburn  7947:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7948: 
1.955     raeburn  7949:     $dirRoot = $perlvar{'lonDocRoot'};
                   7950:     if (defined($getpropath)) {
                   7951:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7952:         $dirRoot =~ s/\/$//;
1.955     raeburn  7953:     } elsif (defined($getuserdir)) {
                   7954:         my $subdir=$uname.'__';
                   7955:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7956:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7957:                    ."/$udom/$subdir/$uname";
                   7958:     } elsif (defined($alternateRoot)) {
                   7959:         $dirRoot = $alternateRoot;
1.751     banghart 7960:     }
1.253     stredwic 7961: 
                   7962:     if($udom) {
                   7963:         if($uname) {
1.955     raeburn  7964:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7965:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7966:                               .':'.&escape($uname).':'.&escape($udom),
                   7967:                               &homeserver($uname,$udom));
                   7968:             if ($listing eq 'unknown_cmd') {
                   7969:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7970:                                   &homeserver($uname,$udom));
                   7971:             } else {
                   7972:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7973:             }
1.605     matthew  7974:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7975:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7976: 				  &homeserver($uname,$udom));
1.605     matthew  7977:                 @listing_results = split(/:/,$listing);
                   7978:             } else {
                   7979:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7980:             }
                   7981:             return @listing_results;
1.955     raeburn  7982:         } elsif(!$alternateRoot) {
1.800     albertel 7983:             my %allusers;
1.841     albertel 7984: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7985:  	    foreach my $tryserver (keys(%servers)) {
                   7986:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7987:                                   &escape($udom),$tryserver);
                   7988:                 if ($listing eq 'unknown_cmd') {
                   7989: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7990: 				      $udom, $tryserver);
                   7991:                 } else {
                   7992:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7993:                 }
1.841     albertel 7994: 		if ($listing eq 'unknown_cmd') {
                   7995: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7996: 				      $udom, $tryserver);
                   7997: 		    @listing_results = split(/:/,$listing);
                   7998: 		} else {
                   7999: 		    @listing_results =
                   8000: 			map { &unescape($_); } split(/:/,$listing);
                   8001: 		}
                   8002: 		if ($listing_results[0] ne 'no_such_dir' && 
                   8003: 		    $listing_results[0] ne 'empty'       &&
                   8004: 		    $listing_results[0] ne 'con_lost') {
                   8005: 		    foreach my $line (@listing_results) {
                   8006: 			my ($entry) = split(/&/,$line,2);
                   8007: 			$allusers{$entry} = 1;
                   8008: 		    }
                   8009: 		}
1.253     stredwic 8010:             }
                   8011:             my $alluserstr='';
1.800     albertel 8012:             foreach my $user (sort(keys(%allusers))) {
                   8013:                 $alluserstr.=$user.'&user:';
1.253     stredwic 8014:             }
                   8015:             $alluserstr=~s/:$//;
                   8016:             return split(/:/,$alluserstr);
                   8017:         } else {
1.800     albertel 8018:             return ('missing user name');
1.253     stredwic 8019:         }
1.955     raeburn  8020:     } elsif(!defined($getpropath)) {
1.841     albertel 8021:         my @all_domains = sort(&all_domains());
1.955     raeburn  8022:         foreach my $domain (@all_domains) {
                   8023:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   8024:         }
                   8025:         return @all_domains;
                   8026:     } else {
1.800     albertel 8027:         return ('missing domain');
1.275     stredwic 8028:     }
                   8029: }
                   8030: 
                   8031: # --------------------------------------------- GetFileTimestamp
                   8032: # This function utilizes dirlist and returns the date stamp for
                   8033: # when it was last modified.  It will also return an error of -1
                   8034: # if an error occurs
                   8035: 
                   8036: sub GetFileTimestamp {
1.955     raeburn  8037:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8038:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8039:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  8040:     my ($fileStat) = 
                   8041:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   8042:                                  undef,$getuserdir);
1.275     stredwic 8043:     my @stats = split('&', $fileStat);
                   8044:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  8045:         # @stats contains first the filename, then the stat output
                   8046:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8047:     } else {
                   8048:         return -1;
1.253     stredwic 8049:     }
1.26      www      8050: }
                   8051: 
1.712     albertel 8052: sub stat_file {
                   8053:     my ($uri) = @_;
1.787     albertel 8054:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8055: 
1.955     raeburn  8056:     my ($udom,$uname,$file);
1.712     albertel 8057:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8058: 	($udom,$uname,$file) =
1.811     albertel 8059: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8060: 	$file = 'userfiles/'.$file;
                   8061:     }
                   8062:     if ($uri =~ m-^/res/-) {
                   8063: 	($udom,$uname) = 
1.807     albertel 8064: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8065: 	$file = $uri;
                   8066:     }
                   8067: 
                   8068:     if (!$udom || !$uname || !$file) {
                   8069: 	# unable to handle the uri
                   8070: 	return ();
                   8071:     }
1.956     raeburn  8072:     my $getpropath;
                   8073:     if ($file =~ /^userfiles\//) {
                   8074:         $getpropath = 1;
                   8075:     }
1.955     raeburn  8076:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8077:     my @stats = split('&', $result);
1.721     banghart 8078:     
1.712     albertel 8079:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8080: 	shift(@stats); #filename is first
                   8081: 	return @stats;
                   8082:     }
                   8083:     return ();
                   8084: }
                   8085: 
1.26      www      8086: # -------------------------------------------------------- Value of a Condition
                   8087: 
1.713     albertel 8088: # gets the value of a specific preevaluated condition
                   8089: #    stored in the string  $env{user.state.<cid>}
                   8090: # or looks up a condition reference in the bighash and if if hasn't
                   8091: # already been evaluated recurses into docondval to get the value of
                   8092: # the condition, then memoizing it to 
                   8093: #   $env{user.state.<cid>.<condition>}
1.40      www      8094: sub directcondval {
                   8095:     my $number=shift;
1.620     albertel 8096:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8097: 	&Apache::lonuserstate::evalstate();
                   8098:     }
1.713     albertel 8099:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8100: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8101:     } elsif ($number =~ /^_/) {
                   8102: 	my $sub_condition;
                   8103: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8104: 		&GDBM_READER(),0640)) {
                   8105: 	    $sub_condition=$bighash{'conditions'.$number};
                   8106: 	    untie(%bighash);
                   8107: 	}
                   8108: 	my $value = &docondval($sub_condition);
1.949     raeburn  8109: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8110: 	return $value;
                   8111:     }
1.620     albertel 8112:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8113:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8114:     } else {
                   8115:        return 2;
                   8116:     }
                   8117: }
                   8118: 
1.713     albertel 8119: # get the collection of conditions for this resource
1.26      www      8120: sub condval {
                   8121:     my $condidx=shift;
1.54      www      8122:     my $allpathcond='';
1.713     albertel 8123:     foreach my $cond (split(/\|/,$condidx)) {
                   8124: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8125: 	    $allpathcond.=
                   8126: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8127: 	}
1.191     harris41 8128:     }
1.54      www      8129:     $allpathcond=~s/\|$//;
1.713     albertel 8130:     return &docondval($allpathcond);
                   8131: }
                   8132: 
                   8133: #evaluates an expression of conditions
                   8134: sub docondval {
                   8135:     my ($allpathcond) = @_;
                   8136:     my $result=0;
                   8137:     if ($env{'request.course.id'}
                   8138: 	&& defined($allpathcond)) {
                   8139: 	my $operand='|';
                   8140: 	my @stack;
                   8141: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8142: 	    if ($chunk eq '(') {
                   8143: 		push @stack,($operand,$result);
                   8144: 	    } elsif ($chunk eq ')') {
                   8145: 		my $before=pop @stack;
                   8146: 		if (pop @stack eq '&') {
                   8147: 		    $result=$result>$before?$before:$result;
                   8148: 		} else {
                   8149: 		    $result=$result>$before?$result:$before;
                   8150: 		}
                   8151: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8152: 		$operand=$chunk;
                   8153: 	    } else {
                   8154: 		my $new=directcondval($chunk);
                   8155: 		if ($operand eq '&') {
                   8156: 		    $result=$result>$new?$new:$result;
                   8157: 		} else {
                   8158: 		    $result=$result>$new?$result:$new;
                   8159: 		}
                   8160: 	    }
                   8161: 	}
1.26      www      8162:     }
                   8163:     return $result;
1.421     albertel 8164: }
                   8165: 
                   8166: # ---------------------------------------------------- Devalidate courseresdata
                   8167: 
                   8168: sub devalidatecourseresdata {
                   8169:     my ($coursenum,$coursedomain)=@_;
                   8170:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8171:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8172: }
                   8173: 
1.763     www      8174: 
1.200     www      8175: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8176: #
                   8177: #  Parameters:
                   8178: #      $coursenum    - Number of the course.
                   8179: #      $coursedomain - Domain at which the course was created.
                   8180: #  Returns:
                   8181: #     A hash of the course parameters along (I think) with timestamps
                   8182: #     and version info.
1.877     foxr     8183: 
1.624     albertel 8184: sub get_courseresdata {
                   8185:     my ($coursenum,$coursedomain)=@_;
1.200     www      8186:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8187:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8188:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8189:     my %dumpreply;
1.417     albertel 8190:     unless (defined($cached)) {
1.624     albertel 8191: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8192: 	$result=\%dumpreply;
1.251     albertel 8193: 	my ($tmp) = keys(%dumpreply);
                   8194: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8195: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8196: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8197: 	    return $tmp;
1.416     albertel 8198: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8199: 	    $result=undef;
1.599     albertel 8200: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8201: 	}
                   8202:     }
1.624     albertel 8203:     return $result;
                   8204: }
                   8205: 
1.633     albertel 8206: sub devalidateuserresdata {
                   8207:     my ($uname,$udom)=@_;
                   8208:     my $hashid="$udom:$uname";
                   8209:     &devalidate_cache_new('userres',$hashid);
                   8210: }
                   8211: 
1.624     albertel 8212: sub get_userresdata {
                   8213:     my ($uname,$udom)=@_;
                   8214:     #most student don\'t have any data set, check if there is some data
                   8215:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8216: 
                   8217:     my $hashid="$udom:$uname";
                   8218:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8219:     if (!defined($cached)) {
                   8220: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8221: 	$result=\%resourcedata;
                   8222: 	&do_cache_new('userres',$hashid,$result,600);
                   8223:     }
                   8224:     my ($tmp)=keys(%$result);
                   8225:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8226: 	return $result;
                   8227:     }
                   8228:     #error 2 occurs when the .db doesn't exist
                   8229:     if ($tmp!~/error: 2 /) {
1.672     albertel 8230: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8231: 		 " Trying to get resource data for ".
                   8232: 		 $uname." at ".$udom.": ".
                   8233: 		 $tmp."</font>");
                   8234:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8235: 	#&EXT_cache_set($udom,$uname);
                   8236: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8237: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8238:     }
                   8239:     return $tmp;
                   8240: }
1.879     foxr     8241: #----------------------------------------------- resdata - return resource data
                   8242: #  Purpose:
                   8243: #    Return resource data for either users or for a course.
                   8244: #  Parameters:
                   8245: #     $name      - Course/user name.
                   8246: #     $domain    - Name of the domain the user/course is registered on.
                   8247: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8248: #     @which     - Array of names of resources desired.
                   8249: #  Returns:
                   8250: #     The value of the first reasource in @which that is found in the
                   8251: #     resource hash.
                   8252: #  Exceptional Conditions:
                   8253: #     If the $type passed in is not valid (not the string 'course' or 
                   8254: #     'user', an undefined  reference is returned.
                   8255: #     If none of the resources are found, an undef is returned
1.624     albertel 8256: sub resdata {
                   8257:     my ($name,$domain,$type,@which)=@_;
                   8258:     my $result;
                   8259:     if ($type eq 'course') {
                   8260: 	$result=&get_courseresdata($name,$domain);
                   8261:     } elsif ($type eq 'user') {
                   8262: 	$result=&get_userresdata($name,$domain);
                   8263:     }
                   8264:     if (!ref($result)) { return $result; }    
1.251     albertel 8265:     foreach my $item (@which) {
1.927     albertel 8266: 	if (defined($result->{$item->[0]})) {
                   8267: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8268: 	}
1.250     albertel 8269:     }
1.291     albertel 8270:     return undef;
1.200     www      8271: }
                   8272: 
1.379     matthew  8273: #
                   8274: # EXT resource caching routines
                   8275: #
                   8276: 
                   8277: sub clear_EXT_cache_status {
1.383     albertel 8278:     &delenv('cache.EXT.');
1.379     matthew  8279: }
                   8280: 
                   8281: sub EXT_cache_status {
                   8282:     my ($target_domain,$target_user) = @_;
1.383     albertel 8283:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8284:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8285:         # We know already the user has no data
                   8286:         return 1;
                   8287:     } else {
                   8288:         return 0;
                   8289:     }
                   8290: }
                   8291: 
                   8292: sub EXT_cache_set {
                   8293:     my ($target_domain,$target_user) = @_;
1.383     albertel 8294:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8295:     #&appenv({$cachename => time});
1.379     matthew  8296: }
                   8297: 
1.28      www      8298: # --------------------------------------------------------- Value of a Variable
1.58      www      8299: sub EXT {
1.715     albertel 8300: 
1.395     albertel 8301:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8302:     unless ($varname) { return ''; }
1.218     albertel 8303:     #get real user name/domain, courseid and symb
                   8304:     my $courseid;
1.359     albertel 8305:     my $publicuser;
1.427     www      8306:     if ($symbparm) {
                   8307: 	$symbparm=&get_symb_from_alias($symbparm);
                   8308:     }
1.218     albertel 8309:     if (!($uname && $udom)) {
1.790     albertel 8310:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8311:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8312:     } else {
1.620     albertel 8313: 	$courseid=$env{'request.course.id'};
1.218     albertel 8314:     }
1.48      www      8315:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8316:     my $rest;
1.320     albertel 8317:     if (defined($therest[0])) {
1.48      www      8318:        $rest=join('.',@therest);
                   8319:     } else {
                   8320:        $rest='';
                   8321:     }
1.320     albertel 8322: 
1.57      www      8323:     my $qualifierrest=$qualifier;
                   8324:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8325:     my $spacequalifierrest=$space;
                   8326:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8327:     if ($realm eq 'user') {
1.48      www      8328: # --------------------------------------------------------------- user.resource
                   8329: 	if ($space eq 'resource') {
1.651     albertel 8330: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8331: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8332: 		 &&
1.744     albertel 8333: 		 ($symbparm eq &symbread()) ) {	
                   8334: 		# if we are in the middle of processing the resource the
                   8335: 		# get the value we are planning on committing
                   8336:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8337:                     return $Apache::lonhomework::results{$qualifierrest};
                   8338:                 } else {
                   8339:                     return $Apache::lonhomework::history{$qualifierrest};
                   8340:                 }
1.335     albertel 8341: 	    } else {
1.359     albertel 8342: 		my %restored;
1.620     albertel 8343: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8344: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8345: 		} else {
                   8346: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8347: 		}
1.335     albertel 8348: 		return $restored{$qualifierrest};
                   8349: 	    }
1.48      www      8350: # ----------------------------------------------------------------- user.access
                   8351:         } elsif ($space eq 'access') {
1.218     albertel 8352: 	    # FIXME - not supporting calls for a specific user
1.48      www      8353:             return &allowed($qualifier,$rest);
                   8354: # ------------------------------------------ user.preferences, user.environment
                   8355:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8356: 	    if (($uname eq $env{'user.name'}) &&
                   8357: 		($udom eq $env{'user.domain'})) {
                   8358: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8359: 	    } else {
1.359     albertel 8360: 		my %returnhash;
                   8361: 		if (!$publicuser) {
                   8362: 		    %returnhash=&userenvironment($udom,$uname,
                   8363: 						 $qualifierrest);
                   8364: 		}
1.218     albertel 8365: 		return $returnhash{$qualifierrest};
                   8366: 	    }
1.48      www      8367: # ----------------------------------------------------------------- user.course
                   8368:         } elsif ($space eq 'course') {
1.218     albertel 8369: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8370:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8371: # ------------------------------------------------------------------- user.role
                   8372:         } elsif ($space eq 'role') {
1.218     albertel 8373: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8374:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8375:             if ($qualifier eq 'value') {
                   8376: 		return $role;
                   8377:             } elsif ($qualifier eq 'extent') {
                   8378:                 return $where;
                   8379:             }
                   8380: # ----------------------------------------------------------------- user.domain
                   8381:         } elsif ($space eq 'domain') {
1.218     albertel 8382:             return $udom;
1.48      www      8383: # ------------------------------------------------------------------- user.name
                   8384:         } elsif ($space eq 'name') {
1.218     albertel 8385:             return $uname;
1.48      www      8386: # ---------------------------------------------------- Any other user namespace
1.29      www      8387:         } else {
1.359     albertel 8388: 	    my %reply;
                   8389: 	    if (!$publicuser) {
                   8390: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8391: 	    }
                   8392: 	    return $reply{$qualifierrest};
1.48      www      8393:         }
1.236     www      8394:     } elsif ($realm eq 'query') {
                   8395: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8396:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8397: 						[$spacequalifierrest]);
1.620     albertel 8398: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8399:    } elsif ($realm eq 'request') {
1.48      www      8400: # ------------------------------------------------------------- request.browser
                   8401:         if ($space eq 'browser') {
1.430     www      8402: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8403: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8404: 		    return 1;
                   8405: 		} else {
                   8406: 		    return 0;
                   8407: 		}
                   8408: 	    } else {
1.620     albertel 8409: 		return $env{'browser.'.$qualifier};
1.430     www      8410: 	    }
1.57      www      8411: # ------------------------------------------------------------ request.filename
                   8412:         } else {
1.620     albertel 8413:             return $env{'request.'.$spacequalifierrest};
1.29      www      8414:         }
1.28      www      8415:     } elsif ($realm eq 'course') {
1.48      www      8416: # ---------------------------------------------------------- course.description
1.620     albertel 8417:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8418:     } elsif ($realm eq 'resource') {
1.165     www      8419: 
1.620     albertel 8420: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8421: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8422: 	}
1.693     albertel 8423: 
                   8424: 	if ($space eq 'title') {
                   8425: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8426: 	    return &gettitle($symbparm);
                   8427: 	}
                   8428: 	
                   8429: 	if ($space eq 'map') {
                   8430: 	    my ($map) = &decode_symb($symbparm);
                   8431: 	    return &symbread($map);
                   8432: 	}
1.905     albertel 8433: 	if ($space eq 'filename') {
                   8434: 	    if ($symbparm) {
                   8435: 		return &clutter((&decode_symb($symbparm))[2]);
                   8436: 	    }
                   8437: 	    return &hreflocation('',$env{'request.filename'});
                   8438: 	}
1.693     albertel 8439: 
                   8440: 	my ($section, $group, @groups);
1.593     albertel 8441: 	my ($courselevelm,$courselevel);
1.539     albertel 8442: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8443: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8444: 
1.218     albertel 8445: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8446: 
1.60      www      8447: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8448: 	    my $symbp=$symbparm;
1.735     albertel 8449: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8450: 
                   8451: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8452: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8453: 
1.620     albertel 8454: 	    if (($env{'user.name'} eq $uname) &&
                   8455: 		($env{'user.domain'} eq $udom)) {
                   8456: 		$section=$env{'request.course.sec'};
1.733     raeburn  8457:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8458:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8459: 	    } else {
1.539     albertel 8460: 		if (! defined($usection)) {
1.551     albertel 8461: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8462: 		} else {
                   8463: 		    $section = $usection;
                   8464: 		}
1.733     raeburn  8465:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8466: 	    }
                   8467: 
                   8468: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8469: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8470: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8471: 
1.593     albertel 8472: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8473: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8474: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8475: 
1.60      www      8476: # ----------------------------------------------------------- first, check user
1.624     albertel 8477: 
                   8478: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8479: 				       ([$courselevelr,'resource'],
                   8480: 					[$courselevelm,'map'     ],
                   8481: 					[$courselevel, 'course'  ]));
1.931     albertel 8482: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8483: 
1.594     albertel 8484: # ------------------------------------------------ second, check some of course
1.684     raeburn  8485:             my $coursereply;
1.691     raeburn  8486:             if (@groups > 0) {
                   8487:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8488:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8489:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8490:             }
1.96      www      8491: 
1.684     raeburn  8492: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8493: 				  $env{'course.'.$courseid.'.domain'},
                   8494: 				  'course',
                   8495: 				  ([$seclevelr,   'resource'],
                   8496: 				   [$seclevelm,   'map'     ],
                   8497: 				   [$seclevel,    'course'  ],
                   8498: 				   [$courselevelr,'resource']));
                   8499: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8500: 
1.60      www      8501: # ------------------------------------------------------ third, check map parms
1.218     albertel 8502: 	    my %parmhash=();
                   8503: 	    my $thisparm='';
                   8504: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8505: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8506: 		    &GDBM_READER(),0640)) {
1.218     albertel 8507: 		$thisparm=$parmhash{$symbparm};
                   8508: 		untie(%parmhash);
                   8509: 	    }
1.927     albertel 8510: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8511: 	}
1.594     albertel 8512: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8513: 
1.218     albertel 8514: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8515: 	my $filename;
                   8516: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8517: 	if ($symbparm) {
1.409     www      8518: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8519: 	} else {
1.620     albertel 8520: 	    $filename=$env{'request.filename'};
1.282     albertel 8521: 	}
                   8522: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8523: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8524: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8525: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8526: 
1.927     albertel 8527: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8528: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8529: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8530: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8531: 				     $env{'course.'.$courseid.'.domain'},
                   8532: 				     'course',
1.927     albertel 8533: 				     ([$courselevelm,'map'   ],
                   8534: 				      [$courselevel, 'course']));
                   8535: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8536: 	}
1.145     www      8537: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8538: 	unless ($space eq '0') {
1.336     albertel 8539: 	    my @parts=split(/_/,$space);
                   8540: 	    my $id=pop(@parts);
                   8541: 	    my $part=join('_',@parts);
                   8542: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8543: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8544: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8545: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8546: 	}
1.395     albertel 8547: 	if ($recurse) { return undef; }
                   8548: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8549: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8550: # ---------------------------------------------------- Any other user namespace
                   8551:     } elsif ($realm eq 'environment') {
                   8552: # ----------------------------------------------------------------- environment
1.620     albertel 8553: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8554: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8555: 	} else {
1.770     albertel 8556: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8557: 		return '';
                   8558: 	    }
1.219     albertel 8559: 	    my %returnhash=&userenvironment($udom,$uname,
                   8560: 					    $spacequalifierrest);
                   8561: 	    return $returnhash{$spacequalifierrest};
                   8562: 	}
1.28      www      8563:     } elsif ($realm eq 'system') {
1.48      www      8564: # ----------------------------------------------------------------- system.time
                   8565: 	if ($space eq 'time') {
                   8566: 	    return time;
                   8567:         }
1.696     albertel 8568:     } elsif ($realm eq 'server') {
                   8569: # ----------------------------------------------------------------- system.time
                   8570: 	if ($space eq 'name') {
                   8571: 	    return $ENV{'SERVER_NAME'};
                   8572:         }
1.28      www      8573:     }
1.48      www      8574:     return '';
1.61      www      8575: }
                   8576: 
1.927     albertel 8577: sub get_reply {
                   8578:     my ($reply_value) = @_;
1.940     raeburn  8579:     if (ref($reply_value) eq 'ARRAY') {
                   8580:         if (wantarray) {
                   8581: 	    return @$reply_value;
                   8582:         }
                   8583:         return $reply_value->[0];
                   8584:     } else {
                   8585:         return $reply_value;
1.927     albertel 8586:     }
                   8587: }
                   8588: 
1.691     raeburn  8589: sub check_group_parms {
                   8590:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8591:     my @groupitems = ();
                   8592:     my $resultitem;
1.927     albertel 8593:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8594:     foreach my $group (@{$groups}) {
                   8595:         foreach my $level (@levels) {
1.927     albertel 8596:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8597:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8598:         }
                   8599:     }
                   8600:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8601:                             $env{'course.'.$courseid.'.domain'},
                   8602:                                      'course',@groupitems);
                   8603:     return $coursereply;
                   8604: }
                   8605: 
                   8606: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8607:     my ($courseid,@groups) = @_;
                   8608:     @groups = sort(@groups);
1.691     raeburn  8609:     return @groups;
                   8610: }
                   8611: 
1.395     albertel 8612: sub packages_tab_default {
                   8613:     my ($uri,$varname)=@_;
                   8614:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8615: 
                   8616:     my (@extension,@specifics,$do_default);
                   8617:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8618: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8619: 	if ($pack_type eq 'default') {
                   8620: 	    $do_default=1;
                   8621: 	} elsif ($pack_type eq 'extension') {
                   8622: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8623: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8624: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8625: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8626: 	}
                   8627:     }
                   8628:     # first look for a package that matches the requested part id
                   8629:     foreach my $package (@specifics) {
                   8630: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8631: 	next if ($pack_part ne $part);
                   8632: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8633: 	    return $packagetab{"$pack_type&$name&default"};
                   8634: 	}
                   8635:     }
                   8636:     # look for any possible matching non extension_ package
                   8637:     foreach my $package (@specifics) {
                   8638: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8639: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8640: 	    return $packagetab{"$pack_type&$name&default"};
                   8641: 	}
1.585     albertel 8642: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8643: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8644: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8645: 	}
                   8646:     }
1.738     albertel 8647:     # look for any posible extension_ match
                   8648:     foreach my $package (@extension) {
                   8649: 	my ($package,$pack_type)=@{$package};
                   8650: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8651: 	    return $packagetab{"$pack_type&$name&default"};
                   8652: 	}
                   8653: 	if (defined($packagetab{$package."&$name&default"})) {
                   8654: 	    return $packagetab{$package."&$name&default"};
                   8655: 	}
                   8656:     }
                   8657:     # look for a global default setting
                   8658:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8659: 	return $packagetab{"default&$name&default"};
                   8660:     }
1.395     albertel 8661:     return undef;
                   8662: }
                   8663: 
1.334     albertel 8664: sub add_prefix_and_part {
                   8665:     my ($prefix,$part)=@_;
                   8666:     my $keyroot;
                   8667:     if (defined($prefix) && $prefix !~ /^__/) {
                   8668: 	# prefix that has a part already
                   8669: 	$keyroot=$prefix;
                   8670:     } elsif (defined($prefix)) {
                   8671: 	# prefix that is missing a part
                   8672: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8673:     } else {
                   8674: 	# no prefix at all
                   8675: 	if (defined($part)) { $keyroot='_'.$part; }
                   8676:     }
                   8677:     return $keyroot;
                   8678: }
                   8679: 
1.71      www      8680: # ---------------------------------------------------------------- Get metadata
                   8681: 
1.599     albertel 8682: my %metaentry;
1.1070    www      8683: my %importedpartids;
1.71      www      8684: sub metadata {
1.176     www      8685:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8686:     $uri=&declutter($uri);
1.288     albertel 8687:     # if it is a non metadata possible uri return quickly
1.529     albertel 8688:     if (($uri eq '') || 
                   8689: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8690: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8691:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8692: 	return undef;
                   8693:     }
                   8694:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8695: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8696: 	return undef;
1.288     albertel 8697:     }
1.73      www      8698:     my $filename=$uri;
                   8699:     $uri=~s/\.meta$//;
1.172     www      8700: #
                   8701: # Is the metadata already cached?
1.177     www      8702: # Look at timestamp of caching
1.172     www      8703: # Everything is cached by the main uri, libraries are never directly cached
                   8704: #
1.428     albertel 8705:     if (!defined($liburi)) {
1.599     albertel 8706: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8707: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8708:     }
                   8709:     {
1.1069    www      8710: # Imported parts would go here
1.1070    www      8711:         my %importedids=();
                   8712:         my @origfileimportpartids=();
1.1069    www      8713:         my $importedparts=0;
1.172     www      8714: #
                   8715: # Is this a recursive call for a library?
                   8716: #
1.599     albertel 8717: #	if (! exists($metacache{$uri})) {
                   8718: #	    $metacache{$uri}={};
                   8719: #	}
1.924     albertel 8720: 	my $cachetime = 60*60;
1.171     www      8721:         if ($liburi) {
                   8722: 	    $liburi=&declutter($liburi);
                   8723:             $filename=$liburi;
1.401     bowersj2 8724:         } else {
1.599     albertel 8725: 	    &devalidate_cache_new('meta',$uri);
                   8726: 	    undef(%metaentry);
1.401     bowersj2 8727: 	}
1.140     www      8728:         my %metathesekeys=();
1.73      www      8729:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8730: 	my $metastring;
1.924     albertel 8731: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8732: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8733: 	    $metastring = 
1.929     albertel 8734: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8735: 					  ('grade_target' => 'meta'));
                   8736: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8737: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8738:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8739: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8740: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8741: 	    $metastring=&getfile($file);
1.489     albertel 8742: 	}
1.208     albertel 8743:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8744:         my $token;
1.140     www      8745:         undef %metathesekeys;
1.71      www      8746:         while ($token=$parser->get_token) {
1.339     albertel 8747: 	    if ($token->[0] eq 'S') {
                   8748: 		if (defined($token->[2]->{'package'})) {
1.172     www      8749: #
                   8750: # This is a package - get package info
                   8751: #
1.339     albertel 8752: 		    my $package=$token->[2]->{'package'};
                   8753: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8754: 		    if (defined($token->[2]->{'id'})) { 
                   8755: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8756: 		    }
1.599     albertel 8757: 		    if ($metaentry{':packages'}) {
                   8758: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8759: 		    } else {
1.599     albertel 8760: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8761: 		    }
1.736     albertel 8762: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8763: 			my $part=$keyroot;
                   8764: 			$part=~s/^\_//;
1.736     albertel 8765: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8766: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8767: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8768: 			    # ignore package.tab specified default values
                   8769:                             # here &package_tab_default() will fetch those
                   8770: 			    if ($subp eq 'default') { next; }
1.736     albertel 8771: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8772: 			    my $unikey;
                   8773: 			    if ($pack =~ /_0$/) {
                   8774: 				$unikey='parameter_0_'.$name;
                   8775: 				$part=0;
                   8776: 			    } else {
                   8777: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8778: 			    }
1.339     albertel 8779: 			    if ($subp eq 'display') {
                   8780: 				$value.=' [Part: '.$part.']';
                   8781: 			    }
1.599     albertel 8782: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8783: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8784: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8785: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8786: 			    }
1.599     albertel 8787: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8788: 				$metaentry{':'.$unikey}=
                   8789: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8790: 			    }
1.339     albertel 8791: 			}
                   8792: 		    }
                   8793: 		} else {
1.172     www      8794: #
                   8795: # This is not a package - some other kind of start tag
1.339     albertel 8796: #
                   8797: 		    my $entry=$token->[1];
1.1068    www      8798: 		    my $unikey='';
1.175     www      8799: 
1.339     albertel 8800: 		    if ($entry eq 'import') {
1.175     www      8801: #
                   8802: # Importing a library here
1.339     albertel 8803: #
1.1067    www      8804:                         my $location=$parser->get_text('/import');
                   8805:                         my $dir=$filename;
                   8806:                         $dir=~s|[^/]*$||;
                   8807:                         $location=&filelocation($dir,$location);
1.1069    www      8808:                        
1.1068    www      8809:                         my $importmode=$token->[2]->{'importmode'};
                   8810:                         if ($importmode eq 'problem') {
1.1069    www      8811: # Import as problem/response
1.1068    www      8812:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8813:                         } elsif ($importmode eq 'part') {
                   8814: # Import as part(s)
1.1069    www      8815:                            $importedparts=1;
                   8816: # We need to get the original file and the imported file to get the part order correct
                   8817: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8818: # Load and inspect original file
1.1070    www      8819:                            if ($#origfileimportpartids<0) {
                   8820:                               undef(%importedpartids);
                   8821:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8822:                               my $origfile=&getfile($origfilelocation);
                   8823:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8824:                            }
                   8825: 
1.1069    www      8826: # Load and inspect imported file
                   8827:                            my $impfile=&getfile($location);
                   8828:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8829:                            if ($#impfilepartids>=0) {
                   8830: # This problem had parts
1.1070    www      8831:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8832:                            } else {
                   8833: # Importing by turning a single problem into a problem part
                   8834: # It gets the import-tags ID as part-ID
                   8835:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8836:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8837:                            }
1.1068    www      8838:                         } else {
                   8839: # Normal import
                   8840:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8841:                            if (defined($token->[2]->{'id'})) {
                   8842:                               $unikey.='_'.$token->[2]->{'id'};
                   8843:                            }
1.1067    www      8844:                         }
                   8845: 
1.339     albertel 8846: 			if ($depthcount<20) {
1.736     albertel 8847: 			    my $metadata = 
                   8848: 				&metadata($uri,'keys', $location,$unikey,
                   8849: 					  $depthcount+1);
                   8850: 			    foreach my $meta (split(',',$metadata)) {
                   8851: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8852: 				$metathesekeys{$meta}=1;
1.339     albertel 8853: 			    }
1.1068    www      8854: 			
                   8855:                         }
1.1067    www      8856: 		    } else {
                   8857: #
                   8858: # Not importing, some other kind of non-package, non-library start tag
                   8859: # 
                   8860:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8861:                         if (defined($token->[2]->{'id'})) {
                   8862:                             $unikey.='_'.$token->[2]->{'id'};
                   8863:                         }
1.339     albertel 8864: 			if (defined($token->[2]->{'name'})) { 
                   8865: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8866: 			}
                   8867: 			$metathesekeys{$unikey}=1;
1.736     albertel 8868: 			foreach my $param (@{$token->[3]}) {
                   8869: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8870: 				$token->[2]->{$param};
1.339     albertel 8871: 			}
                   8872: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8873: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8874: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8875: 		 # only ws inside the tag, and not in default, so use default
                   8876: 		 # as value
1.599     albertel 8877: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8878: 			} elsif ( $internaltext =~ /\S/ ) {
                   8879: 		  # something interesting inside the tag
                   8880: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8881: 			} else {
1.908     albertel 8882: 		  # no interesting values, don't set a default
1.339     albertel 8883: 			}
1.172     www      8884: # end of not-a-package not-a-library import
1.339     albertel 8885: 		    }
1.172     www      8886: # end of not-a-package start tag
1.339     albertel 8887: 		}
1.172     www      8888: # the next is the end of "start tag"
1.339     albertel 8889: 	    }
                   8890: 	}
1.483     albertel 8891: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8892: 	$extension = lc($extension);
                   8893: 	if ($extension eq 'htm') { $extension='html'; }
                   8894: 
1.737     albertel 8895: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8896: 	    #no specific packages #how's our extension
                   8897: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8898: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8899: 					 \%metathesekeys);
                   8900: 	}
1.883     albertel 8901: 
                   8902: 	if (!exists($metaentry{':packages'})
                   8903: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8904: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8905: 		#no specific packages well let's get default then
                   8906: 		if ($key!~/^default&/) { next; }
1.488     albertel 8907: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8908: 					     \%metathesekeys);
                   8909: 	    }
                   8910: 	}
1.338     www      8911: # are there custom rights to evaluate
1.599     albertel 8912: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8913: 
1.338     www      8914:     #
                   8915:     # Importing a rights file here
1.339     albertel 8916:     #
                   8917: 	    unless ($depthcount) {
1.599     albertel 8918: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8919: 		my $dir=$filename;
                   8920: 		$dir=~s|[^/]*$||;
                   8921: 		$location=&filelocation($dir,$location);
1.736     albertel 8922: 		my $rights_metadata =
                   8923: 		    &metadata($uri,'keys',$location,'_rights',
                   8924: 			      $depthcount+1);
                   8925: 		foreach my $rights (split(',',$rights_metadata)) {
                   8926: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8927: 		    $metathesekeys{$rights}=1;
1.339     albertel 8928: 		}
                   8929: 	    }
                   8930: 	}
1.737     albertel 8931: 	# uniqifiy package listing
                   8932: 	my %seen;
                   8933: 	my @uniq_packages =
                   8934: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8935: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8936: 
1.1070    www      8937:         if ($importedparts) {
                   8938: # We had imported parts and need to rebuild partorder
                   8939:            $metaentry{':partorder'}='';
                   8940:            $metathesekeys{'partorder'}=1;
                   8941:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8942:                if ($origfileimportpartids[$index] eq 'part') {
                   8943: # original part, part of the problem
                   8944:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8945:                } else {
                   8946: # we have imported parts at this position
                   8947:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8948:                }
                   8949:            }
                   8950:            $metaentry{':partorder'}=~s/^\,//;
                   8951:         }
                   8952: 
1.737     albertel 8953: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8954: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8955: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8956: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8957: # this is the end of "was not already recently cached
1.71      www      8958:     }
1.599     albertel 8959:     return $metaentry{':'.$what};
1.261     albertel 8960: }
                   8961: 
1.488     albertel 8962: sub metadata_create_package_def {
1.483     albertel 8963:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8964:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8965:     if ($subp eq 'default') { next; }
                   8966:     
1.599     albertel 8967:     if (defined($metaentry{':packages'})) {
                   8968: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8969:     } else {
1.599     albertel 8970: 	$metaentry{':packages'}=$package;
1.483     albertel 8971:     }
                   8972:     my $value=$packagetab{$key};
                   8973:     my $unikey;
                   8974:     $unikey='parameter_0_'.$name;
1.599     albertel 8975:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8976:     $$metathesekeys{$unikey}=1;
1.599     albertel 8977:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8978: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8979:     }
1.599     albertel 8980:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8981: 	$metaentry{':'.$unikey}=
                   8982: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8983:     }
                   8984: }
                   8985: 
1.261     albertel 8986: sub metadata_generate_part0 {
                   8987:     my ($metadata,$metacache,$uri) = @_;
                   8988:     my %allnames;
1.737     albertel 8989:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8990: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8991: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8992: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8993: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8994: 	    $allnames{$name}=$part;
                   8995: 	  }
                   8996: 	}
                   8997:     }
                   8998:     foreach my $name (keys(%allnames)) {
                   8999:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9000:       my $key=":parameter_0_$name";
1.261     albertel 9001:       $$metacache{"$key.part"}='0';
                   9002:       $$metacache{"$key.name"}=$name;
1.428     albertel 9003:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9004: 					   $allnames{$name}.'_'.$name.
                   9005: 					   '.type'};
1.428     albertel 9006:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9007: 			     '.display'};
1.644     www      9008:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9009:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9010:       $$metacache{"$key.display"}=$olddis;
                   9011:     }
1.71      www      9012: }
                   9013: 
1.764     albertel 9014: # ------------------------------------------------------ Devalidate title cache
                   9015: 
                   9016: sub devalidate_title_cache {
                   9017:     my ($url)=@_;
                   9018:     if (!$env{'request.course.id'}) { return; }
                   9019:     my $symb=&symbread($url);
                   9020:     if (!$symb) { return; }
                   9021:     my $key=$env{'request.course.id'}."\0".$symb;
                   9022:     &devalidate_cache_new('title',$key);
                   9023: }
                   9024: 
1.1014    droeschl 9025: # ------------------------------------------------- Get the title of a course
                   9026: 
                   9027: sub current_course_title {
                   9028:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9029: }
1.301     www      9030: # ------------------------------------------------- Get the title of a resource
                   9031: 
                   9032: sub gettitle {
                   9033:     my $urlsymb=shift;
                   9034:     my $symb=&symbread($urlsymb);
1.534     albertel 9035:     if ($symb) {
1.620     albertel 9036: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9037: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9038: 	if (defined($cached)) { 
                   9039: 	    return $result;
                   9040: 	}
1.534     albertel 9041: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9042: 	my $title='';
1.907     albertel 9043: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9044: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9045: 	} else {
                   9046: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9047: 		    &GDBM_READER(),0640)) {
                   9048: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9049: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9050: 		untie(%bighash);
                   9051: 	    }
1.534     albertel 9052: 	}
                   9053: 	$title=~s/\&colon\;/\:/gs;
                   9054: 	if ($title) {
1.599     albertel 9055: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9056: 	}
                   9057: 	$urlsymb=$url;
                   9058:     }
                   9059:     my $title=&metadata($urlsymb,'title');
                   9060:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9061:     return $title;
1.301     www      9062: }
1.613     albertel 9063: 
1.614     albertel 9064: sub get_slot {
                   9065:     my ($which,$cnum,$cdom)=@_;
                   9066:     if (!$cnum || !$cdom) {
1.790     albertel 9067: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9068: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9069: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9070:     }
1.703     albertel 9071:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9072:     my %slotinfo;
                   9073:     if (exists($remembered{$key})) {
                   9074: 	$slotinfo{$which} = $remembered{$key};
                   9075:     } else {
                   9076: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9077: 	&Apache::lonhomework::showhash(%slotinfo);
                   9078: 	my ($tmp)=keys(%slotinfo);
                   9079: 	if ($tmp=~/^error:/) { return (); }
                   9080: 	$remembered{$key} = $slotinfo{$which};
                   9081:     }
1.616     albertel 9082:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9083: 	return %{$slotinfo{$which}};
                   9084:     }
                   9085:     return $slotinfo{$which};
1.614     albertel 9086: }
1.31      www      9087: # ------------------------------------------------- Update symbolic store links
                   9088: 
                   9089: sub symblist {
                   9090:     my ($mapname,%newhash)=@_;
1.438     www      9091:     $mapname=&deversion(&declutter($mapname));
1.31      www      9092:     my %hash;
1.620     albertel 9093:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9094:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9095:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9096: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9097: 		next if ($url eq 'last_known'
                   9098: 			 && $env{'form.no_update_last_known'});
                   9099: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9100: 						    $newhash{$url}->[1],
                   9101: 						    $newhash{$url}->[0]);
1.191     harris41 9102:             }
1.31      www      9103:             if (untie(%hash)) {
                   9104: 		return 'ok';
                   9105:             }
                   9106:         }
                   9107:     }
                   9108:     return 'error';
1.212     www      9109: }
                   9110: 
                   9111: # --------------------------------------------------------------- Verify a symb
                   9112: 
                   9113: sub symbverify {
1.510     www      9114:     my ($symb,$thisurl)=@_;
                   9115:     my $thisfn=$thisurl;
1.439     www      9116:     $thisfn=&declutter($thisfn);
1.215     www      9117: # direct jump to resource in page or to a sequence - will construct own symbs
                   9118:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9119: # check URL part
1.409     www      9120:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9121: 
1.431     www      9122:     unless ($url eq $thisfn) { return 0; }
1.213     www      9123: 
1.216     www      9124:     $symb=&symbclean($symb);
1.510     www      9125:     $thisurl=&deversion($thisurl);
1.439     www      9126:     $thisfn=&deversion($thisfn);
1.213     www      9127: 
                   9128:     my %bighash;
                   9129:     my $okay=0;
1.431     www      9130: 
1.620     albertel 9131:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9132:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9133:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9134:             $thisurl =~ s/\?.+$//;
                   9135:         }
1.510     www      9136:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9137:         unless ($ids) {
                   9138:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9139:             $ids=$bighash{$idkey};
1.216     www      9140:         }
                   9141:         if ($ids) {
                   9142: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9143: 	    foreach my $id (split(/\,/,$ids)) {
                   9144: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9145:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9146:                    $symb =~ s/\?.+$//;
                   9147:                }
1.216     www      9148:                if (
                   9149:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9150:    eq $symb) { 
1.620     albertel 9151: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9152: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9153:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9154: 		       $okay=1; 
                   9155: 		   }
                   9156: 	       }
1.216     www      9157: 	   }
                   9158:         }
1.213     www      9159: 	untie(%bighash);
                   9160:     }
                   9161:     return $okay;
1.31      www      9162: }
                   9163: 
1.210     www      9164: # --------------------------------------------------------------- Clean-up symb
                   9165: 
                   9166: sub symbclean {
                   9167:     my $symb=shift;
1.568     albertel 9168:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9169: # remove version from map
                   9170:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9171: 
1.210     www      9172: # remove version from URL
                   9173:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9174: 
1.507     www      9175: # remove wrapper
                   9176: 
1.510     www      9177:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9178:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9179:     return $symb;
1.409     www      9180: }
                   9181: 
                   9182: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9183: 
                   9184: sub encode_symb {
                   9185:     my ($map,$resid,$url)=@_;
                   9186:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9187: }
1.409     www      9188: 
                   9189: sub decode_symb {
1.568     albertel 9190:     my $symb=shift;
                   9191:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9192:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9193:     return (&fixversion($map),$resid,&fixversion($url));
                   9194: }
                   9195: 
                   9196: sub fixversion {
                   9197:     my $fn=shift;
1.609     banghart 9198:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9199:     my %bighash;
                   9200:     my $uri=&clutter($fn);
1.620     albertel 9201:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9202: # is this cached?
1.599     albertel 9203:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9204:     if (defined($cached)) { return $result; }
                   9205: # unfortunately not cached, or expired
1.620     albertel 9206:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9207: 	    &GDBM_READER(),0640)) {
                   9208:  	if ($bighash{'version_'.$uri}) {
                   9209:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9210:  	    unless (($version eq 'mostrecent') || 
                   9211: 		    ($version==&getversion($uri))) {
1.440     www      9212:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9213:  	    }
                   9214:  	}
                   9215:  	untie %bighash;
1.413     www      9216:     }
1.599     albertel 9217:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9218: }
                   9219: 
                   9220: sub deversion {
                   9221:     my $url=shift;
                   9222:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9223:     return $url;
1.210     www      9224: }
                   9225: 
1.31      www      9226: # ------------------------------------------------------ Return symb list entry
                   9227: 
                   9228: sub symbread {
1.249     www      9229:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9230:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9231:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9232: # no filename provided? try from environment
1.44      www      9233:     unless ($thisfn) {
1.620     albertel 9234:         if ($env{'request.symb'}) {
                   9235: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9236: 	}
1.620     albertel 9237: 	$thisfn=$env{'request.filename'};
1.44      www      9238:     }
1.569     albertel 9239:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9240: # is that filename actually a symb? Verify, clean, and return
                   9241:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9242: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9243: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9244: 	}
1.242     www      9245:     }
1.44      www      9246:     $thisfn=declutter($thisfn);
1.31      www      9247:     my %hash;
1.37      www      9248:     my %bighash;
                   9249:     my $syval='';
1.620     albertel 9250:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9251:         my $targetfn = $thisfn;
1.609     banghart 9252:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9253:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9254:         }
1.687     albertel 9255: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9256: 	    $targetfn=$1;
                   9257: 	}
1.620     albertel 9258:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9259:                       &GDBM_READER(),0640)) {
1.481     raeburn  9260: 	    $syval=$hash{$targetfn};
1.37      www      9261:             untie(%hash);
                   9262:         }
                   9263: # ---------------------------------------------------------- There was an entry
                   9264:         if ($syval) {
1.601     albertel 9265: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9266: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9267: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9268: 		    #return $env{$cache_str}='';
1.601     albertel 9269: 		#}    
                   9270: 		#$syval.=$1;
                   9271: 	    #}
1.37      www      9272:         } else {
                   9273: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9274:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9275:                             &GDBM_READER(),0640)) {
1.37      www      9276: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9277:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9278:               unless ($ids) { 
                   9279:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9280:               }
                   9281:               unless ($ids) {
                   9282: # alias?
                   9283: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9284:               }
1.37      www      9285:               if ($ids) {
                   9286: # ------------------------------------------------------------------- Has ID(s)
                   9287:                  my @possibilities=split(/\,/,$ids);
1.39      www      9288:                  if ($#possibilities==0) {
                   9289: # ----------------------------------------------- There is only one possibility
1.37      www      9290: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9291: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9292: 						    $resid,$thisfn);
1.249     www      9293:                  } elsif (!$donotrecurse) {
1.39      www      9294: # ------------------------------------------ There is more than one possibility
                   9295:                      my $realpossible=0;
1.800     albertel 9296:                      foreach my $id (@possibilities) {
                   9297: 			 my $file=$bighash{'src_'.$id};
1.39      www      9298:                          if (&allowed('bre',$file)) {
1.800     albertel 9299:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9300:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9301: 				$realpossible++;
1.626     albertel 9302:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9303: 						    $resid,$thisfn);
1.39      www      9304:                             }
                   9305: 			 }
1.191     harris41 9306:                      }
1.39      www      9307: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9308:                  } else {
                   9309:                      $syval='';
1.37      www      9310:                  }
                   9311: 	      }
                   9312:               untie(%bighash)
1.481     raeburn  9313:            }
1.31      www      9314:         }
1.62      www      9315:         if ($syval) {
1.620     albertel 9316: 	    return $env{$cache_str}=$syval;
1.62      www      9317:         }
1.31      www      9318:     }
1.949     raeburn  9319:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9320:     return $env{$cache_str}='';
1.31      www      9321: }
                   9322: 
                   9323: # ---------------------------------------------------------- Return random seed
                   9324: 
1.32      www      9325: sub numval {
                   9326:     my $txt=shift;
                   9327:     $txt=~tr/A-J/0-9/;
                   9328:     $txt=~tr/a-j/0-9/;
                   9329:     $txt=~tr/K-T/0-9/;
                   9330:     $txt=~tr/k-t/0-9/;
                   9331:     $txt=~tr/U-Z/0-5/;
                   9332:     $txt=~tr/u-z/0-5/;
                   9333:     $txt=~s/\D//g;
1.564     albertel 9334:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9335:     return int($txt);
1.368     albertel 9336: }
                   9337: 
1.484     albertel 9338: sub numval2 {
                   9339:     my $txt=shift;
                   9340:     $txt=~tr/A-J/0-9/;
                   9341:     $txt=~tr/a-j/0-9/;
                   9342:     $txt=~tr/K-T/0-9/;
                   9343:     $txt=~tr/k-t/0-9/;
                   9344:     $txt=~tr/U-Z/0-5/;
                   9345:     $txt=~tr/u-z/0-5/;
                   9346:     $txt=~s/\D//g;
                   9347:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9348:     my $total;
                   9349:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9350:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9351:     return int($total);
                   9352: }
                   9353: 
1.575     albertel 9354: sub numval3 {
                   9355:     use integer;
                   9356:     my $txt=shift;
                   9357:     $txt=~tr/A-J/0-9/;
                   9358:     $txt=~tr/a-j/0-9/;
                   9359:     $txt=~tr/K-T/0-9/;
                   9360:     $txt=~tr/k-t/0-9/;
                   9361:     $txt=~tr/U-Z/0-5/;
                   9362:     $txt=~tr/u-z/0-5/;
                   9363:     $txt=~s/\D//g;
                   9364:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9365:     my $total;
                   9366:     foreach my $val (@txts) { $total+=$val; }
                   9367:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9368:     return $total;
                   9369: }
                   9370: 
1.675     albertel 9371: sub digest {
                   9372:     my ($data)=@_;
                   9373:     my $digest=&Digest::MD5::md5($data);
                   9374:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9375:     my ($e,$f);
                   9376:     {
                   9377:         use integer;
                   9378:         $e=($a+$b);
                   9379:         $f=($c+$d);
                   9380:         if ($_64bit) {
                   9381:             $e=(($e<<32)>>32);
                   9382:             $f=(($f<<32)>>32);
                   9383:         }
                   9384:     }
                   9385:     if (wantarray) {
                   9386: 	return ($e,$f);
                   9387:     } else {
                   9388: 	my $g;
                   9389: 	{
                   9390: 	    use integer;
                   9391: 	    $g=($e+$f);
                   9392: 	    if ($_64bit) {
                   9393: 		$g=(($g<<32)>>32);
                   9394: 	    }
                   9395: 	}
                   9396: 	return $g;
                   9397:     }
                   9398: }
                   9399: 
1.368     albertel 9400: sub latest_rnd_algorithm_id {
1.675     albertel 9401:     return '64bit5';
1.366     albertel 9402: }
1.32      www      9403: 
1.503     albertel 9404: sub get_rand_alg {
                   9405:     my ($courseid)=@_;
1.790     albertel 9406:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9407:     if ($courseid) {
1.620     albertel 9408: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9409:     }
                   9410:     return &latest_rnd_algorithm_id();
                   9411: }
                   9412: 
1.562     albertel 9413: sub validCODE {
                   9414:     my ($CODE)=@_;
                   9415:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9416:     return 0;
                   9417: }
                   9418: 
1.491     albertel 9419: sub getCODE {
1.620     albertel 9420:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9421:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9422: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9423: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9424: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9425:     }
                   9426:     return undef;
                   9427: }
                   9428: 
1.31      www      9429: sub rndseed {
1.155     albertel 9430:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9431:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9432:     if (!defined($symb)) {
1.366     albertel 9433: 	unless ($symb=$wsymb) { return time; }
                   9434:     }
                   9435:     if (!$courseid) { $courseid=$wcourseid; }
                   9436:     if (!$domain) { $domain=$wdomain; }
                   9437:     if (!$username) { $username=$wusername }
1.503     albertel 9438:     my $which=&get_rand_alg();
1.1110    www      9439: 
1.491     albertel 9440:     if (defined(&getCODE())) {
1.675     albertel 9441: 	if ($which eq '64bit5') {
                   9442: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9443: 	} elsif ($which eq '64bit4') {
1.575     albertel 9444: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9445: 	} else {
                   9446: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9447: 	}
1.675     albertel 9448:     } elsif ($which eq '64bit5') {
                   9449: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9450:     } elsif ($which eq '64bit4') {
                   9451: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9452:     } elsif ($which eq '64bit3') {
                   9453: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9454:     } elsif ($which eq '64bit2') {
                   9455: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9456:     } elsif ($which eq '64bit') {
                   9457: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9458:     }
                   9459:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9460: }
                   9461: 
                   9462: sub rndseed_32bit {
                   9463:     my ($symb,$courseid,$domain,$username)=@_;
                   9464:     {
                   9465: 	use integer;
                   9466: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9467: 	my $symbseed=numval($symb) << 22;
                   9468: 	my $namechck=unpack("%32C*",$username) << 17;
                   9469: 	my $nameseed=numval($username) << 12;
                   9470: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9471: 	my $courseseed=unpack("%32C*",$courseid);
                   9472: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9473: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9474: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9475: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9476: 	return $num;
                   9477:     }
                   9478: }
                   9479: 
                   9480: sub rndseed_64bit {
                   9481:     my ($symb,$courseid,$domain,$username)=@_;
                   9482:     {
                   9483: 	use integer;
                   9484: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9485: 	my $symbseed=numval($symb) << 10;
                   9486: 	my $namechck=unpack("%32S*",$username);
                   9487: 	
                   9488: 	my $nameseed=numval($username) << 21;
                   9489: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9490: 	my $courseseed=unpack("%32S*",$courseid);
                   9491: 	
                   9492: 	my $num1=$symbchck+$symbseed+$namechck;
                   9493: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9494: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9495: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9496: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9497: 	return "$num1,$num2";
1.155     albertel 9498:     }
1.366     albertel 9499: }
                   9500: 
1.443     albertel 9501: sub rndseed_64bit2 {
                   9502:     my ($symb,$courseid,$domain,$username)=@_;
                   9503:     {
                   9504: 	use integer;
                   9505: 	# strings need to be an even # of cahracters long, it it is odd the
                   9506:         # last characters gets thrown away
                   9507: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9508: 	my $symbseed=numval($symb) << 10;
                   9509: 	my $namechck=unpack("%32S*",$username.' ');
                   9510: 	
                   9511: 	my $nameseed=numval($username) << 21;
1.501     albertel 9512: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9513: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9514: 	
                   9515: 	my $num1=$symbchck+$symbseed+$namechck;
                   9516: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9517: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9518: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9519: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9520: 	return "$num1,$num2";
                   9521:     }
                   9522: }
                   9523: 
                   9524: sub rndseed_64bit3 {
                   9525:     my ($symb,$courseid,$domain,$username)=@_;
                   9526:     {
                   9527: 	use integer;
                   9528: 	# strings need to be an even # of cahracters long, it it is odd the
                   9529:         # last characters gets thrown away
                   9530: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9531: 	my $symbseed=numval2($symb) << 10;
                   9532: 	my $namechck=unpack("%32S*",$username.' ');
                   9533: 	
                   9534: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9535: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9536: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9537: 	
                   9538: 	my $num1=$symbchck+$symbseed+$namechck;
                   9539: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9540: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9541: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9542: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9543: 	
1.503     albertel 9544: 	return "$num1:$num2";
1.443     albertel 9545:     }
                   9546: }
                   9547: 
1.575     albertel 9548: sub rndseed_64bit4 {
                   9549:     my ($symb,$courseid,$domain,$username)=@_;
                   9550:     {
                   9551: 	use integer;
                   9552: 	# strings need to be an even # of cahracters long, it it is odd the
                   9553:         # last characters gets thrown away
                   9554: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9555: 	my $symbseed=numval3($symb) << 10;
                   9556: 	my $namechck=unpack("%32S*",$username.' ');
                   9557: 	
                   9558: 	my $nameseed=numval3($username) << 21;
                   9559: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9560: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9561: 	
                   9562: 	my $num1=$symbchck+$symbseed+$namechck;
                   9563: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9564: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9565: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9566: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9567: 	
1.575     albertel 9568: 	return "$num1:$num2";
                   9569:     }
                   9570: }
                   9571: 
1.675     albertel 9572: sub rndseed_64bit5 {
                   9573:     my ($symb,$courseid,$domain,$username)=@_;
                   9574:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9575:     return "$num1:$num2";
                   9576: }
                   9577: 
1.366     albertel 9578: sub rndseed_CODE_64bit {
                   9579:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9580:     {
1.366     albertel 9581: 	use integer;
1.443     albertel 9582: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9583: 	my $symbseed=numval2($symb);
1.491     albertel 9584: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9585: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9586: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9587: 	my $num1=$symbseed+$CODEchck;
                   9588: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9589: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9590: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9591: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9592: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9593: 	return "$num1:$num2";
1.366     albertel 9594:     }
                   9595: }
                   9596: 
1.575     albertel 9597: sub rndseed_CODE_64bit4 {
                   9598:     my ($symb,$courseid,$domain,$username)=@_;
                   9599:     {
                   9600: 	use integer;
                   9601: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9602: 	my $symbseed=numval3($symb);
                   9603: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9604: 	my $CODEseed=numval3(&getCODE());
                   9605: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9606: 	my $num1=$symbseed+$CODEchck;
                   9607: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9608: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9609: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9610: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9611: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9612: 	return "$num1:$num2";
                   9613:     }
                   9614: }
                   9615: 
1.675     albertel 9616: sub rndseed_CODE_64bit5 {
                   9617:     my ($symb,$courseid,$domain,$username)=@_;
                   9618:     my $code = &getCODE();
                   9619:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9620:     return "$num1:$num2";
                   9621: }
                   9622: 
1.366     albertel 9623: sub setup_random_from_rndseed {
                   9624:     my ($rndseed)=@_;
1.503     albertel 9625:     if ($rndseed =~/([,:])/) {
                   9626: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9627: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9628:     } else {
                   9629: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9630:     }
1.36      albertel 9631: }
                   9632: 
1.474     albertel 9633: sub latest_receipt_algorithm_id {
1.835     albertel 9634:     return 'receipt3';
1.474     albertel 9635: }
                   9636: 
1.480     www      9637: sub recunique {
                   9638:     my $fucourseid=shift;
                   9639:     my $unique;
1.835     albertel 9640:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9641: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9642: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9643:     } else {
                   9644: 	$unique=$perlvar{'lonReceipt'};
                   9645:     }
                   9646:     return unpack("%32C*",$unique);
                   9647: }
                   9648: 
                   9649: sub recprefix {
                   9650:     my $fucourseid=shift;
                   9651:     my $prefix;
1.835     albertel 9652:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9653: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9654: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9655:     } else {
                   9656: 	$prefix=$perlvar{'lonHostID'};
                   9657:     }
                   9658:     return unpack("%32C*",$prefix);
                   9659: }
                   9660: 
1.76      www      9661: sub ireceipt {
1.474     albertel 9662:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9663: 
                   9664:     my $return =&recprefix($fucourseid).'-';
                   9665: 
                   9666:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9667: 	$env{'request.state'} eq 'construct') {
                   9668: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9669: 	return $return;
                   9670:     }
                   9671: 
1.76      www      9672:     my $cuname=unpack("%32C*",$funame);
                   9673:     my $cudom=unpack("%32C*",$fudom);
                   9674:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9675:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9676:     my $cunique=&recunique($fucourseid);
1.474     albertel 9677:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9678:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9679: 
1.790     albertel 9680: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9681: 			       
                   9682: 	$return.= ($cunique%$cuname+
                   9683: 		   $cunique%$cudom+
                   9684: 		   $cusymb%$cuname+
                   9685: 		   $cusymb%$cudom+
                   9686: 		   $cucourseid%$cuname+
                   9687: 		   $cucourseid%$cudom+
                   9688: 		   $cpart%$cuname+
                   9689: 		   $cpart%$cudom);
                   9690:     } else {
                   9691: 	$return.= ($cunique%$cuname+
                   9692: 		   $cunique%$cudom+
                   9693: 		   $cusymb%$cuname+
                   9694: 		   $cusymb%$cudom+
                   9695: 		   $cucourseid%$cuname+
                   9696: 		   $cucourseid%$cudom);
                   9697:     }
                   9698:     return $return;
1.76      www      9699: }
                   9700: 
                   9701: sub receipt {
1.474     albertel 9702:     my ($part)=@_;
1.790     albertel 9703:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9704:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9705: }
1.260     ng       9706: 
1.790     albertel 9707: sub whichuser {
                   9708:     my ($passedsymb)=@_;
                   9709:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9710:     if (defined($env{'form.grade_symb'})) {
                   9711: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9712: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9713: 	if (!$allowed &&
                   9714: 	    exists($env{'request.course.sec'}) &&
                   9715: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9716: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9717: 			      '/'.$env{'request.course.sec'});
                   9718: 	}
                   9719: 	if ($allowed) {
                   9720: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9721: 	    $courseid=$tmp_courseid;
                   9722: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9723: 	    ($name)=&get_env_multiple('form.grade_username');
                   9724: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9725: 	}
                   9726:     }
                   9727:     if (!$passedsymb) {
                   9728: 	$symb=&symbread();
                   9729:     } else {
                   9730: 	$symb=$passedsymb;
                   9731:     }
                   9732:     $courseid=$env{'request.course.id'};
                   9733:     $domain=$env{'user.domain'};
                   9734:     $name=$env{'user.name'};
                   9735:     if ($name eq 'public' && $domain eq 'public') {
                   9736: 	if (!defined($env{'form.username'})) {
                   9737: 	    $env{'form.username'}.=time.rand(10000000);
                   9738: 	}
                   9739: 	$name.=$env{'form.username'};
                   9740:     }
                   9741:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9742: 
                   9743: }
                   9744: 
1.36      albertel 9745: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9746: # returns either the contents of the file or 
                   9747: # -1 if the file doesn't exist
1.481     raeburn  9748: #
                   9749: # if the target is a file that was uploaded via DOCS, 
                   9750: # a check will be made to see if a current copy exists on the local server,
                   9751: # if it does this will be served, otherwise a copy will be retrieved from
                   9752: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9753: # the local server.   
1.472     albertel 9754: 
1.36      albertel 9755: sub getfile {
1.538     albertel 9756:     my ($file) = @_;
1.609     banghart 9757:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9758:     &repcopy($file);
                   9759:     return &readfile($file);
                   9760: }
                   9761: 
                   9762: sub repcopy_userfile {
                   9763:     my ($file)=@_;
1.609     banghart 9764:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9765:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9766:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9767: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9768:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9769:     if (-e "$file") {
1.828     www      9770: # we already have a local copy, check it out
1.538     albertel 9771: 	my @fileinfo = stat($file);
1.828     www      9772: 	my $rtncode;
                   9773: 	my $info;
1.538     albertel 9774: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9775: 	if ($lwpresp ne 'ok') {
1.828     www      9776: # there is no such file anymore, even though we had a local copy
1.482     albertel 9777: 	    if ($rtncode eq '404') {
1.538     albertel 9778: 		unlink($file);
1.482     albertel 9779: 	    }
                   9780: 	    return -1;
                   9781: 	}
                   9782: 	if ($info < $fileinfo[9]) {
1.828     www      9783: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9784: 	    return 'ok';
1.828     www      9785: 	} else {
                   9786: # the file is outdated, get rid of it
                   9787: 	    unlink($file);
1.482     albertel 9788: 	}
1.828     www      9789:     }
                   9790: # one way or the other, at this point, we don't have the file
                   9791: # construct the correct path for the file
                   9792:     my @parts = ($cdom,$cnum); 
                   9793:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9794: 	push @parts, split(/\//,$1);
                   9795:     }
                   9796:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9797:     foreach my $part (@parts) {
                   9798: 	$path .= '/'.$part;
                   9799: 	if (!-e $path) {
                   9800: 	    mkdir($path,0770);
1.482     albertel 9801: 	}
                   9802:     }
1.828     www      9803: # now the path exists for sure
                   9804: # get a user agent
                   9805:     my $ua=new LWP::UserAgent;
                   9806:     my $transferfile=$file.'.in.transfer';
                   9807: # FIXME: this should flock
                   9808:     if (-e $transferfile) { return 'ok'; }
                   9809:     my $request;
                   9810:     $uri=~s/^\///;
1.980     raeburn  9811:     my $homeserver = &homeserver($cnum,$cdom);
                   9812:     my $protocol = $protocol{$homeserver};
                   9813:     $protocol = 'http' if ($protocol ne 'https');
                   9814:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9815:     my $response=$ua->request($request,$transferfile);
                   9816: # did it work?
                   9817:     if ($response->is_error()) {
                   9818: 	unlink($transferfile);
                   9819: 	&logthis("Userfile repcopy failed for $uri");
                   9820: 	return -1;
                   9821:     }
                   9822: # worked, rename the transfer file
                   9823:     rename($transferfile,$file);
1.607     raeburn  9824:     return 'ok';
1.481     raeburn  9825: }
                   9826: 
1.517     albertel 9827: sub tokenwrapper {
                   9828:     my $uri=shift;
1.980     raeburn  9829:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9830:     $uri=~s|^/||;
1.620     albertel 9831:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9832:     my $token=$1;
1.552     albertel 9833:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9834:     if ($udom && $uname && $file) {
                   9835: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9836:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9837:         my $homeserver = &homeserver($uname,$udom);
                   9838:         my $protocol = $protocol{$homeserver};
                   9839:         $protocol = 'http' if ($protocol ne 'https');
                   9840:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9841:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9842:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9843:     } else {
                   9844:         return '/adm/notfound.html';
                   9845:     }
                   9846: }
                   9847: 
1.828     www      9848: # call with reqtype HEAD: get last modification time
                   9849: # call with reqtype GET: get the file contents
                   9850: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9851: #
1.481     raeburn  9852: sub getuploaded {
                   9853:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9854:     $uri=~s/^\///;
1.980     raeburn  9855:     my $homeserver = &homeserver($cnum,$cdom);
                   9856:     my $protocol = $protocol{$homeserver};
                   9857:     $protocol = 'http' if ($protocol ne 'https');
                   9858:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9859:     my $ua=new LWP::UserAgent;
                   9860:     my $request=new HTTP::Request($reqtype,$uri);
                   9861:     my $response=$ua->request($request);
                   9862:     $$rtncode = $response->code;
1.482     albertel 9863:     if (! $response->is_success()) {
                   9864: 	return 'failed';
                   9865:     }      
                   9866:     if ($reqtype eq 'HEAD') {
1.486     www      9867: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9868:     } elsif ($reqtype eq 'GET') {
                   9869: 	$$info = $response->content;
1.472     albertel 9870:     }
1.482     albertel 9871:     return 'ok';
1.36      albertel 9872: }
                   9873: 
1.481     raeburn  9874: sub readfile {
                   9875:     my $file = shift;
                   9876:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9877:     my $fh;
                   9878:     open($fh,"<$file");
                   9879:     my $a='';
1.800     albertel 9880:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9881:     return $a;
                   9882: }
                   9883: 
1.36      albertel 9884: sub filelocation {
1.590     banghart 9885:     my ($dir,$file) = @_;
                   9886:     my $location;
                   9887:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9888: 
                   9889:     if ($file =~ m-^/adm/-) {
                   9890: 	$file=~s-^/adm/wrapper/-/-;
                   9891: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9892:     }
1.882     albertel 9893: 
1.590     banghart 9894:     if ($file=~m:^/~:) { # is a contruction space reference
                   9895:         $location = $file;
                   9896:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9897:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9898: 	# is a correct contruction space reference
                   9899:         $location = $file;
1.956     raeburn  9900:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9901:         $location = $file;
1.609     banghart 9902:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9903:         my ($udom,$uname,$filename)=
1.811     albertel 9904:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9905:         my $home=&homeserver($uname,$udom);
                   9906:         my $is_me=0;
                   9907:         my @ids=&current_machine_ids();
                   9908:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9909:         if ($is_me) {
1.1117    foxr     9910:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9911:         } else {
                   9912:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9913:   	      $udom.'/'.$uname.'/'.$filename;
                   9914:         }
1.882     albertel 9915:     } elsif ($file =~ m-^/adm/-) {
                   9916: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9917:     } else {
                   9918:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9919:         $file=~s:^/res/:/:;
                   9920:         if ( !( $file =~ m:^/:) ) {
                   9921:             $location = $dir. '/'.$file;
                   9922:         } else {
                   9923:             $location = '/home/httpd/html/res'.$file;
                   9924:         }
1.59      albertel 9925:     }
1.590     banghart 9926:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9927:     while ($location=~m{/\.\./}) {
                   9928: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9929: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9930: 	} else {
                   9931: 	    $location=~ s{/\.\./}{/}g;
                   9932: 	}
                   9933:     } #remove dir/..
1.590     banghart 9934:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9935:     return $location;
1.46      www      9936: }
1.36      albertel 9937: 
1.46      www      9938: sub hreflocation {
                   9939:     my ($dir,$file)=@_;
1.980     raeburn  9940:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9941: 	$file=filelocation($dir,$file);
1.700     albertel 9942:     } elsif ($file=~m-^/adm/-) {
                   9943: 	$file=~s-^/adm/wrapper/-/-;
                   9944: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9945:     }
                   9946:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9947: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9948:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9949: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9950:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9951: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9952: 	    -/uploaded/$1/$2/-x;
1.46      www      9953:     }
1.913     albertel 9954:     if ($file=~ m{^/userfiles/}) {
                   9955: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9956:     }
1.462     albertel 9957:     return $file;
1.465     albertel 9958: }
                   9959: 
                   9960: sub current_machine_domains {
1.853     albertel 9961:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9962: }
                   9963: 
                   9964: sub machine_domains {
                   9965:     my ($hostname) = @_;
1.465     albertel 9966:     my @domains;
1.838     albertel 9967:     my %hostname = &all_hostnames();
1.465     albertel 9968:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9969: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9970: 	if ($hostname eq $name) {
1.844     albertel 9971: 	    push(@domains,&host_domain($id));
1.465     albertel 9972: 	}
                   9973:     }
                   9974:     return @domains;
                   9975: }
                   9976: 
                   9977: sub current_machine_ids {
1.853     albertel 9978:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9979: }
                   9980: 
                   9981: sub machine_ids {
                   9982:     my ($hostname) = @_;
                   9983:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9984:     my @ids;
1.888     albertel 9985:     my %name_to_host = &all_names();
1.889     albertel 9986:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9987: 	return @{ $name_to_host{$hostname} };
                   9988:     }
                   9989:     return;
1.31      www      9990: }
                   9991: 
1.824     raeburn  9992: sub additional_machine_domains {
                   9993:     my @domains;
                   9994:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9995:     while( my $line = <$fh>) {
                   9996:         $line =~ s/\s//g;
                   9997:         push(@domains,$line);
                   9998:     }
                   9999:     return @domains;
                   10000: }
                   10001: 
                   10002: sub default_login_domain {
                   10003:     my $domain = $perlvar{'lonDefDomain'};
                   10004:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10005:     foreach my $posdom (&current_machine_domains(),
                   10006:                         &additional_machine_domains()) {
                   10007:         if (lc($posdom) eq lc($testdomain)) {
                   10008:             $domain=$posdom;
                   10009:             last;
                   10010:         }
                   10011:     }
                   10012:     return $domain;
                   10013: }
                   10014: 
1.31      www      10015: # ------------------------------------------------------------- Declutters URLs
                   10016: 
                   10017: sub declutter {
                   10018:     my $thisfn=shift;
1.569     albertel 10019:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10020:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10021:     $thisfn=~s/^\///;
1.697     albertel 10022:     $thisfn=~s|^adm/wrapper/||;
                   10023:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10024:     $thisfn=~s/^res\///;
1.1032    raeburn  10025:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10026:         $thisfn=~s/\?.+$//;
                   10027:     }
1.268     www      10028:     return $thisfn;
                   10029: }
                   10030: 
                   10031: # ------------------------------------------------------------- Clutter up URLs
                   10032: 
                   10033: sub clutter {
                   10034:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10035:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10036: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10037:        $thisfn='/res'.$thisfn; 
                   10038:     }
1.1031    raeburn  10039:     if ($thisfn !~m|^/adm|) {
                   10040: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10041: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10042: 	} else {
                   10043: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10044: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10045: 	    if ($embstyle eq 'ssi'
                   10046: 		|| ($embstyle eq 'hdn')
                   10047: 		|| ($embstyle eq 'rat')
                   10048: 		|| ($embstyle eq 'prv')
                   10049: 		|| ($embstyle eq 'ign')) {
                   10050: 		#do nothing with these
                   10051: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10052: 		|| ($embstyle eq 'emb')
                   10053: 		|| ($embstyle eq 'wrp')) {
                   10054: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10055: 	    } elsif ($embstyle eq 'unk'
                   10056: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10057: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10058: 	    } else {
1.718     www      10059: #		&logthis("Got a blank emb style");
1.695     albertel 10060: 	    }
1.694     albertel 10061: 	}
                   10062:     }
1.31      www      10063:     return $thisfn;
1.12      www      10064: }
                   10065: 
1.787     albertel 10066: sub clutter_with_no_wrapper {
                   10067:     my $uri = &clutter(shift);
                   10068:     if ($uri =~ m-^/adm/-) {
                   10069: 	$uri =~ s-^/adm/wrapper/-/-;
                   10070: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10071:     }
                   10072:     return $uri;
                   10073: }
                   10074: 
1.557     albertel 10075: sub freeze_escape {
                   10076:     my ($value)=@_;
                   10077:     if (ref($value)) {
                   10078: 	$value=&nfreeze($value);
                   10079: 	return '__FROZEN__'.&escape($value);
                   10080:     }
                   10081:     return &escape($value);
                   10082: }
                   10083: 
1.11      www      10084: 
1.557     albertel 10085: sub thaw_unescape {
                   10086:     my ($value)=@_;
                   10087:     if ($value =~ /^__FROZEN__/) {
                   10088: 	substr($value,0,10,undef);
                   10089: 	$value=&unescape($value);
                   10090: 	return &thaw($value);
                   10091:     }
                   10092:     return &unescape($value);
                   10093: }
                   10094: 
1.436     albertel 10095: sub correct_line_ends {
                   10096:     my ($result)=@_;
                   10097:     $$result =~s/\r\n/\n/mg;
                   10098:     $$result =~s/\r/\n/mg;
1.415     albertel 10099: }
1.1       albertel 10100: # ================================================================ Main Program
                   10101: 
1.184     www      10102: sub goodbye {
1.204     albertel 10103:    &logthis("Starting Shut down");
1.443     albertel 10104: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10105:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10106: #converted
1.599     albertel 10107: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10108:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10109: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10110: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10111: #1.1 only
1.870     albertel 10112: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10113: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10114: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10115: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10116:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10117:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10118:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10119:    &flushcourselogs();
                   10120:    &logthis("Shutting down");
                   10121: }
                   10122: 
1.852     albertel 10123: sub get_dns {
1.869     albertel 10124:     my ($url,$func,$ignore_cache) = @_;
                   10125:     if (!$ignore_cache) {
                   10126: 	my ($content,$cached)=
                   10127: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10128: 	if ($cached) {
                   10129: 	    &$func($content);
                   10130: 	    return;
                   10131: 	}
                   10132:     }
                   10133: 
                   10134:     my %alldns;
1.852     albertel 10135:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10136:     foreach my $dns (<$config>) {
                   10137: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10138:         my $line = $1;
                   10139:         my ($host,$protocol) = split(/:/,$line);
                   10140:         if ($protocol ne 'https') {
                   10141:             $protocol = 'http';
                   10142:         }
                   10143: 	$alldns{$host} = $protocol;
1.869     albertel 10144:     }
                   10145:     while (%alldns) {
                   10146: 	my ($dns) = keys(%alldns);
1.852     albertel 10147: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10148: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10149: 	my $response=$ua->request($request);
1.979     raeburn  10150:         delete($alldns{$dns});
1.852     albertel 10151: 	next if ($response->is_error());
                   10152: 	my @content = split("\n",$response->content);
1.869     albertel 10153: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10154: 	&$func(\@content);
1.869     albertel 10155: 	return;
1.852     albertel 10156:     }
                   10157:     close($config);
1.871     albertel 10158:     my $which = (split('/',$url))[3];
                   10159:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10160:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10161:     my @content = <$config>;
                   10162:     &$func(\@content);
                   10163:     return;
1.852     albertel 10164: }
1.327     albertel 10165: # ------------------------------------------------------------ Read domain file
                   10166: {
1.852     albertel 10167:     my $loaded;
1.846     albertel 10168:     my %domain;
                   10169: 
1.852     albertel 10170:     sub parse_domain_tab {
                   10171: 	my ($lines) = @_;
                   10172: 	foreach my $line (@$lines) {
                   10173: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10174: 
1.846     albertel 10175: 	    chomp($line);
1.852     albertel 10176: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10177: 	    my %this_domain;
                   10178: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10179: 			       'lang_def', 'city', 'longi', 'lati',
                   10180: 			       'primary') {
                   10181: 		$this_domain{$field} = shift(@elements);
                   10182: 	    }
                   10183: 	    $domain{$name} = \%this_domain;
1.852     albertel 10184: 	}
                   10185:     }
1.864     albertel 10186: 
                   10187:     sub reset_domain_info {
                   10188: 	undef($loaded);
                   10189: 	undef(%domain);
                   10190:     }
                   10191: 
1.852     albertel 10192:     sub load_domain_tab {
1.869     albertel 10193: 	my ($ignore_cache) = @_;
                   10194: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10195: 	my $fh;
                   10196: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10197: 	    my @lines = <$fh>;
                   10198: 	    &parse_domain_tab(\@lines);
1.448     albertel 10199: 	}
1.852     albertel 10200: 	close($fh);
                   10201: 	$loaded = 1;
1.327     albertel 10202:     }
1.846     albertel 10203: 
                   10204:     sub domain {
1.852     albertel 10205: 	&load_domain_tab() if (!$loaded);
                   10206: 
1.846     albertel 10207: 	my ($name,$what) = @_;
                   10208: 	return if ( !exists($domain{$name}) );
                   10209: 
                   10210: 	if (!$what) {
                   10211: 	    return $domain{$name}{'description'};
                   10212: 	}
                   10213: 	return $domain{$name}{$what};
                   10214:     }
1.974     raeburn  10215: 
                   10216:     sub domain_info {
                   10217:         &load_domain_tab() if (!$loaded);
                   10218:         return %domain;
                   10219:     }
                   10220: 
1.327     albertel 10221: }
                   10222: 
                   10223: 
1.1       albertel 10224: # ------------------------------------------------------------- Read hosts file
                   10225: {
1.838     albertel 10226:     my %hostname;
1.844     albertel 10227:     my %hostdom;
1.845     albertel 10228:     my %libserv;
1.852     albertel 10229:     my $loaded;
1.888     albertel 10230:     my %name_to_host;
1.1074    raeburn  10231:     my %internetdom;
1.1107    raeburn  10232:     my %LC_dns_serv;
1.852     albertel 10233: 
                   10234:     sub parse_hosts_tab {
                   10235: 	my ($file) = @_;
                   10236: 	foreach my $configline (@$file) {
                   10237: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10238:             chomp($configline);
                   10239: 	    if ($configline =~ /^\^/) {
                   10240:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10241:                     $LC_dns_serv{$1} = 1;
                   10242:                 }
                   10243:                 next;
                   10244:             }
1.1074    raeburn  10245: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10246: 	    $name=~s/\s//g;
                   10247: 	    if ($id && $domain && $role && $name) {
                   10248: 		$hostname{$id}=$name;
1.888     albertel 10249: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10250: 		$hostdom{$id}=$domain;
                   10251: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10252:                 if (defined($protocol)) {
                   10253:                     if ($protocol eq 'https') {
                   10254:                         $protocol{$id} = $protocol;
                   10255:                     } else {
                   10256:                         $protocol{$id} = 'http'; 
                   10257:                     }
1.968     raeburn  10258:                 } else {
1.969     raeburn  10259:                     $protocol{$id} = 'http';
1.968     raeburn  10260:                 }
1.1074    raeburn  10261:                 if (defined($intdom)) {
                   10262:                     $internetdom{$id} = $intdom;
                   10263:                 }
1.852     albertel 10264: 	    }
                   10265: 	}
                   10266:     }
1.864     albertel 10267:     
                   10268:     sub reset_hosts_info {
1.897     albertel 10269: 	&purge_remembered();
1.864     albertel 10270: 	&reset_domain_info();
                   10271: 	&reset_hosts_ip_info();
1.892     albertel 10272: 	undef(%name_to_host);
1.864     albertel 10273: 	undef(%hostname);
                   10274: 	undef(%hostdom);
                   10275: 	undef(%libserv);
                   10276: 	undef($loaded);
                   10277:     }
1.1       albertel 10278: 
1.852     albertel 10279:     sub load_hosts_tab {
1.869     albertel 10280: 	my ($ignore_cache) = @_;
                   10281: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10282: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10283: 	my @config = <$config>;
                   10284: 	&parse_hosts_tab(\@config);
                   10285: 	close($config);
                   10286: 	$loaded=1;
1.1       albertel 10287:     }
1.852     albertel 10288: 
1.838     albertel 10289:     sub hostname {
1.852     albertel 10290: 	&load_hosts_tab() if (!$loaded);
                   10291: 
1.838     albertel 10292: 	my ($lonid) = @_;
                   10293: 	return $hostname{$lonid};
                   10294:     }
1.845     albertel 10295: 
1.838     albertel 10296:     sub all_hostnames {
1.852     albertel 10297: 	&load_hosts_tab() if (!$loaded);
                   10298: 
1.838     albertel 10299: 	return %hostname;
                   10300:     }
1.845     albertel 10301: 
1.888     albertel 10302:     sub all_names {
                   10303: 	&load_hosts_tab() if (!$loaded);
                   10304: 
                   10305: 	return %name_to_host;
                   10306:     }
                   10307: 
1.974     raeburn  10308:     sub all_host_domain {
                   10309:         &load_hosts_tab() if (!$loaded);
                   10310:         return %hostdom;
                   10311:     }
                   10312: 
1.845     albertel 10313:     sub is_library {
1.852     albertel 10314: 	&load_hosts_tab() if (!$loaded);
                   10315: 
1.845     albertel 10316: 	return exists($libserv{$_[0]});
                   10317:     }
                   10318: 
                   10319:     sub all_library {
1.852     albertel 10320: 	&load_hosts_tab() if (!$loaded);
                   10321: 
1.845     albertel 10322: 	return %libserv;
                   10323:     }
                   10324: 
1.1062    droeschl 10325:     sub unique_library {
                   10326: 	#2x reverse removes all hostnames that appear more than once
                   10327:         my %unique = reverse &all_library();
                   10328:         return reverse %unique;
                   10329:     }
                   10330: 
1.841     albertel 10331:     sub get_servers {
1.852     albertel 10332: 	&load_hosts_tab() if (!$loaded);
                   10333: 
1.841     albertel 10334: 	my ($domain,$type) = @_;
                   10335: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10336: 	                                          : %hostname;
                   10337: 	my %result;
1.842     albertel 10338: 	if (ref($domain) eq 'ARRAY') {
                   10339: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10340: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10341: 		    $result{$host} = $hostname;
                   10342: 		}
                   10343: 	    }
                   10344: 	} else {
                   10345: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10346: 		if ($hostdom{$host} eq $domain) {
                   10347: 		    $result{$host} = $hostname;
                   10348: 		}
1.841     albertel 10349: 	    }
                   10350: 	}
                   10351: 	return %result;
                   10352:     }
1.845     albertel 10353: 
1.1062    droeschl 10354:     sub get_unique_servers {
                   10355:         my %unique = reverse &get_servers(@_);
                   10356: 	return reverse %unique;
                   10357:     }
                   10358: 
1.844     albertel 10359:     sub host_domain {
1.852     albertel 10360: 	&load_hosts_tab() if (!$loaded);
                   10361: 
1.844     albertel 10362: 	my ($lonid) = @_;
                   10363: 	return $hostdom{$lonid};
                   10364:     }
                   10365: 
1.841     albertel 10366:     sub all_domains {
1.852     albertel 10367: 	&load_hosts_tab() if (!$loaded);
                   10368: 
1.841     albertel 10369: 	my %seen;
                   10370: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10371: 	return @uniq;
                   10372:     }
1.1074    raeburn  10373: 
                   10374:     sub internet_dom {
                   10375:         &load_hosts_tab() if (!$loaded);
                   10376: 
                   10377:         my ($lonid) = @_;
                   10378:         return $internetdom{$lonid};
                   10379:     }
1.1107    raeburn  10380: 
                   10381:     sub is_LC_dns {
                   10382:         &load_hosts_tab() if (!$loaded);
                   10383: 
                   10384:         my ($hostname) = @_;
                   10385:         return exists($LC_dns_serv{$hostname});
                   10386:     }
                   10387: 
1.1       albertel 10388: }
                   10389: 
1.847     albertel 10390: { 
                   10391:     my %iphost;
1.856     albertel 10392:     my %name_to_ip;
                   10393:     my %lonid_to_ip;
1.869     albertel 10394: 
1.847     albertel 10395:     sub get_hosts_from_ip {
                   10396: 	my ($ip) = @_;
                   10397: 	my %iphosts = &get_iphost();
                   10398: 	if (ref($iphosts{$ip})) {
                   10399: 	    return @{$iphosts{$ip}};
                   10400: 	}
                   10401: 	return;
1.839     albertel 10402:     }
1.864     albertel 10403:     
                   10404:     sub reset_hosts_ip_info {
                   10405: 	undef(%iphost);
                   10406: 	undef(%name_to_ip);
                   10407: 	undef(%lonid_to_ip);
                   10408:     }
1.856     albertel 10409: 
                   10410:     sub get_host_ip {
                   10411: 	my ($lonid) = @_;
                   10412: 	if (exists($lonid_to_ip{$lonid})) {
                   10413: 	    return $lonid_to_ip{$lonid};
                   10414: 	}
                   10415: 	my $name=&hostname($lonid);
                   10416:    	my $ip = gethostbyname($name);
                   10417: 	return if (!$ip || length($ip) ne 4);
                   10418: 	$ip=inet_ntoa($ip);
                   10419: 	$name_to_ip{$name}   = $ip;
                   10420: 	$lonid_to_ip{$lonid} = $ip;
                   10421: 	return $ip;
                   10422:     }
1.847     albertel 10423:     
                   10424:     sub get_iphost {
1.869     albertel 10425: 	my ($ignore_cache) = @_;
1.894     albertel 10426: 
1.869     albertel 10427: 	if (!$ignore_cache) {
                   10428: 	    if (%iphost) {
                   10429: 		return %iphost;
                   10430: 	    }
                   10431: 	    my ($ip_info,$cached)=
                   10432: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10433: 	    if ($cached) {
                   10434: 		%iphost      = %{$ip_info->[0]};
                   10435: 		%name_to_ip  = %{$ip_info->[1]};
                   10436: 		%lonid_to_ip = %{$ip_info->[2]};
                   10437: 		return %iphost;
                   10438: 	    }
                   10439: 	}
1.894     albertel 10440: 
                   10441: 	# get yesterday's info for fallback
                   10442: 	my %old_name_to_ip;
                   10443: 	my ($ip_info,$cached)=
                   10444: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10445: 	if ($cached) {
                   10446: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10447: 	}
                   10448: 
1.888     albertel 10449: 	my %name_to_host = &all_names();
                   10450: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10451: 	    my $ip;
                   10452: 	    if (!exists($name_to_ip{$name})) {
                   10453: 		$ip = gethostbyname($name);
                   10454: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10455: 		    if (defined($old_name_to_ip{$name})) {
                   10456: 			$ip = $old_name_to_ip{$name};
                   10457: 			&logthis("Can't find $name defaulting to old $ip");
                   10458: 		    } else {
                   10459: 			&logthis("Name $name no IP found");
                   10460: 			next;
                   10461: 		    }
                   10462: 		} else {
                   10463: 		    $ip=inet_ntoa($ip);
1.847     albertel 10464: 		}
                   10465: 		$name_to_ip{$name} = $ip;
                   10466: 	    } else {
                   10467: 		$ip = $name_to_ip{$name};
1.653     albertel 10468: 	    }
1.888     albertel 10469: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10470: 		$lonid_to_ip{$id} = $ip;
                   10471: 	    }
                   10472: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10473: 	}
1.869     albertel 10474: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10475: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10476: 				      48*60*60);
1.869     albertel 10477: 
1.847     albertel 10478: 	return %iphost;
1.598     albertel 10479:     }
                   10480: 
1.992     raeburn  10481:     #
                   10482:     #  Given a DNS returns the loncapa host name for that DNS 
                   10483:     # 
                   10484:     sub host_from_dns {
                   10485:         my ($dns) = @_;
                   10486:         my @hosts;
                   10487:         my $ip;
                   10488: 
1.993     raeburn  10489:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10490:             $ip = $name_to_ip{$dns};
                   10491:         }
                   10492:         if (!$ip) {
                   10493:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10494:             if (length($ip) == 4) { 
                   10495: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10496:             }
                   10497:         }
                   10498:         if ($ip) {
                   10499: 	    @hosts = get_hosts_from_ip($ip);
                   10500: 	    return $hosts[0];
                   10501:         }
                   10502:         return undef;
1.986     foxr     10503:     }
1.992     raeburn  10504: 
1.1074    raeburn  10505:     sub get_internet_names {
                   10506:         my ($lonid) = @_;
                   10507:         return if ($lonid eq '');
                   10508:         my ($idnref,$cached)=
                   10509:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10510:         if ($cached) {
                   10511:             return $idnref;
                   10512:         }
                   10513:         my $ip = &get_host_ip($lonid);
                   10514:         my @hosts = &get_hosts_from_ip($ip);
                   10515:         my %iphost = &get_iphost();
                   10516:         my (@idns,%seen);
                   10517:         foreach my $id (@hosts) {
                   10518:             my $dom = &host_domain($id);
                   10519:             my $prim_id = &domain($dom,'primary');
                   10520:             my $prim_ip = &get_host_ip($prim_id);
                   10521:             next if ($seen{$prim_ip});
                   10522:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10523:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10524:                     my $intdom = &internet_dom($id);
                   10525:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10526:                         push(@idns,$intdom);
                   10527:                     }
                   10528:                 }
                   10529:             }
                   10530:             $seen{$prim_ip} = 1;
                   10531:         }
                   10532:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10533:     }
                   10534: 
1.986     foxr     10535: }
                   10536: 
1.1079    raeburn  10537: sub all_loncaparevs {
                   10538:     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);
                   10539: }
                   10540: 
1.862     albertel 10541: BEGIN {
                   10542: 
                   10543: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10544:     unless ($readit) {
                   10545: {
                   10546:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10547:     %perlvar = (%perlvar,%{$configvars});
                   10548: }
                   10549: 
                   10550: 
1.1       albertel 10551: # ------------------------------------------------------ Read spare server file
                   10552: {
1.448     albertel 10553:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10554: 
                   10555:     while (my $configline=<$config>) {
                   10556:        chomp($configline);
1.284     matthew  10557:        if ($configline) {
1.784     albertel 10558: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10559: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10560: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10561:        }
                   10562:     }
1.448     albertel 10563:     close($config);
1.1       albertel 10564: }
1.11      www      10565: # ------------------------------------------------------------ Read permissions
                   10566: {
1.448     albertel 10567:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10568: 
                   10569:     while (my $configline=<$config>) {
1.448     albertel 10570: 	chomp($configline);
                   10571: 	if ($configline) {
                   10572: 	    my ($role,$perm)=split(/ /,$configline);
                   10573: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10574: 	}
1.11      www      10575:     }
1.448     albertel 10576:     close($config);
1.11      www      10577: }
                   10578: 
                   10579: # -------------------------------------------- Read plain texts for permissions
                   10580: {
1.448     albertel 10581:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10582: 
                   10583:     while (my $configline=<$config>) {
1.448     albertel 10584: 	chomp($configline);
                   10585: 	if ($configline) {
1.742     raeburn  10586: 	    my ($short,@plain)=split(/:/,$configline);
                   10587:             %{$prp{$short}} = ();
                   10588: 	    if (@plain > 0) {
                   10589:                 $prp{$short}{'std'} = $plain[0];
                   10590:                 for (my $i=1; $i<@plain; $i++) {
                   10591:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10592:                 }
                   10593:             }
1.448     albertel 10594: 	}
1.135     www      10595:     }
1.448     albertel 10596:     close($config);
1.135     www      10597: }
                   10598: 
                   10599: # ---------------------------------------------------------- Read package table
                   10600: {
1.448     albertel 10601:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10602: 
                   10603:     while (my $configline=<$config>) {
1.483     albertel 10604: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10605: 	chomp($configline);
                   10606: 	my ($short,$plain)=split(/:/,$configline);
                   10607: 	my ($pack,$name)=split(/\&/,$short);
                   10608: 	if ($plain ne '') {
                   10609: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10610: 	    $packagetab{$short}=$plain; 
                   10611: 	}
1.11      www      10612:     }
1.448     albertel 10613:     close($config);
1.329     matthew  10614: }
                   10615: 
1.1073    raeburn  10616: # ---------------------------------------------------------- Read loncaparev table
                   10617: {
                   10618:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10619:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10620:             while (my $configline=<$config>) {
                   10621:                 chomp($configline);
                   10622:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10623:                 $loncaparevs{$hostid}=$loncaparev;
                   10624:             }
                   10625:             close($config);
                   10626:         }
                   10627:     }
                   10628: }
                   10629: 
1.1074    raeburn  10630: # ---------------------------------------------------------- Read serverhostID table
                   10631: {
                   10632:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10633:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10634:             while (my $configline=<$config>) {
                   10635:                 chomp($configline);
                   10636:                 my ($name,$id)=split(/:/,$configline);
                   10637:                 $serverhomeIDs{$name}=$id;
                   10638:             }
                   10639:             close($config);
                   10640:         }
                   10641:     }
                   10642: }
                   10643: 
1.1079    raeburn  10644: {
                   10645:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10646:     if (-e $file) {
                   10647:         my $parser = HTML::LCParser->new($file);
                   10648:         while (my $token = $parser->get_token()) {
                   10649:             if ($token->[0] eq 'S') {
                   10650:                 my $item = $token->[1];
                   10651:                 my $name = $token->[2]{'name'};
                   10652:                 my $value = $token->[2]{'value'};
                   10653:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10654:                     my $release = $parser->get_text();
                   10655:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10656:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10657:                 }
                   10658:             }
                   10659:         }
                   10660:     }
1.1073    raeburn  10661: }
                   10662: 
1.329     matthew  10663: # ------------- set up temporary directory
                   10664: {
1.1117    foxr     10665:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10666: 
1.11      www      10667: }
                   10668: 
1.794     albertel 10669: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10670: 				'compress_threshold'=> 20_000,
                   10671:  			        });
1.185     www      10672: 
1.281     www      10673: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10674: $dumpcount=0;
1.958     www      10675: $locknum=0;
1.22      www      10676: 
1.163     harris41 10677: &logtouch();
1.672     albertel 10678: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10679: $readit=1;
1.564     albertel 10680:     {
                   10681: 	use integer;
                   10682: 	my $test=(2**32)+1;
1.568     albertel 10683: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10684: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10685:     }
1.195     www      10686: }
1.1       albertel 10687: }
1.179     www      10688: 
1.1       albertel 10689: 1;
1.191     harris41 10690: __END__
                   10691: 
1.243     albertel 10692: =pod
                   10693: 
1.191     harris41 10694: =head1 NAME
                   10695: 
1.243     albertel 10696: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10697: 
                   10698: =head1 SYNOPSIS
                   10699: 
1.243     albertel 10700: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10701: 
                   10702:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10703: 
1.243     albertel 10704: Common parameters:
                   10705: 
                   10706: =over 4
                   10707: 
                   10708: =item *
                   10709: 
                   10710: $uname : an internal username (if $cname expecting a course Id specifically)
                   10711: 
                   10712: =item *
                   10713: 
                   10714: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10715: 
                   10716: =item *
                   10717: 
                   10718: $symb : a resource instance identifier
                   10719: 
                   10720: =item *
                   10721: 
                   10722: $namespace : the name of a .db file that contains the data needed or
                   10723: being set.
                   10724: 
                   10725: =back
                   10726: 
1.394     bowersj2 10727: =head1 OVERVIEW
1.191     harris41 10728: 
1.394     bowersj2 10729: lonnet provides subroutines which interact with the
                   10730: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10731: about classes, users, and resources.
1.243     albertel 10732: 
                   10733: For many of these objects you can also use this to store data about
                   10734: them or modify them in various ways.
1.191     harris41 10735: 
1.394     bowersj2 10736: =head2 Symbs
1.191     harris41 10737: 
1.394     bowersj2 10738: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10739: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10740: map, the resource number of the resource in the map, and the URL of
                   10741: the resource itself. The latter is somewhat redundant, but might help
                   10742: if maps change.
                   10743: 
                   10744: An example is
                   10745: 
                   10746:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10747: 
                   10748: The respective map entry is
                   10749: 
                   10750:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10751:   title="Problem 2">
                   10752:  </resource>
                   10753: 
                   10754: Symbs are used by the random number generator, as well as to store and
                   10755: restore data specific to a certain instance of for example a problem.
                   10756: 
                   10757: =head2 Storing And Retrieving Data
                   10758: 
                   10759: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10760: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10761: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10762: is is the non-critical message twin of cstore. These functions are for
                   10763: handlers to store a perl hash to a user's permanent data space in an
                   10764: easy manner, and to retrieve it again on another call. It is expected
                   10765: that a handler would use this once at the beginning to retrieve data,
                   10766: and then again once at the end to send only the new data back.
                   10767: 
                   10768: The data is stored in the user's data directory on the user's
                   10769: homeserver under the ID of the course.
                   10770: 
                   10771: The hash that is returned by restore will have all of the previous
                   10772: value for all of the elements of the hash.
                   10773: 
                   10774: Example:
                   10775: 
                   10776:  #creating a hash
                   10777:  my %hash;
                   10778:  $hash{'foo'}='bar';
                   10779: 
                   10780:  #storing it
                   10781:  &Apache::lonnet::cstore(\%hash);
                   10782: 
                   10783:  #changing a value
                   10784:  $hash{'foo'}='notbar';
                   10785: 
                   10786:  #adding a new value
                   10787:  $hash{'bar'}='foo';
                   10788:  &Apache::lonnet::cstore(\%hash);
                   10789: 
                   10790:  #retrieving the hash
                   10791:  my %history=&Apache::lonnet::restore();
                   10792: 
                   10793:  #print the hash
                   10794:  foreach my $key (sort(keys(%history))) {
                   10795:    print("\%history{$key} = $history{$key}");
                   10796:  }
                   10797: 
                   10798: Will print out:
1.191     harris41 10799: 
1.394     bowersj2 10800:  %history{1:foo} = bar
                   10801:  %history{1:keys} = foo:timestamp
                   10802:  %history{1:timestamp} = 990455579
                   10803:  %history{2:bar} = foo
                   10804:  %history{2:foo} = notbar
                   10805:  %history{2:keys} = foo:bar:timestamp
                   10806:  %history{2:timestamp} = 990455580
                   10807:  %history{bar} = foo
                   10808:  %history{foo} = notbar
                   10809:  %history{timestamp} = 990455580
                   10810:  %history{version} = 2
                   10811: 
                   10812: Note that the special hash entries C<keys>, C<version> and
                   10813: C<timestamp> were added to the hash. C<version> will be equal to the
                   10814: total number of versions of the data that have been stored. The
                   10815: C<timestamp> attribute will be the UNIX time the hash was
                   10816: stored. C<keys> is available in every historical section to list which
                   10817: keys were added or changed at a specific historical revision of a
                   10818: hash.
                   10819: 
                   10820: B<Warning>: do not store the hash that restore returns directly. This
                   10821: will cause a mess since it will restore the historical keys as if the
                   10822: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10823: 
1.394     bowersj2 10824: Calling convention:
1.191     harris41 10825: 
1.394     bowersj2 10826:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10827:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10828: 
1.394     bowersj2 10829: For more detailed information, see lonnet specific documentation.
1.191     harris41 10830: 
1.394     bowersj2 10831: =head1 RETURN MESSAGES
1.191     harris41 10832: 
1.394     bowersj2 10833: =over 4
1.191     harris41 10834: 
1.394     bowersj2 10835: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10836: 
1.394     bowersj2 10837: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10838: when the connection is brought back up
1.191     harris41 10839: 
1.394     bowersj2 10840: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10841: for later delivery
1.191     harris41 10842: 
1.967     bisitz   10843: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10844: 
1.394     bowersj2 10845: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10846: that was requested
1.191     harris41 10847: 
1.243     albertel 10848: =back
1.191     harris41 10849: 
1.243     albertel 10850: =head1 PUBLIC SUBROUTINES
1.191     harris41 10851: 
1.243     albertel 10852: =head2 Session Environment Functions
1.191     harris41 10853: 
1.243     albertel 10854: =over 4
1.191     harris41 10855: 
1.394     bowersj2 10856: =item * 
                   10857: X<appenv()>
1.949     raeburn  10858: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10859: the user envirnoment file, and will be restored for each access this
1.620     albertel 10860: user makes during this session, also modifies the %env for the current
1.949     raeburn  10861: process. Optional rolesarrayref - if defined contains a reference to an array
                   10862: of roles which are exempt from the restriction on modifying user.role entries 
                   10863: in the user's environment.db and in %env.    
1.191     harris41 10864: 
                   10865: =item *
1.394     bowersj2 10866: X<delenv()>
1.987     raeburn  10867: B<delenv($delthis,$regexp)>: removes all items from the session
                   10868: environment file that begin with $delthis. If the 
                   10869: optional second arg - $regexp - is true, $delthis is treated as a 
                   10870: regular expression, otherwise \Q$delthis\E is used. 
                   10871: The values are also deleted from the current processes %env.
1.191     harris41 10872: 
1.795     albertel 10873: =item * get_env_multiple($name) 
                   10874: 
                   10875: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10876: values may be defined and end up as an array ref.
                   10877: 
                   10878: returns an array of values
                   10879: 
1.243     albertel 10880: =back
                   10881: 
                   10882: =head2 User Information
1.191     harris41 10883: 
1.243     albertel 10884: =over 4
1.191     harris41 10885: 
                   10886: =item *
1.394     bowersj2 10887: X<queryauthenticate()>
                   10888: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10889: authentication scheme
                   10890: 
                   10891: =item *
1.394     bowersj2 10892: X<authenticate()>
1.1073    raeburn  10893: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10894: authenticate user from domain's lib servers (first use the current
                   10895: one). C<$upass> should be the users password.
1.1073    raeburn  10896: $checkdefauth is optional (value is 1 if a check should be made to
                   10897:    authenticate user using default authentication method, and allow
                   10898:    account creation if username does not have account in the domain).
                   10899: $clientcancheckhost is optional (value is 1 if checking whether the
                   10900:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10901: 
                   10902: =item *
1.394     bowersj2 10903: X<homeserver()>
                   10904: B<homeserver($uname,$udom)>: find the server which has
                   10905: the user's directory and files (there must be only one), this caches
                   10906: the answer, and also caches if there is a borken connection.
1.191     harris41 10907: 
                   10908: =item *
1.394     bowersj2 10909: X<idget()>
                   10910: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10911: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10912: username, and only 1 username per ID in a specific domain) (returns
                   10913: hash: id=>name,id=>name)
1.191     harris41 10914: 
                   10915: =item *
1.394     bowersj2 10916: X<idrget()>
                   10917: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10918: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10919: 
                   10920: =item *
1.394     bowersj2 10921: X<idput()>
                   10922: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10923: 
                   10924: =item *
1.394     bowersj2 10925: X<rolesinit()>
                   10926: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10927: 
                   10928: =item *
1.551     albertel 10929: X<getsection()>
                   10930: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10931: course $cname, return section name/number or '' for "not in course"
                   10932: and '-1' for "no section"
                   10933: 
                   10934: =item *
1.394     bowersj2 10935: X<userenvironment()>
                   10936: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10937: passed in @what from the requested user's environment, returns a hash
                   10938: 
1.858     raeburn  10939: =item * 
                   10940: X<userlog_query()>
1.859     albertel 10941: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10942: activity.log file. %filters defines filters applied when parsing the
                   10943: log file. These can be start or end timestamps, or the type of action
                   10944: - log to look for Login or Logout events, check for Checkin or
                   10945: Checkout, role for role selection. The response is in the form
                   10946: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10947: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10948: 
1.243     albertel 10949: =back
                   10950: 
                   10951: =head2 User Roles
                   10952: 
                   10953: =over 4
                   10954: 
                   10955: =item *
                   10956: 
1.810     raeburn  10957: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10958:  F: full access
                   10959:  U,I,K: authentication modes (cxx only)
                   10960:  '': forbidden
                   10961:  1: user needs to choose course
                   10962:  2: browse allowed
1.766     albertel 10963:  A: passphrase authentication needed
1.243     albertel 10964: 
                   10965: =item *
                   10966: 
                   10967: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10968: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10969: and course level
                   10970: 
                   10971: =item *
                   10972: 
1.988     raeburn  10973: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10974: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10975: $type is Course (default) or Community.
1.988     raeburn  10976: If $forcedefault evaluates to true, text returned will be default 
                   10977: text for $type. Otherwise, if this is a course, the text returned 
                   10978: will be a custom name for the role (if defined in the course's 
                   10979: environment).  If no custom name is defined the default is returned.
                   10980:    
1.832     raeburn  10981: =item *
                   10982: 
1.935     raeburn  10983: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10984: All arguments are optional. Returns a hash of a roles, either for
                   10985: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10986: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10987: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10988: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10989: For each key, value is set to colon-separated start and end times for
                   10990: the role.  If no username and domain are specified, will default to
1.934     raeburn  10991: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10992: of role statuses (active, future or previous), roles 
                   10993: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10994: to restrict the list of roles reported. If no array ref is 
                   10995: provided for types, will default to return only active roles.
1.834     albertel 10996: 
1.243     albertel 10997: =back
                   10998: 
                   10999: =head2 User Modification
                   11000: 
                   11001: =over 4
                   11002: 
                   11003: =item *
                   11004: 
1.957     raeburn  11005: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11006: user for the level given by URL.  Optional start and end dates (leave empty
                   11007: string or zero for "no date")
1.191     harris41 11008: 
                   11009: =item *
                   11010: 
1.243     albertel 11011: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11012: change a users, password, possible return values are: ok,
                   11013: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11014: refused
1.191     harris41 11015: 
                   11016: =item *
                   11017: 
1.243     albertel 11018: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11019: 
                   11020: =item *
                   11021: 
1.1058    raeburn  11022: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11023:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11024: 
                   11025: will update user information (firstname,middlename,lastname,generation,
                   11026: permanentemail), and if forceid is true, student/employee ID also.
                   11027: A user's institutional affiliation(s) can also be updated.
                   11028: User information fields will not be overwritten with empty entries 
                   11029: unless the field is included in the $candelete array reference.
                   11030: This array is included when a single user is modified via "Manage Users",
                   11031: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11032: 
                   11033: =item *
                   11034: 
1.286     matthew  11035: modifystudent
                   11036: 
1.957     raeburn  11037: modify a student's enrollment and identification information.
1.286     matthew  11038: The course id is resolved based on the current users environment.  
                   11039: This means the envoking user must be a course coordinator or otherwise
                   11040: associated with a course.
                   11041: 
1.297     matthew  11042: This call is essentially a wrapper for lonnet::modifyuser and
                   11043: lonnet::modify_student_enrollment
1.286     matthew  11044: 
                   11045: Inputs: 
                   11046: 
                   11047: =over 4
                   11048: 
1.957     raeburn  11049: =item B<$udom> Student's loncapa domain
1.286     matthew  11050: 
1.957     raeburn  11051: =item B<$uname> Student's loncapa login name
1.286     matthew  11052: 
1.964     bisitz   11053: =item B<$uid> Student/Employee ID
1.286     matthew  11054: 
1.957     raeburn  11055: =item B<$umode> Student's authentication mode
1.286     matthew  11056: 
1.957     raeburn  11057: =item B<$upass> Student's password
1.286     matthew  11058: 
1.957     raeburn  11059: =item B<$first> Student's first name
1.286     matthew  11060: 
1.957     raeburn  11061: =item B<$middle> Student's middle name
1.286     matthew  11062: 
1.957     raeburn  11063: =item B<$last> Student's last name
1.286     matthew  11064: 
1.957     raeburn  11065: =item B<$gene> Student's generation
1.286     matthew  11066: 
1.957     raeburn  11067: =item B<$usec> Student's section in course
1.286     matthew  11068: 
                   11069: =item B<$end> Unix time of the roles expiration
                   11070: 
                   11071: =item B<$start> Unix time of the roles start date
                   11072: 
                   11073: =item B<$forceid> If defined, allow $uid to be changed
                   11074: 
                   11075: =item B<$desiredhome> server to use as home server for student
                   11076: 
1.957     raeburn  11077: =item B<$email> Student's permanent e-mail address
                   11078: 
                   11079: =item B<$type> Type of enrollment (auto or manual)
                   11080: 
1.963     raeburn  11081: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11082: 
                   11083: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11084: 
1.963     raeburn  11085: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11086: 
1.963     raeburn  11087: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11088: 
1.963     raeburn  11089: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11090: 
1.286     matthew  11091: =back
1.297     matthew  11092: 
                   11093: =item *
                   11094: 
                   11095: modify_student_enrollment
                   11096: 
                   11097: Change a students enrollment status in a class.  The environment variable
                   11098: 'role.request.course' must be defined for this function to proceed.
                   11099: 
                   11100: Inputs:
                   11101: 
                   11102: =over 4
                   11103: 
                   11104: =item $udom, students domain
                   11105: 
                   11106: =item $uname, students name
                   11107: 
                   11108: =item $uid, students user id
                   11109: 
                   11110: =item $first, students first name
                   11111: 
                   11112: =item $middle
                   11113: 
                   11114: =item $last
                   11115: 
                   11116: =item $gene
                   11117: 
                   11118: =item $usec
                   11119: 
                   11120: =item $end
                   11121: 
                   11122: =item $start
                   11123: 
1.957     raeburn  11124: =item $type
                   11125: 
                   11126: =item $locktype
                   11127: 
                   11128: =item $cid
                   11129: 
                   11130: =item $selfenroll
                   11131: 
                   11132: =item $context
                   11133: 
1.297     matthew  11134: =back
                   11135: 
1.191     harris41 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11140: custom role; give a custom role to a user for the level given by URL.  Specify
                   11141: name and domain of role author, and role name
1.191     harris41 11142: 
                   11143: =item *
                   11144: 
1.243     albertel 11145: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11146: 
                   11147: =item *
                   11148: 
1.243     albertel 11149: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11150: 
                   11151: =back
                   11152: 
                   11153: =head2 Course Infomation
                   11154: 
                   11155: =over 4
1.191     harris41 11156: 
                   11157: =item *
                   11158: 
1.1118    foxr     11159: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11160: specified course id, including all environment settings for the
                   11161: course, the description of the course will be in the hash under the
                   11162: key 'description'
1.191     harris41 11163: 
1.1118    foxr     11164: $options is an optional parameter that if supplied is a hash reference that controls
                   11165: what how this function works.  It has the following key/values:
                   11166: 
                   11167: =over 4
                   11168: 
                   11169: =item freshen_cache
                   11170: 
                   11171: If defined, and the environment cache for the course is valid, it is 
                   11172: returned in the returned hash.
                   11173: 
                   11174: =item one_time
                   11175: 
                   11176: If defined, the last cache time is set to _now_
                   11177: 
                   11178: =item user
                   11179: 
                   11180: If defined, the supplied username is used instead of the current user.
                   11181: 
                   11182: 
                   11183: =back
                   11184: 
1.191     harris41 11185: =item *
                   11186: 
1.624     albertel 11187: resdata($name,$domain,$type,@which) : request for current parameter
                   11188: setting for a specific $type, where $type is either 'course' or 'user',
                   11189: @what should be a list of parameters to ask about. This routine caches
                   11190: answers for 5 minutes.
1.243     albertel 11191: 
1.877     foxr     11192: =item *
                   11193: 
                   11194: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11195: data base, returning a hash that is keyed by the resource name and has
                   11196: values that are the resource value.  I believe that the timestamps and
                   11197: versions are also returned.
                   11198: 
                   11199: 
1.243     albertel 11200: =back
                   11201: 
                   11202: =head2 Course Modification
                   11203: 
                   11204: =over 4
1.191     harris41 11205: 
                   11206: =item *
                   11207: 
1.243     albertel 11208: writecoursepref($courseid,%prefs) : write preferences (environment
                   11209: database) for a course
1.191     harris41 11210: 
                   11211: =item *
                   11212: 
1.1011    raeburn  11213: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11214: 
                   11215: =item *
                   11216: 
1.1038    raeburn  11217: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11218: 
                   11219: =back
                   11220: 
                   11221: =head2 Resource Subroutines
                   11222: 
                   11223: =over 4
1.191     harris41 11224: 
                   11225: =item *
                   11226: 
1.243     albertel 11227: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11228: 
                   11229: =item *
                   11230: 
1.243     albertel 11231: repcopy($filename) : subscribes to the requested file, and attempts to
                   11232: replicate from the owning library server, Might return
1.607     raeburn  11233: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11234: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11235: resource. Expects the local filesystem pathname
                   11236: (/home/httpd/html/res/....)
                   11237: 
                   11238: =back
                   11239: 
                   11240: =head2 Resource Information
                   11241: 
                   11242: =over 4
1.191     harris41 11243: 
                   11244: =item *
                   11245: 
1.243     albertel 11246: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11247: a vairety of different possible values, $varname should be a request
                   11248: string, and the other parameters can be used to specify who and what
                   11249: one is asking about.
                   11250: 
                   11251: Possible values for $varname are environment.lastname (or other item
                   11252: from the envirnment hash), user.name (or someother aspect about the
                   11253: user), resource.0.maxtries (or some other part and parameter of a
                   11254: resource)
1.204     albertel 11255: 
                   11256: =item *
                   11257: 
1.243     albertel 11258: directcondval($number) : get current value of a condition; reads from a state
                   11259: string
1.204     albertel 11260: 
                   11261: =item *
                   11262: 
1.243     albertel 11263: condval($condidx) : value of condition index based on state
1.204     albertel 11264: 
                   11265: =item *
                   11266: 
1.243     albertel 11267: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11268: resource's metadata, $what should be either a specific key, or either
                   11269: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11270: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11271: 
                   11272: this function automatically caches all requests
1.191     harris41 11273: 
                   11274: =item *
                   11275: 
1.243     albertel 11276: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11277: network of library servers; returns file handle of where SQL and regex results
                   11278: will be stored for query
1.191     harris41 11279: 
                   11280: =item *
                   11281: 
1.243     albertel 11282: symbread($filename) : return symbolic list entry (filename argument optional);
                   11283: returns the data handle
1.191     harris41 11284: 
                   11285: =item *
                   11286: 
1.243     albertel 11287: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11288: a possible symb for the URL in $thisfn, and if is an encryypted
                   11289: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11290: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11291: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11292: 
1.191     harris41 11293: 
                   11294: =item *
                   11295: 
1.243     albertel 11296: symbclean($symb) : removes versions numbers from a symb, returns the
                   11297: cleaned symb
1.191     harris41 11298: 
                   11299: =item *
                   11300: 
1.243     albertel 11301: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11302: course map, user must be in a course for it to work.
1.191     harris41 11303: 
                   11304: =item *
                   11305: 
1.243     albertel 11306: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11307: 
                   11308: =item *
                   11309: 
1.243     albertel 11310: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11311: a random seed, all arguments are optional, if they aren't sent it uses the
                   11312: environment to derive them. Note: if symb isn't sent and it can't get one
                   11313: from &symbread it will use the current time as its return value
1.191     harris41 11314: 
                   11315: =item *
                   11316: 
1.243     albertel 11317: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11318: unfakeable, receipt
1.191     harris41 11319: 
                   11320: =item *
                   11321: 
1.620     albertel 11322: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11323: 
                   11324: =item *
                   11325: 
1.243     albertel 11326: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11327: 
                   11328: =item *
                   11329: 
1.243     albertel 11330: 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 11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: 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 11335: 
                   11336: =item *
                   11337: 
1.243     albertel 11338: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11339: 
                   11340: =item *
                   11341: 
1.243     albertel 11342: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11343: forcing spreadsheet to reevaluate the resource scores next time.
                   11344: 
                   11345: =back
                   11346: 
                   11347: =head2 Storing/Retreiving Data
                   11348: 
                   11349: =over 4
1.191     harris41 11350: 
                   11351: =item *
                   11352: 
1.243     albertel 11353: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11354: for this url; hashref needs to be given and should be a \%hashname; the
                   11355: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11356: be derived from the env
1.191     harris41 11357: 
                   11358: =item *
                   11359: 
1.243     albertel 11360: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11361: uses critical subroutine
1.191     harris41 11362: 
                   11363: =item *
                   11364: 
1.243     albertel 11365: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11366: all args are optional
1.191     harris41 11367: 
                   11368: =item *
                   11369: 
1.717     albertel 11370: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11371: dumps the complete (or key matching regexp) namespace into a hash
                   11372: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11373: normally &store()ed into
                   11374: 
                   11375: $range should be either an integer '100' (give me the first 100
                   11376:                                            matching records)
                   11377:               or be  two integers sperated by a - with no spaces
                   11378:                  '30-50' (give me the 30th through the 50th matching
                   11379:                           records)
                   11380: 
                   11381: 
                   11382: =item *
                   11383: 
                   11384: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11385: replaces a &store() version of data with a replacement set of data
                   11386: for a particular resource in a namespace passed in the $storehash hash 
                   11387: reference
                   11388: 
                   11389: =item *
                   11390: 
1.243     albertel 11391: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11392: works very similar to store/cstore, but all data is stored in a
                   11393: temporary location and can be reset using tmpreset, $storehash should
                   11394: be a hash reference, returns nothing on success
1.191     harris41 11395: 
                   11396: =item *
                   11397: 
1.243     albertel 11398: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11399: similar to restore, but all data is stored in a temporary location and
                   11400: can be reset using tmpreset. Returns a hash of values on success,
                   11401: error string otherwise.
1.191     harris41 11402: 
                   11403: =item *
                   11404: 
1.243     albertel 11405: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11406: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11407: 
                   11408: =item *
                   11409: 
1.243     albertel 11410: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11411: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11412: 
                   11413: =item *
                   11414: 
1.243     albertel 11415: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11416: namesp ($udom and $uname are optional)
1.191     harris41 11417: 
                   11418: =item *
                   11419: 
1.702     albertel 11420: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11421: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11422: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11423: 
1.702     albertel 11424: $range should be either an integer '100' (give me the first 100
                   11425:                                            matching records)
                   11426:               or be  two integers sperated by a - with no spaces
                   11427:                  '30-50' (give me the 30th through the 50th matching
                   11428:                           records)
1.449     matthew  11429: =item *
                   11430: 
                   11431: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11432: $store can be a scalar, an array reference, or if the amount to be 
                   11433: incremented is > 1, a hash reference.
                   11434: 
                   11435: ($udom and $uname are optional)
1.191     harris41 11436: 
                   11437: =item *
                   11438: 
1.243     albertel 11439: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11440: ($udom and $uname are optional)
1.191     harris41 11441: 
                   11442: =item *
                   11443: 
1.243     albertel 11444: cput($namespace,$storehash,$udom,$uname) : critical put
                   11445: ($udom and $uname are optional)
1.191     harris41 11446: 
                   11447: =item *
                   11448: 
1.748     albertel 11449: newput($namespace,$storehash,$udom,$uname) :
                   11450: 
                   11451: Attempts to store the items in the $storehash, but only if they don't
                   11452: currently exist, if this succeeds you can be certain that you have 
                   11453: successfully created a new key value pair in the $namespace db.
                   11454: 
                   11455: 
                   11456: Args:
                   11457:  $namespace: name of database to store values to
                   11458:  $storehash: hashref to store to the db
                   11459:  $udom: (optional) domain of user containing the db
                   11460:  $uname: (optional) name of user caontaining the db
                   11461: 
                   11462: Returns:
                   11463:  'ok' -> succeeded in storing all keys of $storehash
                   11464:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11465:                         least <key> already existed in the db (other
                   11466:                         requested keys may also already exist)
1.967     bisitz   11467:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11468:  'con_lost' -> unable to contact request server
                   11469:  'refused' -> action was not allowed by remote machine
                   11470: 
                   11471: 
                   11472: =item *
                   11473: 
1.243     albertel 11474: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11475: reference filled in from namesp (encrypts the return communication)
                   11476: ($udom and $uname are optional)
1.191     harris41 11477: 
                   11478: =item *
                   11479: 
1.243     albertel 11480: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11481: critical subroutine
                   11482: 
1.806     raeburn  11483: =item *
                   11484: 
1.860     raeburn  11485: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11486: array reference filled in from namespace found in domain level on either
                   11487: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11488: 
                   11489: =item *
                   11490: 
1.860     raeburn  11491: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11492: domain level either on specified domain server ($uhome) or primary domain 
                   11493: server ($udom and $uhome are optional)
1.806     raeburn  11494: 
1.943     raeburn  11495: =item * 
                   11496: 
                   11497: get_domain_defaults($target_domain) : returns hash with defaults for
                   11498: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11499: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11500: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11501: Values are retrieved from cache (if current), or from domain's configuration.db
                   11502: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11503: or lonTabs/domain.tab. 
                   11504: 
                   11505: %domdefaults = &get_auth_defaults($target_domain);
                   11506: 
1.243     albertel 11507: =back
                   11508: 
                   11509: =head2 Network Status Functions
                   11510: 
                   11511: =over 4
1.191     harris41 11512: 
                   11513: =item *
                   11514: 
                   11515: dirlist($uri) : return directory list based on URI
                   11516: 
                   11517: =item *
                   11518: 
1.243     albertel 11519: spareserver() : find server with least workload from spare.tab
                   11520: 
1.986     foxr     11521: 
                   11522: =item *
                   11523: 
                   11524: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11525: if there is no corresponding loncapa host.
                   11526: 
1.243     albertel 11527: =back
                   11528: 
1.986     foxr     11529: 
1.243     albertel 11530: =head2 Apache Request
                   11531: 
                   11532: =over 4
1.191     harris41 11533: 
                   11534: =item *
                   11535: 
1.243     albertel 11536: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11537: localhost, posts hash
                   11538: 
                   11539: =back
                   11540: 
                   11541: =head2 Data to String to Data
                   11542: 
                   11543: =over 4
1.191     harris41 11544: 
                   11545: =item *
                   11546: 
1.243     albertel 11547: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11548: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11549: 
                   11550: =item *
                   11551: 
1.243     albertel 11552: hashref2str($hashref) : convert a hashref into a string complete with
                   11553: escaping and '=' and '&' separators, supports elements that are
                   11554: arrayrefs and hashrefs
1.191     harris41 11555: 
                   11556: =item *
                   11557: 
1.243     albertel 11558: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11559: with escaping and '&' separators, supports elements that are arrayrefs
                   11560: and hashrefs
1.191     harris41 11561: 
                   11562: =item *
                   11563: 
1.243     albertel 11564: str2hash($string) : convert string to hash using unescaping and
                   11565: splitting on '=' and '&', supports elements that are arrayrefs and
                   11566: hashrefs
1.191     harris41 11567: 
                   11568: =item *
                   11569: 
1.243     albertel 11570: str2array($string) : convert string to hash using unescaping and
                   11571: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11572: 
                   11573: =back
                   11574: 
                   11575: =head2 Logging Routines
                   11576: 
                   11577: 
                   11578: These routines allow one to make log messages in the lonnet.log and
                   11579: lonnet.perm logfiles.
1.191     harris41 11580: 
1.1119    foxr     11581: =over 4
                   11582: 
1.191     harris41 11583: =item *
                   11584: 
1.243     albertel 11585: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11586: 
                   11587: =item *
                   11588: 
1.243     albertel 11589: logthis() : append message to the normal lonnet.log file, it gets
                   11590: preiodically rolled over and deleted.
1.191     harris41 11591: 
                   11592: =item *
                   11593: 
1.243     albertel 11594: logperm() : append a permanent message to lonnet.perm.log, this log
                   11595: file never gets deleted by any automated portion of the system, only
                   11596: messages of critical importance should go in here.
                   11597: 
1.1119    foxr     11598: 
1.243     albertel 11599: =back
                   11600: 
                   11601: =head2 General File Helper Routines
                   11602: 
                   11603: =over 4
1.191     harris41 11604: 
                   11605: =item *
                   11606: 
1.481     raeburn  11607: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11608: (a) files in /uploaded
                   11609:   (i) If a local copy of the file exists - 
                   11610:       compares modification date of local copy with last-modified date for 
                   11611:       definitive version stored on home server for course. If local copy is 
                   11612:       stale, requests a new version from the home server and stores it. 
                   11613:       If the original has been removed from the home server, then local copy 
                   11614:       is unlinked.
                   11615:   (ii) If local copy does not exist -
                   11616:       requests the file from the home server and stores it. 
                   11617:   
                   11618:   If $caller is 'uploadrep':  
                   11619:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11620:     for request for files originally uploaded via DOCS. 
                   11621:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11622:   
                   11623:   Otherwise:
                   11624:      This indicates a call from the content generation phase of the request.
                   11625:      -  returns the entire contents of the file or -1.
                   11626:      
                   11627: (b) files in /res
                   11628:    - returns the entire contents of a file or -1; 
                   11629:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11630: 
1.712     albertel 11631: 
                   11632: =item *
                   11633: 
                   11634: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11635:                   reference
                   11636: 
                   11637: returns either a stat() list of data about the file or an empty list
                   11638: if the file doesn't exist or couldn't find out about it (connection
                   11639: problems or user unknown)
                   11640: 
1.191     harris41 11641: =item *
                   11642: 
1.243     albertel 11643: filelocation($dir,$file) : returns file system location of a file
                   11644: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11645: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11646: and a file of ../bob will become /a/bob)
1.191     harris41 11647: 
                   11648: =item *
                   11649: 
                   11650: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11651: filelocation except for hrefs
                   11652: 
                   11653: =item *
                   11654: 
                   11655: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11656: 
1.243     albertel 11657: =back
                   11658: 
1.608     albertel 11659: =head2 Usererfile file routines (/uploaded*)
                   11660: 
                   11661: =over 4
                   11662: 
                   11663: =item *
                   11664: 
                   11665: userfileupload(): main rotine for putting a file in a user or course's
                   11666:                   filespace, arguments are,
                   11667: 
1.620     albertel 11668:  formname - required - this is the name of the element in $env where the
1.608     albertel 11669:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11670:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11671:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11672:  context - if coursedoc, store the file in the course of the active role
                   11673:              of the current user; 
                   11674:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11675:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11676:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11677:          if undefined, it will be placed in "unknown"
                   11678: 
                   11679:  (This routine calls clean_filename() to remove any dangerous
                   11680:  characters from the filename, and then calls finuserfileupload() to
                   11681:  complete the transaction)
                   11682: 
                   11683:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11684:  and /adm/notfound.html if unsuccessful
                   11685: 
                   11686: =item *
                   11687: 
                   11688: clean_filename(): routine for cleaing a filename up for storage in
                   11689:                  userfile space, argument is:
                   11690: 
                   11691:  filename - proposed filename
                   11692: 
                   11693: returns: the new clean filename
                   11694: 
                   11695: =item *
                   11696: 
1.1090    raeburn  11697: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11698: userspace, probably shouldn't be called directly
                   11699: 
                   11700:   docuname: username or courseid of destination for the file
                   11701:   docudom: domain of user/course of destination for the file
                   11702:   formname: same as for userfileupload()
1.1090    raeburn  11703:   fname: filename (including subdirectories) for the file
                   11704:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11705:   allfiles: reference to hash used to store objects found by parser
                   11706:   codebase: reference to hash used for codebases of java objects found by parser
                   11707:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11708:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11709:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11710:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11711:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11712:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11713:   mimetype: reference to scalar to accommodate mime type determined
                   11714:             from File::MMagic if $parser = parse.
1.608     albertel 11715: 
                   11716:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11717:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11718:  was 'overwrite').
                   11719:  
1.608     albertel 11720: 
                   11721: =item *
                   11722: 
                   11723: renameuserfile(): renames an existing userfile to a new name
                   11724: 
                   11725:   Args:
                   11726:    docuname: username or courseid of destination for the file
                   11727:    docudom: domain of user/course of destination for the file
                   11728:    old: current file name (including any subdirs under userfiles)
                   11729:    new: desired file name (including any subdirs under userfiles)
                   11730: 
                   11731: =item *
                   11732: 
                   11733: mkdiruserfile(): creates a directory is a userfiles dir
                   11734: 
                   11735:   Args:
                   11736:    docuname: username or courseid of destination for the file
                   11737:    docudom: domain of user/course of destination for the file
                   11738:    dir: dir to create (including any subdirs under userfiles)
                   11739: 
                   11740: =item *
                   11741: 
                   11742: removeuserfile(): removes a file that exists in userfiles
                   11743: 
                   11744:   Args:
                   11745:    docuname: username or courseid of destination for the file
                   11746:    docudom: domain of user/course of destination for the file
                   11747:    fname: filname to delete (including any subdirs under userfiles)
                   11748: 
                   11749: =item *
                   11750: 
                   11751: removeuploadedurl(): convience function for removeuserfile()
                   11752: 
                   11753:   Args:
                   11754:    url:  a full /uploaded/... url to delete
                   11755: 
1.747     albertel 11756: =item * 
                   11757: 
                   11758: get_portfile_permissions():
                   11759:   Args:
                   11760:     domain: domain of user or course contain the portfolio files
                   11761:     user: name of user or num of course contain the portfolio files
                   11762:   Returns:
                   11763:     hashref of a dump of the proper file_permissions.db
                   11764:    
                   11765: 
                   11766: =item * 
                   11767: 
                   11768: get_access_controls():
                   11769: 
                   11770: Args:
                   11771:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11772:   group: (optional) the group you want the files associated with
                   11773:   file: (optional) the file you want access info on
                   11774: 
                   11775: Returns:
1.749     raeburn  11776:     a hash (keys are file names) of hashes containing
                   11777:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11778:         values are XML containing access control settings (see below) 
1.747     albertel 11779: 
                   11780: Internal notes:
                   11781: 
1.749     raeburn  11782:  access controls are stored in file_permissions.db as key=value pairs.
                   11783:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11784:         where scope -> public,guest,course,group,domains or users.
                   11785:               end -> UNIX time for end of access (0 -> no end date)
                   11786:               start -> UNIX time for start of access
                   11787: 
                   11788:     value -> XML description of access control
                   11789:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11790:             <start></start>
                   11791:             <end></end>
                   11792: 
                   11793:             <password></password>  for scope type = guest
                   11794: 
                   11795:             <domain></domain>     for scope type = course or group
                   11796:             <number></number>
                   11797:             <roles id="">
                   11798:              <role></role>
                   11799:              <access></access>
                   11800:              <section></section>
                   11801:              <group></group>
                   11802:             </roles>
                   11803: 
                   11804:             <dom></dom>         for scope type = domains
                   11805: 
                   11806:             <users>             for scope type = users
                   11807:              <user>
                   11808:               <uname></uname>
                   11809:               <udom></udom>
                   11810:              </user>
                   11811:             </users>
                   11812:            </scope> 
                   11813:               
                   11814:  Access data is also aggregated for each file in an additional key=value pair:
                   11815:  key -> path to file/file_name\0accesscontrol 
                   11816:  value -> reference to hash
                   11817:           hash contains key = value pairs
                   11818:           where key = uniqueID:scope_end_start
                   11819:                 value = UNIX time record was last updated
                   11820: 
                   11821:           Used to improve speed of look-ups of access controls for each file.  
                   11822:  
                   11823:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11824: 
                   11825: modify_access_controls():
                   11826: 
                   11827: Modifies access controls for a portfolio file
                   11828: Args
                   11829: 1. file name
                   11830: 2. reference to hash of required changes,
                   11831: 3. domain
                   11832: 4. username
                   11833:   where domain,username are the domain of the portfolio owner 
                   11834:   (either a user or a course) 
                   11835: 
                   11836: Returns:
                   11837: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11838: 2. result of deletions ('ok' or 'error', with error message).
                   11839: 3. reference to hash of any new or updated access controls.
                   11840: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11841:    key = integer (inbound ID)
                   11842:    value = uniqueID  
1.747     albertel 11843: 
1.608     albertel 11844: =back
                   11845: 
1.243     albertel 11846: =head2 HTTP Helper Routines
                   11847: 
                   11848: =over 4
                   11849: 
1.191     harris41 11850: =item *
                   11851: 
                   11852: escape() : unpack non-word characters into CGI-compatible hex codes
                   11853: 
                   11854: =item *
                   11855: 
                   11856: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11857: 
1.243     albertel 11858: =back
                   11859: 
                   11860: =head1 PRIVATE SUBROUTINES
                   11861: 
                   11862: =head2 Underlying communication routines (Shouldn't call)
                   11863: 
                   11864: =over 4
                   11865: 
                   11866: =item *
                   11867: 
                   11868: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11869: 
                   11870: =item *
                   11871: 
                   11872: reply() : uses subreply to send a message to remote machine, logs all failures
                   11873: 
                   11874: =item *
                   11875: 
                   11876: critical() : passes a critical message to another server; if cannot
                   11877: get through then place message in connection buffer directory and
                   11878: returns con_delayed, if incapable of saving message, returns
                   11879: con_failed
                   11880: 
                   11881: =item *
                   11882: 
                   11883: reconlonc() : tries to reconnect lonc client processes.
                   11884: 
                   11885: =back
                   11886: 
                   11887: =head2 Resource Access Logging
                   11888: 
                   11889: =over 4
                   11890: 
                   11891: =item *
                   11892: 
                   11893: flushcourselogs() : flush (save) buffer logs and access logs
                   11894: 
                   11895: =item *
                   11896: 
                   11897: courselog($what) : save message for course in hash
                   11898: 
                   11899: =item *
                   11900: 
                   11901: courseacclog($what) : save message for course using &courselog().  Perform
                   11902: special processing for specific resource types (problems, exams, quizzes, etc).
                   11903: 
1.191     harris41 11904: =item *
                   11905: 
                   11906: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11907: as a PerlChildExitHandler
1.243     albertel 11908: 
                   11909: =back
                   11910: 
                   11911: =head2 Other
                   11912: 
                   11913: =over 4
                   11914: 
                   11915: =item *
                   11916: 
                   11917: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11918: 
                   11919: =back
                   11920: 
                   11921: =cut
1.877     foxr     11922: 

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