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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.28! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.27 2013/05/29 19:36:56 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.1172.2.18  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
                    355:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   357:     return $response;
                    358: }
                    359: 
1.1       albertel  360: # -------------------------------------------------- Non-critical communication
                    361: sub subreply {
                    362:     my ($cmd,$server)=@_;
1.838     albertel  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      364:     #
                    365:     #  With loncnew process trimming, there's a timing hole between lonc server
                    366:     #  process exit and the master server picking up the listen on the AF_UNIX
                    367:     #  socket.  In that time interval, a lock file will exist:
                    368: 
                    369:     my $lockfile=$peerfile.".lock";
                    370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    371: 	sleep(1);
                    372:     }
                    373:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      374:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      375:     #
1.550     foxr      376:     #   We'll give the connection a few tries before abandoning it.  If
                    377:     #   connection is not possible, we'll con_lost back to the client.
                    378:     #   
                    379:     my $client;
                    380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    382: 				      Type    => SOCK_STREAM,
                    383: 				      Timeout => 10);
1.869     albertel  384: 	if ($client) {
1.550     foxr      385: 	    last;		# Connected!
1.850     albertel  386: 	} else {
1.853     albertel  387: 	    &create_connection(&hostname($server),$server);
1.550     foxr      388: 	}
1.850     albertel  389:         sleep(1);		# Try again later if failed connection.
1.550     foxr      390:     }
                    391:     my $answer;
                    392:     if ($client) {
1.704     albertel  393: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      394: 	$answer=<$client>;
                    395: 	if (!$answer) { $answer="con_lost"; }
                    396: 	chomp($answer);
                    397:     } else {
                    398: 	$answer = 'con_lost';	# Failed connection.
                    399:     }
1.1       albertel  400:     return $answer;
                    401: }
                    402: 
                    403: sub reply {
                    404:     my ($cmd,$server)=@_;
1.838     albertel  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  406:     my $answer=subreply($cmd,$server);
1.65      www       407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  408:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       409:                 " $cmd to $server returned $answer</font>");
                    410:     }
1.1       albertel  411:     return $answer;
                    412: }
                    413: 
                    414: # ----------------------------------------------------------- Send USR1 to lonc
                    415: 
                    416: sub reconlonc {
1.891     albertel  417:     my ($lonid) = @_;
                    418:     my $hostname = &hostname($lonid);
                    419:     if ($lonid) {
                    420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    421: 	if ($hostname && -e $peerfile) {
                    422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    424: 					     Type    => SOCK_STREAM,
                    425: 					     Timeout => 10);
                    426: 	    if ($client) {
                    427: 		print $client ("reset_retries\n");
                    428: 		my $answer=<$client>;
                    429: 		#reset just this one.
                    430: 	    }
                    431: 	}
                    432: 	return;
                    433:     }
                    434: 
1.836     www       435:     &logthis("Trying to reconnect lonc");
1.1       albertel  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  437:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  438: 	my $loncpid=<$fh>;
                    439:         chomp($loncpid);
                    440:         if (kill 0 => $loncpid) {
                    441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    442:             kill USR1 => $loncpid;
                    443:             sleep 1;
1.836     www       444:          } else {
1.12      www       445: 	    &logthis(
1.672     albertel  446:                "<font color=\"blue\">WARNING:".
1.12      www       447:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  448:         }
                    449:     } else {
1.836     www       450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  451:     }
                    452: }
                    453: 
                    454: # ------------------------------------------------------ Critical communication
1.12      www       455: 
1.1       albertel  456: sub critical {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (&hostname($server)) {
1.672     albertel  459:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       460:                " Critical message to unknown server ($server)</font>");
                    461:         return 'no_such_host';
                    462:     }
1.1       albertel  463:     my $answer=reply($cmd,$server);
                    464:     if ($answer eq 'con_lost') {
                    465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  466: 	my $answer=reply($cmd,$server);
1.1       albertel  467:         if ($answer eq 'con_lost') {
                    468:             my $now=time;
                    469:             my $middlename=$cmd;
1.5       www       470:             $middlename=substr($middlename,0,16);
1.1       albertel  471:             $middlename=~s/\W//g;
                    472:             my $dfilename=
1.305     www       473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    474:             $dumpcount++;
1.1       albertel  475:             {
1.448     albertel  476: 		my $dfh;
                    477: 		if (open($dfh,">$dfilename")) {
                    478: 		    print $dfh "$cmd\n"; 
                    479: 		    close($dfh);
                    480: 		}
1.1       albertel  481:             }
                    482:             sleep 2;
                    483:             my $wcmd='';
                    484:             {
1.448     albertel  485: 		my $dfh;
                    486: 		if (open($dfh,"<$dfilename")) {
                    487: 		    $wcmd=<$dfh>; 
                    488: 		    close($dfh);
                    489: 		}
1.1       albertel  490:             }
                    491:             chomp($wcmd);
1.7       www       492:             if ($wcmd eq $cmd) {
1.672     albertel  493: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       494:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  495:                 &logperm("D:$server:$cmd");
                    496: 	        return 'con_delayed';
                    497:             } else {
1.672     albertel  498:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       499:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  500:                 &logperm("F:$server:$cmd");
                    501:                 return 'con_failed';
                    502:             }
                    503:         }
                    504:     }
                    505:     return $answer;
1.405     albertel  506: }
                    507: 
1.755     albertel  508: # ------------------------------------------- check if return value is an error
                    509: 
                    510: sub error {
                    511:     my ($result) = @_;
1.756     albertel  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  513: 	if ($2 == 2) { return undef; }
                    514: 	return $1;
                    515:     }
                    516:     return undef;
                    517: }
                    518: 
1.783     albertel  519: sub convert_and_load_session_env {
                    520:     my ($lonidsdir,$handle)=@_;
                    521:     my @profile;
                    522:     {
1.917     albertel  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    524: 	if (!$opened) {
1.915     albertel  525: 	    return 0;
                    526: 	}
1.783     albertel  527: 	flock($idf,LOCK_SH);
                    528: 	@profile=<$idf>;
                    529: 	close($idf);
                    530:     }
                    531:     my %temp_env;
                    532:     foreach my $line (@profile) {
1.786     albertel  533: 	if ($line !~ m/=/) {
                    534: 	    return 0;
                    535: 	}
1.783     albertel  536: 	chomp($line);
                    537: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    539:     }
                    540:     unlink("$lonidsdir/$handle.id");
                    541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    542: 	    0640)) {
                    543: 	%disk_env = %temp_env;
                    544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    545: 	untie(%disk_env);
                    546:     }
1.786     albertel  547:     return 1;
1.783     albertel  548: }
                    549: 
1.374     www       550: # ------------------------------------------- Transfer profile into environment
1.780     albertel  551: my $env_loaded;
                    552: sub transfer_profile_to_env {
1.788     albertel  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    554:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       555: 
1.720     albertel  556:     if (!defined($lonidsdir)) {
                    557: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    558:     }
                    559:     if (!defined($handle)) {
                    560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    561:     }
                    562: 
1.786     albertel  563:     my $convert;
                    564:     {
1.917     albertel  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    566: 	if (!$opened) {
1.915     albertel  567: 	    return;
                    568: 	}
1.786     albertel  569: 	flock($idf,LOCK_SH);
                    570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    571: 		&GDBM_READER(),0640)) {
                    572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    573: 	    untie(%disk_env);
                    574: 	} else {
                    575: 	    $convert = 1;
                    576: 	}
                    577:     }
                    578:     if ($convert) {
                    579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    580: 	    &logthis("Failed to load session, or convert session.");
                    581: 	}
1.374     www       582:     }
1.783     albertel  583: 
1.786     albertel  584:     my %remove;
1.783     albertel  585:     while ( my $envname = each(%env) ) {
1.433     matthew   586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    587:             if ($time < time-300) {
1.783     albertel  588:                 $remove{$key}++;
1.433     matthew   589:             }
                    590:         }
                    591:     }
1.783     albertel  592: 
1.619     albertel  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  594:     $env_loaded=1;
1.783     albertel  595:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   596:         &delenv($expired_key);
1.374     www       597:     }
1.1       albertel  598: }
                    599: 
1.916     albertel  600: # ---------------------------------------------------- Check for valid session 
                    601: sub check_for_valid_session {
1.1155    raeburn   602:     my ($r,$name) = @_;
1.916     albertel  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   604:     if ($name eq '') {
                    605:         $name = 'lonID';
                    606:     }
                    607:     my $lonid=$cookies{$name};
1.916     albertel  608:     return undef if (!$lonid);
                    609: 
                    610:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   611:     my $lonidsdir;
                    612:     if ($name eq 'lonDAV') {
                    613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    614:     } else {
                    615:         $lonidsdir=$r->dir_config('lonIDsDir');
                    616:     }
1.916     albertel  617:     return undef if (!-e "$lonidsdir/$handle.id");
                    618: 
1.917     albertel  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    620:     return undef if (!$opened);
1.916     albertel  621: 
                    622:     flock($idf,LOCK_SH);
                    623:     my %disk_env;
                    624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    625: 	    &GDBM_READER(),0640)) {
                    626: 	return undef;	
                    627:     }
                    628: 
                    629:     if (!defined($disk_env{'user.name'})
                    630: 	|| !defined($disk_env{'user.domain'})) {
                    631: 	return undef;
                    632:     }
1.1172.2.18  raeburn   633: 
                    634:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    635:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    636:             $r->user($disk_env{'user.name'});
                    637:         } else {
                    638:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    639:         }
                    640:     }
                    641: 
1.916     albertel  642:     return $handle;
                    643: }
                    644: 
1.830     albertel  645: sub timed_flock {
                    646:     my ($file,$lock_type) = @_;
                    647:     my $failed=0;
                    648:     eval {
                    649: 	local $SIG{__DIE__}='DEFAULT';
                    650: 	local $SIG{ALRM}=sub {
                    651: 	    $failed=1;
                    652: 	    die("failed lock");
                    653: 	};
                    654: 	alarm(13);
                    655: 	flock($file,$lock_type);
                    656: 	alarm(0);
                    657:     };
                    658:     if ($failed) {
                    659: 	return undef;
                    660:     } else {
                    661: 	return 1;
                    662:     }
                    663: }
                    664: 
1.5       www       665: # ---------------------------------------------------------- Append Environment
                    666: 
                    667: sub appenv {
1.949     raeburn   668:     my ($newenv,$roles) = @_;
                    669:     if (ref($newenv) eq 'HASH') {
                    670:         foreach my $key (keys(%{$newenv})) {
                    671:             my $refused = 0;
                    672: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    673:                 $refused = 1;
                    674:                 if (ref($roles) eq 'ARRAY') {
                    675:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    676:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    677:                         $refused = 0;
                    678:                     }
                    679:                 }
                    680:             }
                    681:             if ($refused) {
                    682:                 &logthis("<font color=\"blue\">WARNING: ".
                    683:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    684:                          .'</font>');
                    685: 	        delete($newenv->{$key});
                    686:             } else {
                    687:                 $env{$key}=$newenv->{$key};
                    688:             }
                    689:         }
                    690:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    691:         if ($opened
                    692: 	    && &timed_flock($env_file,LOCK_EX)
                    693: 	    &&
                    694: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    695: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    696: 	    while (my ($key,$value) = each(%{$newenv})) {
                    697: 	        $disk_env{$key} = $value;
                    698: 	    }
                    699: 	    untie(%disk_env);
1.35      www       700:         }
1.191     harris41  701:     }
1.56      www       702:     return 'ok';
                    703: }
                    704: # ----------------------------------------------------- Delete from Environment
                    705: 
                    706: sub delenv {
1.1104    raeburn   707:     my ($delthis,$regexp,$roles) = @_;
                    708:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    709:         my $refused = 1;
                    710:         if (ref($roles) eq 'ARRAY') {
                    711:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    712:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    713:                 $refused = 0;
                    714:             }
                    715:         }
                    716:         if ($refused) {
                    717:             &logthis("<font color=\"blue\">WARNING: ".
                    718:                      "Attempt to delete from environment ".$delthis);
                    719:             return 'error';
                    720:         }
1.56      www       721:     }
1.917     albertel  722:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    723:     if ($opened
1.915     albertel  724: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  725: 	&&
                    726: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    727: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  728: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   729: 	    if ($regexp) {
                    730:                 if ($key=~/^$delthis/) {
                    731:                     delete($env{$key});
                    732:                     delete($disk_env{$key});
                    733:                 } 
                    734:             } else {
                    735:                 if ($key=~/^\Q$delthis\E/) {
                    736: 		    delete($env{$key});
                    737: 		    delete($disk_env{$key});
                    738: 	        }
                    739:             }
1.448     albertel  740: 	}
1.783     albertel  741: 	untie(%disk_env);
1.5       www       742:     }
                    743:     return 'ok';
1.369     albertel  744: }
                    745: 
1.790     albertel  746: sub get_env_multiple {
                    747:     my ($name) = @_;
                    748:     my @values;
                    749:     if (defined($env{$name})) {
                    750:         # exists is it an array
                    751:         if (ref($env{$name})) {
                    752:             @values=@{ $env{$name} };
                    753:         } else {
                    754:             $values[0]=$env{$name};
                    755:         }
                    756:     }
                    757:     return(@values);
                    758: }
                    759: 
1.958     www       760: # ------------------------------------------------------------------- Locking
                    761: 
                    762: sub set_lock {
                    763:     my ($text)=@_;
                    764:     $locknum++;
                    765:     my $id=$$.'-'.$locknum;
                    766:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    767:              'session.lock.'.$id => $text});
                    768:     return $id;
                    769: }
                    770: 
                    771: sub get_locks {
                    772:     my $num=0;
                    773:     my %texts=();
                    774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    775:        if ($lock=~/\w/) {
                    776:           $num++;
                    777:           $texts{$lock}=$env{'session.lock.'.$lock};
                    778:        }
                    779:    }
                    780:    return ($num,%texts);
                    781: }
                    782: 
                    783: sub remove_lock {
                    784:     my ($id)=@_;
                    785:     my $newlocks='';
                    786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    787:        if (($lock=~/\w/) && ($lock ne $id)) {
                    788:           $newlocks.=','.$lock;
                    789:        }
                    790:     }
                    791:     &appenv({'session.locks' => $newlocks});
                    792:     &delenv('session.lock.'.$id);
                    793: }
                    794: 
                    795: sub remove_all_locks {
                    796:     my $activelocks=$env{'session.locks'};
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if ($lock=~/\w/) {
                    799:           &remove_lock($lock);
                    800:        }
                    801:     }
                    802: }
                    803: 
                    804: 
1.369     albertel  805: # ------------------------------------------ Find out current server userload
                    806: sub userload {
                    807:     my $numusers=0;
                    808:     {
                    809: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    810: 	my $filename;
                    811: 	my $curtime=time;
                    812: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  813: 	    next if ($filename eq '.' || $filename eq '..');
                    814: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  815: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  816: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  817: 	}
                    818: 	closedir(LONIDS);
                    819:     }
                    820:     my $userloadpercent=0;
                    821:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    822:     if ($maxuserload) {
1.371     albertel  823: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  824:     }
1.372     albertel  825:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  826:     return $userloadpercent;
1.283     www       827: }
                    828: 
1.1       albertel  829: # ------------------------------ Find server with least workload from spare.tab
1.11      www       830: 
1.1       albertel  831: sub spareserver {
1.1083    raeburn   832:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  833:     my $spare_server;
1.370     albertel  834:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  835:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    836:                                                      :  $userloadpercent;
1.1083    raeburn   837:     my ($uint_dom,$remotesessions);
                    838:     if (($udom ne '') && (&domain($udom) ne '')) {
                    839:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    840:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    841:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    842:         $remotesessions = $udomdefaults{'remotesessions'};
                    843:     }
1.1123    raeburn   844:     my $spareshash = &this_host_spares($udom);
                    845:     if (ref($spareshash) eq 'HASH') {
                    846:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    847:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    848:                 if ($uint_dom) {
                    849:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    850:                                                  $try_server));
                    851:                 }
                    852: 	        ($spare_server, $lowest_load) =
                    853: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    854:             }
1.1083    raeburn   855:         }
1.784     albertel  856: 
1.1123    raeburn   857:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    858: 
                    859:         if (!$found_server) {
                    860:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    861: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    862:                     if ($uint_dom) {
                    863:                         next unless (&spare_can_host($udom,$uint_dom,
                    864:                                                      $remotesessions,$try_server));
                    865:                     }
                    866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
                    889:     my ($try_server, $spare_server, $lowest_load) = @_;
                    890: 
                    891:     my $loadans     = &reply('load',    $try_server);
                    892:     my $userloadans = &reply('userload',$try_server);
                    893: 
                    894:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   895: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  896:     }
                    897: 
                    898:     my $load;
                    899:     if ($loadans =~ /\d/) {
                    900: 	if ($userloadans =~ /\d/) {
                    901: 	    #both are numbers, pick the bigger one
                    902: 	    $load = ($loadans > $userloadans) ? $loadans 
                    903: 		                              : $userloadans;
1.411     albertel  904: 	} else {
1.784     albertel  905: 	    $load = $loadans;
1.411     albertel  906: 	}
1.784     albertel  907:     } else {
                    908: 	$load = $userloadans;
                    909:     }
                    910: 
                    911:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    912: 	$spare_server = $try_server;
                    913: 	$lowest_load  = $load;
1.370     albertel  914:     }
1.784     albertel  915:     return ($spare_server,$lowest_load);
1.202     matthew   916: }
1.914     albertel  917: 
                    918: # --------------------------- ask offload servers if user already has a session
                    919: sub find_existing_session {
                    920:     my ($udom,$uname) = @_;
1.1123    raeburn   921:     my $spareshash = &this_host_spares($udom);
                    922:     if (ref($spareshash) eq 'HASH') {
                    923:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    924:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    926:             }
                    927:         }
                    928:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
1.914     albertel  933:     }
                    934:     return;
                    935: }
                    936: 
                    937: # -------------------------------- ask if server already has a session for user
                    938: sub has_user_session {
                    939:     my ($lonid,$udom,$uname) = @_;
                    940:     my $result = &reply(join(':','userhassession',
                    941: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    942:     return 1 if ($result eq 'ok');
                    943: 
                    944:     return 0;
                    945: }
                    946: 
1.1076    raeburn   947: # --------- determine least loaded server in a user's domain which allows login
                    948: 
                    949: sub choose_server {
1.1115    raeburn   950:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   951:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   952:     my %servers = &get_servers($udom);
1.1076    raeburn   953:     my $lowest_load = 30000;
1.1151    raeburn   954:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   955:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   956:         my $loginvia;
                    957:         if ($checkloginvia) {
                    958:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   959:             if ($loginvia) {
                    960:                 my ($server,$path) = split(/:/,$loginvia);
                    961:                 ($login_host, $lowest_load) =
                    962:                     &compare_server_load($server, $login_host, $lowest_load);
                    963:                 if ($login_host eq $server) {
                    964:                     $portal_path = $path;
1.1151    raeburn   965:                     $isredirect = 1;
1.1116    raeburn   966:                 }
                    967:             } else {
                    968:                 ($login_host, $lowest_load) =
                    969:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    970:                 if ($login_host eq $lonhost) {
                    971:                     $portal_path = '';
1.1151    raeburn   972:                     $isredirect = ''; 
1.1116    raeburn   973:                 }
                    974:             }
                    975:         } else {
1.1076    raeburn   976:             ($login_host, $lowest_load) =
1.1116    raeburn   977:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   978:         }
                    979:     }
                    980:     if ($login_host ne '') {
1.1116    raeburn   981:         $hostname = &hostname($login_host);
1.1076    raeburn   982:     }
1.1151    raeburn   983:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   984: }
                    985: 
1.202     matthew   986: # --------------------------------------------- Try to change a user's password
                    987: 
                    988: sub changepass {
1.799     raeburn   989:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   990:     $currentpass = &escape($currentpass);
                    991:     $newpass     = &escape($newpass);
1.1030    raeburn   992:     my $lonhost = $perlvar{'lonHostID'};
                    993:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   994: 		       $server);
                    995:     if (! $answer) {
                    996: 	&logthis("No reply on password change request to $server ".
                    997: 		 "by $uname in domain $udom.");
                    998:     } elsif ($answer =~ "^ok") {
                    999:         &logthis("$uname in $udom successfully changed their password ".
                   1000: 		 "on $server.");
                   1001:     } elsif ($answer =~ "^pwchange_failure") {
                   1002: 	&logthis("$uname in $udom was unable to change their password ".
                   1003: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1004: 		 "or pwchange");
                   1005:     } elsif ($answer =~ "^non_authorized") {
                   1006:         &logthis("$uname in $udom did not get their password correct when ".
                   1007: 		 "attempting to change it on $server.");
                   1008:     } elsif ($answer =~ "^auth_mode_error") {
                   1009:         &logthis("$uname in $udom attempted to change their password despite ".
                   1010: 		 "not being locally or internally authenticated on $server.");
                   1011:     } elsif ($answer =~ "^unknown_user") {
                   1012:         &logthis("$uname in $udom attempted to change their password ".
                   1013: 		 "on $server but were unable to because $server is not ".
                   1014: 		 "their home server.");
                   1015:     } elsif ($answer =~ "^refused") {
                   1016: 	&logthis("$server refused to change $uname in $udom password because ".
                   1017: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1018:     } elsif ($answer =~ "invalid_client") {
                   1019:         &logthis("$server refused to change $uname in $udom password because ".
                   1020:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1021:     }
                   1022:     return $answer;
1.1       albertel 1023: }
                   1024: 
1.169     harris41 1025: # ----------------------- Try to determine user's current authentication scheme
                   1026: 
                   1027: sub queryauthenticate {
                   1028:     my ($uname,$udom)=@_;
1.456     albertel 1029:     my $uhome=&homeserver($uname,$udom);
                   1030:     if (!$uhome) {
                   1031: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1032: 	return 'no_host';
                   1033:     }
                   1034:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1035:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1036: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1037:     }
1.456     albertel 1038:     return $answer;
1.169     harris41 1039: }
                   1040: 
1.1       albertel 1041: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1042: 
1.1       albertel 1043: sub authenticate {
1.1073    raeburn  1044:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1045:     $upass=&escape($upass);
                   1046:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1047:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1048:     my $newhome;
1.836     www      1049:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1050: # Maybe the machine was offline and only re-appeared again recently?
                   1051:         &reconlonc();
                   1052: # One more
1.952     raeburn  1053: 	$uhome=&homeserver($uname,$udom,1);
                   1054:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1055:             if (defined(&domain($udom,'primary'))) {
                   1056:                 $newhome=&domain($udom,'primary');
                   1057:             }
                   1058:             if ($newhome ne '') {
                   1059:                 $uhome = $newhome;
                   1060:             }
                   1061:         }
1.836     www      1062: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1063: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1064: 	    return 'no_host';
                   1065:         }
1.1       albertel 1066:     }
1.1073    raeburn  1067:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1068:     if ($answer eq 'authorized') {
1.952     raeburn  1069:         if ($newhome) {
                   1070:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1071:             return 'no_account_on_host'; 
                   1072:         } else {
                   1073:             &logthis("User $uname at $udom authorized by $uhome");
                   1074:             return $uhome;
                   1075:         }
1.471     albertel 1076:     }
                   1077:     if ($answer eq 'non_authorized') {
                   1078: 	&logthis("User $uname at $udom rejected by $uhome");
                   1079: 	return 'no_host'; 
1.9       www      1080:     }
1.471     albertel 1081:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1082:     return 'no_host';
                   1083: }
                   1084: 
1.1073    raeburn  1085: sub can_host_session {
1.1074    raeburn  1086:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1087:     my $canhost = 1;
1.1074    raeburn  1088:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1089:     if (ref($remotesessions) eq 'HASH') {
                   1090:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1091:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1092:                 $canhost = 0;
                   1093:             } else {
                   1094:                 $canhost = 1;
                   1095:             }
                   1096:         }
                   1097:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1098:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1099:                 $canhost = 1;
                   1100:             } else {
                   1101:                 $canhost = 0;
                   1102:             }
                   1103:         }
                   1104:         if ($canhost) {
                   1105:             if ($remotesessions->{'version'} ne '') {
                   1106:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1107:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1108:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1109:                         my $major = $1;
                   1110:                         my $minor = $2;
                   1111:                         if (($major < $reqmajor ) ||
                   1112:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1113:                             $canhost = 0;
                   1114:                         }
                   1115:                     } else {
                   1116:                         $canhost = 0;
                   1117:                     }
                   1118:                 }
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     if ($canhost) {
                   1123:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1124:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1125:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1126:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1127:                 if (($uint_dom ne '') && 
                   1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1129:                     $canhost = 0;
                   1130:                 } else {
                   1131:                     $canhost = 1;
                   1132:                 }
                   1133:             }
                   1134:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1135:                 if (($uint_dom ne '') && 
                   1136:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1137:                     $canhost = 1;
                   1138:                 } else {
                   1139:                     $canhost = 0;
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     return $canhost;
                   1145: }
                   1146: 
1.1083    raeburn  1147: sub spare_can_host {
                   1148:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1149:     my $canhost=1;
                   1150:     my @intdoms;
                   1151:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1152:     if (ref($internet_names) eq 'ARRAY') {
                   1153:         @intdoms = @{$internet_names};
                   1154:     }
                   1155:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1156:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1157:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1158:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1159:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1160:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1161:                                      $remotesessions,
                   1162:                                      $defdomdefaults{'hostedsessions'});
                   1163:     }
                   1164:     return $canhost;
                   1165: }
                   1166: 
1.1123    raeburn  1167: sub this_host_spares {
                   1168:     my ($dom) = @_;
1.1126    raeburn  1169:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1170:     my @hosts = &current_machine_ids();
                   1171:     foreach my $lonhost (@hosts) {
                   1172:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1173:             $dom_in_use = $dom;
                   1174:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1175:             last;
                   1176:         }
                   1177:     }
1.1126    raeburn  1178:     if ($dom_in_use ne '') {
                   1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1180:     }
                   1181:     if (ref($result) ne 'HASH') {
                   1182:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1183:         $dom_in_use = &host_domain($lonhost_in_use);
                   1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1185:         if (ref($result) ne 'HASH') {
                   1186:             $result = \%spareid;
                   1187:         }
                   1188:     }
                   1189:     return $result;
                   1190: }
                   1191: 
                   1192: sub spares_for_offload  {
                   1193:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1194:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1195:     if (defined($cached)) {
                   1196:         return $result;
                   1197:     } else {
1.1126    raeburn  1198:         my $cachetime = 60*60*24;
                   1199:         my %domconfig =
                   1200:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1201:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1202:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1203:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1204:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1205:                 }
                   1206:             }
                   1207:         }
                   1208:     }
1.1126    raeburn  1209:     return;
1.1123    raeburn  1210: }
                   1211: 
1.1129    raeburn  1212: sub get_lonbalancer_config {
                   1213:     my ($servers) = @_;
                   1214:     my ($currbalancer,$currtargets);
                   1215:     if (ref($servers) eq 'HASH') {
                   1216:         foreach my $server (keys(%{$servers})) {
                   1217:             my %what = (
                   1218:                          spareid => 1,
                   1219:                          perlvar => 1,
                   1220:                        );
                   1221:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1222:             if ($result eq 'ok') {
                   1223:                 if (ref($returnhash) eq 'HASH') {
                   1224:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1225:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1226:                             $currbalancer = $server;
                   1227:                             $currtargets = {};
                   1228:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1229:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1230:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1231:                                 }
                   1232:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1233:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1234:                                 }
                   1235:                             }
                   1236:                             last;
                   1237:                         }
                   1238:                     }
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return ($currbalancer,$currtargets);
                   1244: }
                   1245: 
                   1246: sub check_loadbalancing {
                   1247:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1248:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1249:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1250:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1251:     my @hosts = &current_machine_ids();
1.1129    raeburn  1252:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1253:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1254:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1255:     my $serverhomedom = &host_domain($lonhost);
                   1256: 
                   1257:     my $cachetime = 60*60*24;
                   1258: 
                   1259:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1260:         $dom_in_use = $udom;
                   1261:         $homeintdom = 1;
                   1262:     } else {
                   1263:         $dom_in_use = $serverhomedom;
                   1264:     }
                   1265:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1266:     unless (defined($cached)) {
                   1267:         my %domconfig =
                   1268:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1269:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1270:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1271:         }
                   1272:     }
                   1273:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1274:         ($is_balancer,$currtargets,$currrules) =
                   1275:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1276:         if ($is_balancer) {
                   1277:             if (ref($currrules) eq 'HASH') {
                   1278:                 if ($homeintdom) {
                   1279:                     if ($uname ne '') {
                   1280:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1281:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1282:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1283:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1284:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1286:                             }
                   1287:                         }
                   1288:                         if ($rule_in_effect eq '') {
                   1289:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1290:                             if ($userenv{'inststatus'} ne '') {
                   1291:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1292:                                 my ($othertitle,$usertypes,$types) =
                   1293:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1294:                                 if (ref($types) eq 'ARRAY') {
                   1295:                                     foreach my $type (@{$types}) {
                   1296:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1297:                                             if (exists($currrules->{$type})) {
                   1298:                                                 $rule_in_effect = $currrules->{$type};
                   1299:                                             }
                   1300:                                         }
                   1301:                                     }
                   1302:                                 }
                   1303:                             } else {
                   1304:                                 if (exists($currrules->{'default'})) {
                   1305:                                     $rule_in_effect = $currrules->{'default'};
                   1306:                                 }
                   1307:                             }
                   1308:                         }
                   1309:                     } else {
                   1310:                         if (exists($currrules->{'default'})) {
                   1311:                             $rule_in_effect = $currrules->{'default'};
                   1312:                         }
                   1313:                     }
                   1314:                 } else {
                   1315:                     if ($currrules->{'_LC_external'} ne '') {
                   1316:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1317:                     }
                   1318:                 }
                   1319:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1320:                                                        $uname,$udom);
                   1321:             }
                   1322:         }
                   1323:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1324:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1325:         unless (defined($cached)) {
                   1326:             my %domconfig =
                   1327:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1328:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1329:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1330:             }
                   1331:         }
                   1332:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1333:             ($is_balancer,$currtargets,$currrules) =
                   1334:                 &check_balancer_result($result,@hosts);
                   1335:             if ($is_balancer) {
1.1129    raeburn  1336:                 if (ref($currrules) eq 'HASH') {
                   1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1339:                     }
                   1340:                 }
                   1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1342:                                                        $uname,$udom);
                   1343:             }
                   1344:         } else {
                   1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1346:                 $is_balancer = 1;
                   1347:                 $offloadto = &this_host_spares($dom_in_use);
                   1348:             }
                   1349:         }
                   1350:     } else {
                   1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1352:             $is_balancer = 1;
                   1353:             $offloadto = &this_host_spares($dom_in_use);
                   1354:         }
                   1355:     }
1.1172.2.5  raeburn  1356:     if ($is_balancer) {
                   1357:         my $lowest_load = 30000;
                   1358:         if (ref($offloadto) eq 'HASH') {
                   1359:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1360:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1361:                     ($otherserver,$lowest_load) =
                   1362:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1363:                 }
1.1129    raeburn  1364:             }
1.1172.2.5  raeburn  1365:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1366: 
1.1172.2.5  raeburn  1367:             if (!$found_server) {
                   1368:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1369:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1370:                         ($otherserver,$lowest_load) =
                   1371:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1372:                     }
                   1373:                 }
                   1374:             }
                   1375:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1376:             if (@{$offloadto} == 1) {
                   1377:                 $otherserver = $offloadto->[0];
                   1378:             } elsif (@{$offloadto} > 1) {
                   1379:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1380:                     ($otherserver,$lowest_load) =
                   1381:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1382:                 }
                   1383:             }
                   1384:         }
1.1172.2.5  raeburn  1385:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1386:             $is_balancer = 0;
                   1387:             if ($uname ne '' && $udom ne '') {
                   1388:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1389: 
                   1390:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1391:                              'user.loadbalcheck.time' => time});
                   1392:                 }
1.1129    raeburn  1393:             }
                   1394:         }
                   1395:     }
                   1396:     return ($is_balancer,$otherserver);
                   1397: }
                   1398: 
1.1172.2.12  raeburn  1399: sub check_balancer_result {
                   1400:     my ($result,@hosts) = @_;
                   1401:     my ($is_balancer,$currtargets,$currrules);
                   1402:     if (ref($result) eq 'HASH') {
                   1403:         if ($result->{'lonhost'} ne '') {
                   1404:             my $currbalancer = $result->{'lonhost'};
                   1405:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1406:                 $is_balancer = 1;
                   1407:                 $currtargets = $result->{'targets'};
                   1408:                 $currrules = $result->{'rules'};
                   1409:             }
                   1410:         } else {
                   1411:             foreach my $key (keys(%{$result})) {
                   1412:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1413:                     (ref($result->{$key}) eq 'HASH')) {
                   1414:                     $is_balancer = 1;
                   1415:                     $currrules = $result->{$key}{'rules'};
                   1416:                     $currtargets = $result->{$key}{'targets'};
                   1417:                     last;
                   1418:                 }
                   1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$currtargets,$currrules);
                   1423: }
                   1424: 
1.1129    raeburn  1425: sub get_loadbalancer_targets {
                   1426:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1427:     my $offloadto;
1.1172.2.4  raeburn  1428:     if ($rule_in_effect eq 'none') {
                   1429:         return [$perlvar{'lonHostID'}];
                   1430:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1431:         $offloadto = $currtargets;
                   1432:     } else {
                   1433:         if ($rule_in_effect eq 'homeserver') {
                   1434:             my $homeserver = &homeserver($uname,$udom);
                   1435:             if ($homeserver ne 'no_host') {
                   1436:                 $offloadto = [$homeserver];
                   1437:             }
                   1438:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1439:             my %domconfig =
                   1440:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1441:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1442:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1443:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1444:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1445:                     }
                   1446:                 }
                   1447:             } else {
1.1172.2.7  raeburn  1448:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1449:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1450:                 if (&hostname($remotebalancer) ne '') {
                   1451:                     $offloadto = [$remotebalancer];
                   1452:                 }
                   1453:             }
                   1454:         } elsif (&hostname($rule_in_effect) ne '') {
                   1455:             $offloadto = [$rule_in_effect];
                   1456:         }
                   1457:     }
                   1458:     return $offloadto;
                   1459: }
                   1460: 
1.1127    raeburn  1461: sub internet_dom_servers {
                   1462:     my ($dom) = @_;
                   1463:     my (%uniqservers,%servers);
                   1464:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1465:     my @machinedoms = &machine_domains($primaryserver);
                   1466:     foreach my $mdom (@machinedoms) {
                   1467:         my %currservers = %servers;
                   1468:         my %server = &get_servers($mdom);
                   1469:         %servers = (%currservers,%server);
                   1470:     }
                   1471:     my %by_hostname;
                   1472:     foreach my $id (keys(%servers)) {
                   1473:         push(@{$by_hostname{$servers{$id}}},$id);
                   1474:     }
                   1475:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1476:         if (@{$by_hostname{$hostname}} > 1) {
                   1477:             my $match = 0;
                   1478:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1479:                 if (&host_domain($id) eq $dom) {
                   1480:                     $uniqservers{$id} = $hostname;
                   1481:                     $match = 1;
                   1482:                 }
                   1483:             }
                   1484:             unless ($match) {
                   1485:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1486:             }
                   1487:         } else {
                   1488:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1489:         }
                   1490:     }
                   1491:     return %uniqservers;
                   1492: }
                   1493: 
1.1       albertel 1494: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1495: 
1.599     albertel 1496: my %homecache;
1.1       albertel 1497: sub homeserver {
1.230     stredwic 1498:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1499:     my $index="$uname:$udom";
1.426     albertel 1500: 
1.599     albertel 1501:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1502: 
                   1503:     my %servers = &get_servers($udom,'library');
                   1504:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1505:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1506: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1507: 
                   1508: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1509: 	if ($answer eq 'found') {
                   1510: 	    delete($badServerCache{$tryserver}); 
                   1511: 	    return $homecache{$index}=$tryserver;
                   1512: 	} elsif ($answer eq 'no_host') {
                   1513: 	    $badServerCache{$tryserver}=1;
                   1514: 	}
1.1       albertel 1515:     }    
                   1516:     return 'no_host';
1.70      www      1517: }
                   1518: 
                   1519: # ------------------------------------- Find the usernames behind a list of IDs
                   1520: 
                   1521: sub idget {
                   1522:     my ($udom,@ids)=@_;
                   1523:     my %returnhash=();
                   1524:     
1.841     albertel 1525:     my %servers = &get_servers($udom,'library');
                   1526:     foreach my $tryserver (keys(%servers)) {
                   1527: 	my $idlist=join('&',@ids);
                   1528: 	$idlist=~tr/A-Z/a-z/; 
                   1529: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1530: 	my @answer=();
                   1531: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1532: 	    @answer=split(/\&/,$reply);
                   1533: 	}                    ;
                   1534: 	my $i;
                   1535: 	for ($i=0;$i<=$#ids;$i++) {
                   1536: 	    if ($answer[$i]) {
                   1537: 		$returnhash{$ids[$i]}=$answer[$i];
                   1538: 	    } 
                   1539: 	}
                   1540:     } 
1.70      www      1541:     return %returnhash;
                   1542: }
                   1543: 
                   1544: # ------------------------------------- Find the IDs behind a list of usernames
                   1545: 
                   1546: sub idrget {
                   1547:     my ($udom,@unames)=@_;
                   1548:     my %returnhash=();
1.800     albertel 1549:     foreach my $uname (@unames) {
                   1550:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1551:     }
1.70      www      1552:     return %returnhash;
                   1553: }
                   1554: 
                   1555: # ------------------------------- Store away a list of names and associated IDs
                   1556: 
                   1557: sub idput {
                   1558:     my ($udom,%ids)=@_;
                   1559:     my %servers=();
1.800     albertel 1560:     foreach my $uname (keys(%ids)) {
                   1561: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1562:         my $uhom=&homeserver($uname,$udom);
1.70      www      1563:         if ($uhom ne 'no_host') {
1.800     albertel 1564:             my $id=&escape($ids{$uname});
1.70      www      1565:             $id=~tr/A-Z/a-z/;
1.800     albertel 1566:             my $esc_unam=&escape($uname);
1.70      www      1567: 	    if ($servers{$uhom}) {
1.800     albertel 1568: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1569:             } else {
1.800     albertel 1570:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1571:             }
                   1572:         }
1.191     harris41 1573:     }
1.800     albertel 1574:     foreach my $server (keys(%servers)) {
                   1575:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1576:     }
1.344     www      1577: }
                   1578: 
1.1023    raeburn  1579: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1580: sub dump_dom {
1.1165    droeschl 1581:     my ($namespace, $udom, $regexp) = @_;
                   1582: 
                   1583:     $udom ||= $env{'user.domain'};
                   1584: 
                   1585:     return () unless $udom;
                   1586: 
                   1587:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1588: }
                   1589: 
1.1023    raeburn  1590: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1591: 
                   1592: sub get_dom {
1.860     raeburn  1593:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1594:     my $items='';
                   1595:     foreach my $item (@$storearr) {
                   1596:         $items.=&escape($item).'&';
                   1597:     }
                   1598:     $items=~s/\&$//;
1.860     raeburn  1599:     if (!$udom) {
                   1600:         $udom=$env{'user.domain'};
                   1601:         if (defined(&domain($udom,'primary'))) {
                   1602:             $uhome=&domain($udom,'primary');
                   1603:         } else {
1.874     albertel 1604:             undef($uhome);
1.860     raeburn  1605:         }
                   1606:     } else {
                   1607:         if (!$uhome) {
                   1608:             if (defined(&domain($udom,'primary'))) {
                   1609:                 $uhome=&domain($udom,'primary');
                   1610:             }
                   1611:         }
                   1612:     }
                   1613:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1614:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1615:         my %returnhash;
1.875     albertel 1616:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1617:             return %returnhash;
                   1618:         }
1.806     raeburn  1619:         my @pairs=split(/\&/,$rep);
                   1620:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1621:             return @pairs;
                   1622:         }
                   1623:         my $i=0;
                   1624:         foreach my $item (@$storearr) {
                   1625:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1626:             $i++;
                   1627:         }
                   1628:         return %returnhash;
                   1629:     } else {
1.880     banghart 1630:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1631:     }
                   1632: }
                   1633: 
                   1634: # -------------------------------------------- put items in domain db files 
                   1635: 
                   1636: sub put_dom {
1.860     raeburn  1637:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1638:     if (!$udom) {
                   1639:         $udom=$env{'user.domain'};
                   1640:         if (defined(&domain($udom,'primary'))) {
                   1641:             $uhome=&domain($udom,'primary');
                   1642:         } else {
1.874     albertel 1643:             undef($uhome);
1.860     raeburn  1644:         }
                   1645:     } else {
                   1646:         if (!$uhome) {
                   1647:             if (defined(&domain($udom,'primary'))) {
                   1648:                 $uhome=&domain($udom,'primary');
                   1649:             }
                   1650:         }
                   1651:     } 
                   1652:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1653:         my $items='';
                   1654:         foreach my $item (keys(%$storehash)) {
                   1655:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1656:         }
                   1657:         $items=~s/\&$//;
                   1658:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1659:     } else {
1.860     raeburn  1660:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1661:     }
                   1662: }
                   1663: 
1.1023    raeburn  1664: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1665: sub newput_dom {
1.1023    raeburn  1666:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1667:     my $result;
                   1668:     if (!$udom) {
                   1669:         $udom=$env{'user.domain'};
                   1670:     }
1.1023    raeburn  1671:     if ($udom) {
                   1672:         my $uname = &get_domainconfiguser($udom);
                   1673:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1674:     }
                   1675:     return $result;
                   1676: }
                   1677: 
1.1023    raeburn  1678: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1679: sub del_dom {
1.1023    raeburn  1680:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1681:     if (ref($storearr) eq 'ARRAY') {
                   1682:         if (!$udom) {
                   1683:             $udom=$env{'user.domain'};
                   1684:         }
1.1023    raeburn  1685:         if ($udom) {
                   1686:             my $uname = &get_domainconfiguser($udom); 
                   1687:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1688:         }
                   1689:     }
                   1690: }
                   1691: 
1.1023    raeburn  1692: # ----------------------------------construct domainconfig user for a domain 
                   1693: sub get_domainconfiguser {
                   1694:     my ($udom) = @_;
                   1695:     return $udom.'-domainconfig';
                   1696: }
                   1697: 
1.837     raeburn  1698: sub retrieve_inst_usertypes {
                   1699:     my ($udom) = @_;
                   1700:     my (%returnhash,@order);
1.989     raeburn  1701:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1702:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1703:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1704:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1705:         @order = @{$domdefs{'inststatusorder'}};
                   1706:     } else {
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             my $uhome=&domain($udom,'primary');
                   1709:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1710:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1711:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1712:                 return (\%returnhash,\@order);
                   1713:             }
                   1714:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1715:             my @pairs=split(/\&/,$hashitems);
                   1716:             foreach my $item (@pairs) {
                   1717:                 my ($key,$value)=split(/=/,$item,2);
                   1718:                 $key = &unescape($key);
                   1719:                 next if ($key =~ /^error: 2 /);
                   1720:                 $returnhash{$key}=&thaw_unescape($value);
                   1721:             }
                   1722:             my @esc_order = split(/\&/,$orderitems);
                   1723:             foreach my $item (@esc_order) {
                   1724:                 push(@order,&unescape($item));
                   1725:             }
                   1726:         } else {
                   1727:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1728:         }
                   1729:     }
                   1730:     return (\%returnhash,\@order);
                   1731: }
                   1732: 
1.868     raeburn  1733: sub is_domainimage {
                   1734:     my ($url) = @_;
                   1735:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1736:         if (&domain($1) ne '') {
                   1737:             return '1';
                   1738:         }
                   1739:     }
                   1740:     return;
                   1741: }
                   1742: 
1.899     raeburn  1743: sub inst_directory_query {
                   1744:     my ($srch) = @_;
                   1745:     my $udom = $srch->{'srchdomain'};
                   1746:     my %results;
                   1747:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1748:     my $outcome;
1.899     raeburn  1749:     if ($homeserver ne '') {
1.904     albertel 1750: 	my $queryid=&reply("querysend:instdirsearch:".
                   1751: 			   &escape($srch->{'srchby'}).':'.
                   1752: 			   &escape($srch->{'srchterm'}).':'.
                   1753: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1754: 	my $host=&hostname($homeserver);
                   1755: 	if ($queryid !~/^\Q$host\E\_/) {
                   1756: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1757: 	    return;
                   1758: 	}
                   1759: 	my $response = &get_query_reply($queryid);
                   1760: 	my $maxtries = 5;
                   1761: 	my $tries = 1;
                   1762: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1763: 	    $response = &get_query_reply($queryid);
                   1764: 	    $tries ++;
                   1765: 	}
                   1766: 
                   1767:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1768:             if ($response eq 'unavailable') {
                   1769:                 $outcome = $response;
                   1770:             } else {
                   1771:                 $outcome = 'ok';
                   1772:                 my @matches = split(/\n/,$response);
                   1773:                 foreach my $match (@matches) {
                   1774:                     my ($key,$value) = split(/=/,$match);
                   1775:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1776:                 }
1.899     raeburn  1777:             }
                   1778:         }
                   1779:     }
1.909     raeburn  1780:     return ($outcome,%results);
1.899     raeburn  1781: }
                   1782: 
                   1783: sub usersearch {
                   1784:     my ($srch) = @_;
                   1785:     my $dom = $srch->{'srchdomain'};
                   1786:     my %results;
                   1787:     my %libserv = &all_library();
                   1788:     my $query = 'usersearch';
                   1789:     foreach my $tryserver (keys(%libserv)) {
                   1790:         if (&host_domain($tryserver) eq $dom) {
                   1791:             my $host=&hostname($tryserver);
                   1792:             my $queryid=
1.911     raeburn  1793:                 &reply("querysend:".&escape($query).':'.
                   1794:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1795:                        &escape($srch->{'srchtype'}).':'.
                   1796:                        &escape($srch->{'srchterm'}),$tryserver);
                   1797:             if ($queryid !~/^\Q$host\E\_/) {
                   1798:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1799:                 next;
1.899     raeburn  1800:             }
                   1801:             my $reply = &get_query_reply($queryid);
                   1802:             my $maxtries = 1;
                   1803:             my $tries = 1;
                   1804:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1805:                 $reply = &get_query_reply($queryid);
                   1806:                 $tries ++;
                   1807:             }
                   1808:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1809:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1810:             } else {
1.911     raeburn  1811:                 my @matches;
                   1812:                 if ($reply =~ /\n/) {
                   1813:                     @matches = split(/\n/,$reply);
                   1814:                 } else {
                   1815:                     @matches = split(/\&/,$reply);
                   1816:                 }
1.899     raeburn  1817:                 foreach my $match (@matches) {
                   1818:                     my ($uname,$udom,%userhash);
1.911     raeburn  1819:                     foreach my $entry (split(/:/,$match)) {
                   1820:                         my ($key,$value) =
                   1821:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1822:                         $userhash{$key} = $value;
                   1823:                         if ($key eq 'username') {
                   1824:                             $uname = $value;
                   1825:                         } elsif ($key eq 'domain') {
                   1826:                             $udom = $value;
1.911     raeburn  1827:                         }
1.899     raeburn  1828:                     }
                   1829:                     $results{$uname.':'.$udom} = \%userhash;
                   1830:                 }
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     return %results;
                   1835: }
                   1836: 
1.912     raeburn  1837: sub get_instuser {
                   1838:     my ($udom,$uname,$id) = @_;
                   1839:     my $homeserver = &domain($udom,'primary');
                   1840:     my ($outcome,%results);
                   1841:     if ($homeserver ne '') {
                   1842:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1843:                            &escape($id).':'.&escape($udom),$homeserver);
                   1844:         my $host=&hostname($homeserver);
                   1845:         if ($queryid !~/^\Q$host\E\_/) {
                   1846:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1847:             return;
                   1848:         }
                   1849:         my $response = &get_query_reply($queryid);
                   1850:         my $maxtries = 5;
                   1851:         my $tries = 1;
                   1852:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1853:             $response = &get_query_reply($queryid);
                   1854:             $tries ++;
                   1855:         }
                   1856:         if (!&error($response) && $response ne 'refused') {
                   1857:             if ($response eq 'unavailable') {
                   1858:                 $outcome = $response;
                   1859:             } else {
                   1860:                 $outcome = 'ok';
                   1861:                 my @matches = split(/\n/,$response);
                   1862:                 foreach my $match (@matches) {
                   1863:                     my ($key,$value) = split(/=/,$match);
                   1864:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869:     my %userinfo;
                   1870:     if (ref($results{$uname}) eq 'HASH') {
                   1871:         %userinfo = %{$results{$uname}};
                   1872:     } 
                   1873:     return ($outcome,%userinfo);
                   1874: }
                   1875: 
                   1876: sub inst_rulecheck {
1.923     raeburn  1877:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1878:     my %returnhash;
                   1879:     if ($udom ne '') {
                   1880:         if (ref($rules) eq 'ARRAY') {
                   1881:             @{$rules} = map {&escape($_);} (@{$rules});
                   1882:             my $rulestr = join(':',@{$rules});
                   1883:             my $homeserver=&domain($udom,'primary');
                   1884:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1885:                 my $response;
                   1886:                 if ($item eq 'username') {                
                   1887:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1888:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1889:                                               $homeserver));
1.923     raeburn  1890:                 } elsif ($item eq 'id') {
                   1891:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1892:                                               ':'.&escape($id).':'.$rulestr,
                   1893:                                               $homeserver));
1.945     raeburn  1894:                 } elsif ($item eq 'selfcreate') {
                   1895:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1896:                                                &escape($udom).':'.&escape($uname).
                   1897:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1898:                 }
1.912     raeburn  1899:                 if ($response ne 'refused') {
                   1900:                     my @pairs=split(/\&/,$response);
                   1901:                     foreach my $item (@pairs) {
                   1902:                         my ($key,$value)=split(/=/,$item,2);
                   1903:                         $key = &unescape($key);
                   1904:                         next if ($key =~ /^error: 2 /);
                   1905:                         $returnhash{$key}=&thaw_unescape($value);
                   1906:                     }
                   1907:                 }
                   1908:             }
                   1909:         }
                   1910:     }
                   1911:     return %returnhash;
                   1912: }
                   1913: 
                   1914: sub inst_userrules {
1.923     raeburn  1915:     my ($udom,$check) = @_;
1.912     raeburn  1916:     my (%ruleshash,@ruleorder);
                   1917:     if ($udom ne '') {
                   1918:         my $homeserver=&domain($udom,'primary');
                   1919:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1920:             my $response;
                   1921:             if ($check eq 'id') {
                   1922:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1923:                                  $homeserver);
1.943     raeburn  1924:             } elsif ($check eq 'email') {
                   1925:                 $response=&reply('instemailrules:'.&escape($udom),
                   1926:                                  $homeserver);
1.923     raeburn  1927:             } else {
                   1928:                 $response=&reply('instuserrules:'.&escape($udom),
                   1929:                                  $homeserver);
                   1930:             }
1.912     raeburn  1931:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1932:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1933:                 ($response ne 'no_such_host')) {
                   1934:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1935:                 my @pairs=split(/\&/,$hashitems);
                   1936:                 foreach my $item (@pairs) {
                   1937:                     my ($key,$value)=split(/=/,$item,2);
                   1938:                     $key = &unescape($key);
                   1939:                     next if ($key =~ /^error: 2 /);
                   1940:                     $ruleshash{$key}=&thaw_unescape($value);
                   1941:                 }
                   1942:                 my @esc_order = split(/\&/,$orderitems);
                   1943:                 foreach my $item (@esc_order) {
                   1944:                     push(@ruleorder,&unescape($item));
                   1945:                 }
                   1946:             }
                   1947:         }
                   1948:     }
                   1949:     return (\%ruleshash,\@ruleorder);
                   1950: }
                   1951: 
1.976     raeburn  1952: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1953: 
                   1954: sub get_domain_defaults {
                   1955:     my ($domain) = @_;
                   1956:     my $cachetime = 60*60*24;
                   1957:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1958:     if (defined($cached)) {
                   1959:         if (ref($result) eq 'HASH') {
                   1960:             return %{$result};
                   1961:         }
                   1962:     }
                   1963:     my %domdefaults;
                   1964:     my %domconfig =
1.989     raeburn  1965:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1966:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1967:                                   'coursedefaults','usersessions',
                   1968:                                   'requestauthor'],$domain);
1.943     raeburn  1969:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1970:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1971:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1972:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1973:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1974:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1975:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1976:     } else {
                   1977:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1978:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1979:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1980:     }
1.976     raeburn  1981:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1982:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1983:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1984:         } else {
                   1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1986:         } 
1.1172.2.6  raeburn  1987:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1988:         foreach my $item (@usertools) {
                   1989:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1990:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1991:             }
                   1992:         }
                   1993:     }
1.985     raeburn  1994:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1995:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1996:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1997:         }
                   1998:     }
1.1172.2.9  raeburn  1999:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2000:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2001:     }
1.989     raeburn  2002:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2003:         foreach my $item ('inststatustypes','inststatusorder') {
                   2004:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2005:         }
                   2006:     }
1.1047    raeburn  2007:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2008:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2009:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2010:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2011:         }
                   2012:     }
1.1073    raeburn  2013:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2014:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2015:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2016:         }
                   2017:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2018:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2019:         }
                   2020:     }
1.1172.2.23  raeburn  2021:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2022:     return %domdefaults;
                   2023: }
                   2024: 
1.344     www      2025: # --------------------------------------------------- Assign a key to a student
                   2026: 
                   2027: sub assign_access_key {
1.364     www      2028: #
                   2029: # a valid key looks like uname:udom#comments
                   2030: # comments are being appended
                   2031: #
1.498     www      2032:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2033:     $kdom=
1.620     albertel 2034:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2035:     $knum=
1.620     albertel 2036:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2037:     $cdom=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2039:     $cnum=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2041:     $udom=$env{'user.name'} unless (defined($udom));
                   2042:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2043:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2044:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2045:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2046:                                                   # assigned to this person
                   2047:                                                   # - this should not happen,
1.345     www      2048:                                                   # unless something went wrong
                   2049:                                                   # the first time around
                   2050: # ready to assign
1.364     www      2051:         $logentry=$1.'; '.$logentry;
1.496     www      2052:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2053:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2054: # key now belongs to user
1.346     www      2055: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2056:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2057:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2058:                 return 'ok';
                   2059:             } else {
                   2060:                 return 
                   2061:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2062: 	    }
                   2063:         } else {
                   2064:             return 'error: Could not assign key, try again later.';
                   2065:         }
1.364     www      2066:     } elsif (!$existing{$ckey}) {
1.345     www      2067: # the key does not exist
                   2068: 	return 'error: The key does not exist';
                   2069:     } else {
                   2070: # the key is somebody else's
                   2071: 	return 'error: The key is already in use';
                   2072:     }
1.344     www      2073: }
                   2074: 
1.364     www      2075: # ------------------------------------------ put an additional comment on a key
                   2076: 
                   2077: sub comment_access_key {
                   2078: #
                   2079: # a valid key looks like uname:udom#comments
                   2080: # comments are being appended
                   2081: #
                   2082:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2083:     $cdom=
1.620     albertel 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2085:     $cnum=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2087:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2088:     if ($existing{$ckey}) {
                   2089:         $existing{$ckey}.='; '.$logentry;
                   2090: # ready to assign
1.367     www      2091:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2092:                                                  $cdom,$cnum) eq 'ok') {
                   2093: 	    return 'ok';
                   2094:         } else {
                   2095: 	    return 'error: Count not store comment.';
                   2096:         }
                   2097:     } else {
                   2098: # the key does not exist
                   2099: 	return 'error: The key does not exist';
                   2100:     }
                   2101: }
                   2102: 
1.344     www      2103: # ------------------------------------------------------ Generate a set of keys
                   2104: 
                   2105: sub generate_access_keys {
1.364     www      2106:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2107:     $cdom=
1.620     albertel 2108:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2109:     $cnum=
1.620     albertel 2110:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2111:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2112:     unless (($cdom) && ($cnum)) { return 0; }
                   2113:     if ($number>10000) { return 0; }
                   2114:     sleep(2); # make sure don't get same seed twice
                   2115:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2116:     my $total=0;
                   2117:     for (my $i=1;$i<=$number;$i++) {
                   2118:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2119:                   sprintf("%lx",int(100000*rand)).'-'.
                   2120:                   sprintf("%lx",int(100000*rand));
                   2121:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2122:        $newkey=~s/0/h/g; # and also 0 and O
                   2123:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2124:        if ($existing{$newkey}) {
                   2125:            $i--;
                   2126:        } else {
1.364     www      2127: 	  if (&put('accesskeys',
                   2128:               { $newkey => '# generated '.localtime().
1.620     albertel 2129:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2130:                            '; '.$logentry },
                   2131: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2132:               $total++;
                   2133: 	  }
                   2134:        }
                   2135:     }
1.620     albertel 2136:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2137:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2138:     return $total;
                   2139: }
                   2140: 
                   2141: # ------------------------------------------------------- Validate an accesskey
                   2142: 
                   2143: sub validate_access_key {
                   2144:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2145:     $cdom=
1.620     albertel 2146:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2147:     $cnum=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2149:     $udom=$env{'user.domain'} unless (defined($udom));
                   2150:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2151:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2152:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2153: }
                   2154: 
                   2155: # ------------------------------------- Find the section of student in a course
1.652     albertel 2156: sub devalidate_getsection_cache {
                   2157:     my ($udom,$unam,$courseid)=@_;
                   2158:     my $hashid="$udom:$unam:$courseid";
                   2159:     &devalidate_cache_new('getsection',$hashid);
                   2160: }
1.298     matthew  2161: 
1.815     albertel 2162: sub courseid_to_courseurl {
                   2163:     my ($courseid) = @_;
                   2164:     #already url style courseid
                   2165:     return $courseid if ($courseid =~ m{^/});
                   2166: 
                   2167:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2168: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2169: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2170: 	return "/$cdom/$cnum";
                   2171:     }
                   2172: 
                   2173:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2174:     if (exists($courseinfo{'num'})) {
                   2175: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2176:     }
                   2177: 
                   2178:     return undef;
                   2179: }
                   2180: 
1.298     matthew  2181: sub getsection {
                   2182:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2183:     my $cachetime=1800;
1.551     albertel 2184: 
                   2185:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2186:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2187:     if (defined($cached)) { return $result; }
                   2188: 
1.298     matthew  2189:     my %Pending; 
                   2190:     my %Expired;
                   2191:     #
                   2192:     # Each role can either have not started yet (pending), be active, 
                   2193:     #    or have expired.
                   2194:     #
                   2195:     # If there is an active role, we are done.
                   2196:     #
                   2197:     # If there is more than one role which has not started yet, 
                   2198:     #     choose the one which will start sooner
                   2199:     # If there is one role which has not started yet, return it.
                   2200:     #
                   2201:     # If there is more than one expired role, choose the one which ended last.
                   2202:     # If there is a role which has expired, return it.
                   2203:     #
1.815     albertel 2204:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2205:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2206:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2207:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2208:         my $section=$1;
                   2209:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2210:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2211:         my $now=time;
1.548     albertel 2212:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2213:             $Expired{$end}=$section;
                   2214:             next;
                   2215:         }
1.548     albertel 2216:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2217:             $Pending{$start}=$section;
                   2218:             next;
                   2219:         }
1.599     albertel 2220:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2221:     }
                   2222:     #
                   2223:     # Presumedly there will be few matching roles from the above
                   2224:     # loop and the sorting time will be negligible.
                   2225:     if (scalar(keys(%Pending))) {
                   2226:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2228:     } 
                   2229:     if (scalar(keys(%Expired))) {
                   2230:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2231:         my $time = pop(@sorted);
1.599     albertel 2232:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2233:     }
1.599     albertel 2234:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2235: }
1.70      www      2236: 
1.599     albertel 2237: sub save_cache {
                   2238:     &purge_remembered();
1.722     albertel 2239:     #&Apache::loncommon::validate_page();
1.620     albertel 2240:     undef(%env);
1.780     albertel 2241:     undef($env_loaded);
1.599     albertel 2242: }
1.452     albertel 2243: 
1.599     albertel 2244: my $to_remember=-1;
                   2245: my %remembered;
                   2246: my %accessed;
                   2247: my $kicks=0;
                   2248: my $hits=0;
1.849     albertel 2249: sub make_key {
                   2250:     my ($name,$id) = @_;
1.872     albertel 2251:     if (length($id) > 65 
                   2252: 	&& length(&escape($id)) > 200) {
                   2253: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2254:     }
1.849     albertel 2255:     return &escape($name.':'.$id);
                   2256: }
                   2257: 
1.599     albertel 2258: sub devalidate_cache_new {
                   2259:     my ($name,$id,$debug) = @_;
                   2260:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2261:     $id=&make_key($name,$id);
1.599     albertel 2262:     $memcache->delete($id);
                   2263:     delete($remembered{$id});
                   2264:     delete($accessed{$id});
                   2265: }
                   2266: 
                   2267: sub is_cached_new {
                   2268:     my ($name,$id,$debug) = @_;
1.849     albertel 2269:     $id=&make_key($name,$id);
1.599     albertel 2270:     if (exists($remembered{$id})) {
1.1133    foxr     2271: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2272: 	$accessed{$id}=[&gettimeofday()];
                   2273: 	$hits++;
                   2274: 	return ($remembered{$id},1);
                   2275:     }
                   2276:     my $value = $memcache->get($id);
                   2277:     if (!(defined($value))) {
                   2278: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2279: 	return (undef,undef);
1.416     albertel 2280:     }
1.599     albertel 2281:     if ($value eq '__undef__') {
                   2282: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2283: 	$value=undef;
                   2284:     }
                   2285:     &make_room($id,$value,$debug);
                   2286:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2287:     return ($value,1);
                   2288: }
                   2289: 
                   2290: sub do_cache_new {
                   2291:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2292:     $id=&make_key($name,$id);
1.599     albertel 2293:     my $setvalue=$value;
                   2294:     if (!defined($setvalue)) {
                   2295: 	$setvalue='__undef__';
                   2296:     }
1.623     albertel 2297:     if (!defined($time) ) {
                   2298: 	$time=600;
                   2299:     }
1.599     albertel 2300:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2301:     my $result = $memcache->set($id,$setvalue,$time);
                   2302:     if (! $result) {
1.872     albertel 2303: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2304: 	$memcache->disconnect_all();
1.872     albertel 2305:     }
1.600     albertel 2306:     # need to make a copy of $value
1.919     albertel 2307:     &make_room($id,$value,$debug);
1.599     albertel 2308:     return $value;
                   2309: }
                   2310: 
                   2311: sub make_room {
                   2312:     my ($id,$value,$debug)=@_;
1.919     albertel 2313: 
                   2314:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2315:                                     : $value;
1.599     albertel 2316:     if ($to_remember<0) { return; }
                   2317:     $accessed{$id}=[&gettimeofday()];
                   2318:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2319:     my $to_kick;
                   2320:     my $max_time=0;
                   2321:     foreach my $other (keys(%accessed)) {
                   2322: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2323: 	    $to_kick=$other;
                   2324: 	    $max_time=&tv_interval($accessed{$other});
                   2325: 	}
                   2326:     }
                   2327:     delete($remembered{$to_kick});
                   2328:     delete($accessed{$to_kick});
                   2329:     $kicks++;
                   2330:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2331:     return;
                   2332: }
                   2333: 
1.599     albertel 2334: sub purge_remembered {
1.604     albertel 2335:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2336:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2337:     undef(%remembered);
                   2338:     undef(%accessed);
1.428     albertel 2339: }
1.70      www      2340: # ------------------------------------- Read an entry from a user's environment
                   2341: 
                   2342: sub userenvironment {
                   2343:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2344:     my $items;
                   2345:     foreach my $item (@what) {
                   2346:         $items.=&escape($item).'&';
                   2347:     }
                   2348:     $items=~s/\&$//;
1.70      www      2349:     my %returnhash=();
1.1009    raeburn  2350:     my $uhome = &homeserver($unam,$udom);
                   2351:     unless ($uhome eq 'no_host') {
                   2352:         my @answer=split(/\&/, 
                   2353:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2354:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2355:             return %returnhash;
                   2356:         }
1.1009    raeburn  2357:         my $i;
                   2358:         for ($i=0;$i<=$#what;$i++) {
                   2359: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2360:         }
1.70      www      2361:     }
                   2362:     return %returnhash;
1.1       albertel 2363: }
                   2364: 
1.617     albertel 2365: # ---------------------------------------------------------- Get a studentphoto
                   2366: sub studentphoto {
                   2367:     my ($udom,$unam,$ext) = @_;
                   2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2369:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2370:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2371:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2372:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2373:             } else {
                   2374:                 my ($result,$perm_reqd)=
1.707     albertel 2375: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2376:                 if ($result eq 'ok') {
                   2377:                     if (!($perm_reqd eq 'yes')) {
                   2378:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2379:                     }
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:     } else {
                   2384:         my ($result,$perm_reqd) = 
1.707     albertel 2385: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2386:         if ($result eq 'ok') {
                   2387:             if (!($perm_reqd eq 'yes')) {
                   2388:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2389:             }
                   2390:         }
                   2391:     }
                   2392:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2393: }
                   2394: 
                   2395: sub retrievestudentphoto {
                   2396:     my ($udom,$unam,$ext,$type) = @_;
                   2397:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2398:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2399:     if ($ret eq 'ok') {
                   2400:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2401:         if ($type eq 'thumbnail') {
                   2402:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2403:         }
                   2404:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2405:         return $tokenurl;
                   2406:     } else {
                   2407:         if ($type eq 'thumbnail') {
                   2408:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2409:         } else { 
                   2410:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2411:         }
1.617     albertel 2412:     }
                   2413: }
                   2414: 
1.263     www      2415: # -------------------------------------------------------------------- New chat
                   2416: 
                   2417: sub chatsend {
1.724     raeburn  2418:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2419:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2421:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2422:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2423: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2424: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2425: }
                   2426: 
                   2427: # ------------------------------------------ Find current version of a resource
                   2428: 
                   2429: sub getversion {
                   2430:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2431:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2432:     return &currentversion(&filelocation('',$fname));
                   2433: }
                   2434: 
                   2435: sub currentversion {
                   2436:     my $fname=shift;
                   2437:     my $author=$fname;
                   2438:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2439:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2440:     my $home=&homeserver($uname,$udom);
1.292     www      2441:     if ($home eq 'no_host') { 
                   2442:         return -1; 
                   2443:     }
1.1112    www      2444:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2445:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2446: 	return -1;
                   2447:     }
1.1112    www      2448:     return $answer;
1.263     www      2449: }
                   2450: 
1.1111    www      2451: #
                   2452: # Return special version number of resource if set by override, empty otherwise
                   2453: #
                   2454: sub usedversion {
                   2455:     my $fname=shift;
                   2456:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2457:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2458:     if ($urlversion) { return $urlversion; }
                   2459:     return '';
                   2460: }
                   2461: 
1.1       albertel 2462: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2463: 
1.1       albertel 2464: sub subscribe {
                   2465:     my $fname=shift;
1.761     raeburn  2466:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2467:     $fname=~s/[\n\r]//g;
1.1       albertel 2468:     my $author=$fname;
                   2469:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2470:     my ($udom,$uname)=split(/\//,$author);
                   2471:     my $home=homeserver($uname,$udom);
1.335     albertel 2472:     if ($home eq 'no_host') {
                   2473:         return 'not_found';
1.1       albertel 2474:     }
                   2475:     my $answer=reply("sub:$fname",$home);
1.64      www      2476:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2477: 	$answer.=' by '.$home;
                   2478:     }
1.1       albertel 2479:     return $answer;
                   2480: }
                   2481:     
1.8       www      2482: # -------------------------------------------------------------- Replicate file
                   2483: 
                   2484: sub repcopy {
                   2485:     my $filename=shift;
1.23      www      2486:     $filename=~s/\/+/\//g;
1.1142    raeburn  2487:     my $londocroot = $perlvar{'lonDocRoot'};
                   2488:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2489:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2490:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2491: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2492: 	return &repcopy_userfile($filename);
                   2493:     }
1.532     albertel 2494:     $filename=~s/[\n\r]//g;
1.8       www      2495:     my $transname="$filename.in.transfer";
1.828     www      2496: # FIXME: this should flock
1.607     raeburn  2497:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2498:     my $remoteurl=subscribe($filename);
1.64      www      2499:     if ($remoteurl =~ /^con_lost by/) {
                   2500: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2501:            return 'unavailable';
1.8       www      2502:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2503: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2504: 	   return 'not_found';
1.64      www      2505:     } elsif ($remoteurl =~ /^rejected by/) {
                   2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2507:            return 'forbidden';
1.20      www      2508:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2509:            return 'ok';
1.8       www      2510:     } else {
1.290     www      2511:         my $author=$filename;
                   2512:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:         my ($udom,$uname)=split(/\//,$author);
                   2514:         my $home=homeserver($uname,$udom);
                   2515:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2516:            my @parts=split(/\//,$filename);
                   2517:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2518:            if ($path ne "$londocroot/res") {
1.8       www      2519:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2520: 	       return 'bad_request';
1.8       www      2521:            }
                   2522:            my $count;
                   2523:            for ($count=5;$count<$#parts;$count++) {
                   2524:                $path.="/$parts[$count]";
                   2525:                if ((-e $path)!=1) {
                   2526: 		   mkdir($path,0777);
                   2527:                }
                   2528:            }
                   2529:            my $ua=new LWP::UserAgent;
                   2530:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2531:            my $response=$ua->request($request,$transname);
                   2532:            if ($response->is_error()) {
                   2533: 	       unlink($transname);
                   2534:                my $message=$response->status_line;
1.672     albertel 2535:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2536:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2537:                return 'unavailable';
1.8       www      2538:            } else {
1.16      www      2539: 	       if ($remoteurl!~/\.meta$/) {
                   2540:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2541:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2542:                   if ($mresponse->is_error()) {
                   2543: 		      unlink($filename.'.meta');
                   2544:                       &logthis(
1.672     albertel 2545:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2546:                   }
                   2547: 	       }
1.8       www      2548:                rename($transname,$filename);
1.607     raeburn  2549:                return 'ok';
1.8       www      2550:            }
1.290     www      2551:        }
1.8       www      2552:     }
1.330     www      2553: }
                   2554: 
                   2555: # ------------------------------------------------ Get server side include body
                   2556: sub ssi_body {
1.381     albertel 2557:     my ($filelink,%form)=@_;
1.606     matthew  2558:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2559:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2560:     }
1.953     www      2561:     my $output='';
                   2562:     my $response;
1.980     raeburn  2563:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2564:        ($output,$response)=&externalssi($filelink);
1.953     www      2565:     } else {
1.1004    droeschl 2566:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2567:        $filelink .= 'inhibitmenu=yes';
1.953     www      2568:        ($output,$response)=&ssi($filelink,%form);
                   2569:     }
1.778     albertel 2570:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2571:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2572:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2573:     if (wantarray) {
                   2574:         return ($output, $response);
                   2575:     } else {
                   2576:         return $output;
                   2577:     }
1.8       www      2578: }
                   2579: 
1.15      www      2580: # --------------------------------------------------------- Server Side Include
                   2581: 
1.782     albertel 2582: sub absolute_url {
                   2583:     my ($host_name) = @_;
                   2584:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2585:     if ($host_name eq '') {
                   2586: 	$host_name = $ENV{'SERVER_NAME'};
                   2587:     }
                   2588:     return $protocol.$host_name;
                   2589: }
                   2590: 
1.942     foxr     2591: #
                   2592: #   Server side include.
                   2593: # Parameters:
                   2594: #  fn     Possibly encrypted resource name/id.
                   2595: #  form   Hash that describes how the rendering should be done
                   2596: #         and other things.
1.944     foxr     2597: # Returns:
1.950     raeburn  2598: #   Scalar context: The content of the response.
                   2599: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2600: #     
1.15      www      2601: sub ssi {
                   2602: 
1.944     foxr     2603:     my ($fn,%form)=@_;
1.15      www      2604:     my $ua=new LWP::UserAgent;
1.23      www      2605:     my $request;
1.711     albertel 2606: 
                   2607:     $form{'no_update_last_known'}=1;
1.895     albertel 2608:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2609:     if (%form) {
1.782     albertel 2610:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2611:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2612:     } else {
1.782     albertel 2613:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2614:     }
                   2615: 
1.15      www      2616:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2617:     my $response= $ua->request($request);
1.944     foxr     2618:     if (wantarray) {
1.1172.2.3  raeburn  2619: 	return ($response->content, $response);
1.944     foxr     2620:     } else {
1.1172.2.3  raeburn  2621: 	return $response->content;
1.942     foxr     2622:     }
1.324     www      2623: }
                   2624: 
                   2625: sub externalssi {
                   2626:     my ($url)=@_;
                   2627:     my $ua=new LWP::UserAgent;
                   2628:     my $request=new HTTP::Request('GET',$url);
                   2629:     my $response=$ua->request($request);
1.954     raeburn  2630:     if (wantarray) {
                   2631:         return ($response->content, $response);
                   2632:     } else {
                   2633:         return $response->content;
                   2634:     }
1.15      www      2635: }
1.254     www      2636: 
1.492     albertel 2637: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2638: 
                   2639: sub allowuploaded {
                   2640:     my ($srcurl,$url)=@_;
                   2641:     $url=&clutter(&declutter($url));
                   2642:     my $dir=$url;
                   2643:     $dir=~s/\/[^\/]+$//;
                   2644:     my %httpref=();
                   2645:     my $httpurl=&hreflocation('',$url);
                   2646:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2647:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2648: }
1.477     raeburn  2649: 
1.1172.2.13  raeburn  2650: #
                   2651: # Determine if the current user should be able to edit a particular resource,
                   2652: # when viewing in course context.
                   2653: # (a) When viewing resource used to determine if "Edit" item is included in
                   2654: #     Functions.
                   2655: # (b) When displaying folder contents in course editor, used to determine if
                   2656: #     "Edit" link will be displayed alongside resource.
                   2657: #
                   2658: #  input: six args -- filename (decluttered), course number, course domain,
                   2659: #                   url, symb (if registered) and group (if this is a group
                   2660: #                   item -- e.g., bulletin board, group page etc.).
                   2661: #  output: array of five scalars --
                   2662: #          $cfile -- url for file editing if editable on current server
                   2663: #          $home -- homeserver of resource (i.e., for author if published,
                   2664: #                                           or course if uploaded.).
                   2665: #          $switchserver --  1 if server switch will be needed.
                   2666: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2667: #          $forceview -- 1 if icon/link should be to go to view mode
                   2668: #
                   2669: 
                   2670: sub can_edit_resource {
                   2671:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2672:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2673: #
                   2674: # For aboutme pages user can only edit his/her own.
                   2675: #
                   2676:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2677:         my ($sdom,$sname) = ($1,$2);
                   2678:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2679:             $home = $env{'user.home'};
                   2680:             $cfile = $resurl;
                   2681:             if ($env{'form.forceedit'}) {
                   2682:                 $forceview = 1;
                   2683:             } else {
                   2684:                 $forceedit = 1;
                   2685:             }
                   2686:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2687:         } else {
                   2688:             return;
                   2689:         }
                   2690:     }
                   2691: 
                   2692:     if ($env{'request.course.id'}) {
                   2693:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2694:         if ($group ne '') {
                   2695: # if this is a group homepage or group bulletin board, check group privs
                   2696:             my $allowed = 0;
                   2697:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2698:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2699:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2700:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2701:                     $allowed = 1;
                   2702:                 }
                   2703:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2704:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2705:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2706:                     $allowed = 1;
                   2707:                 }
                   2708:             }
                   2709:             if ($allowed) {
                   2710:                 $home=&homeserver($cnum,$cdom);
                   2711:                 if ($env{'form.forceedit'}) {
                   2712:                     $forceview = 1;
                   2713:                 } else {
                   2714:                     $forceedit = 1;
                   2715:                 }
                   2716:                 $cfile = $resurl;
                   2717:             } else {
                   2718:                 return;
                   2719:             }
                   2720:         } else {
1.1172.2.15  raeburn  2721:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2722:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2723:                     return;
                   2724:                 }
                   2725:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2726: #
                   2727: # No edit allowed where CC has switched to student role.
                   2728: #
                   2729:                 return;
                   2730:             }
                   2731:         }
                   2732:     }
                   2733: 
                   2734:     if ($file ne '') {
                   2735:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2736:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2737:                 $uploaded = 1;
                   2738:                 $incourse = 1;
                   2739:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2740:                     $cfile = &hreflocation('',$file);
                   2741:                     if ($env{'form.forceedit'}) {
                   2742:                         $forceview = 1;
                   2743:                     } else {
                   2744:                         $forceedit = 1;
                   2745:                     }
                   2746:                 }
                   2747:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2748:                 $incourse = 1;
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2756:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2757:                     $incourse = 1;
                   2758:                     if ($env{'form.forceedit'}) {
                   2759:                         $forceview = 1;
                   2760:                     } else {
                   2761:                         $forceedit = 1;
                   2762:                     }
                   2763:                     $cfile = $resurl;
                   2764:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2765:                     $incourse = 1;
                   2766:                     $cfile = $resurl.'/smpedit';
                   2767:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2768:                     $incourse = 1;
                   2769:                     if ($env{'form.forceedit'}) {
                   2770:                         $forceview = 1;
                   2771:                     } else {
                   2772:                         $forceedit = 1;
                   2773:                     }
                   2774:                     $cfile = $resurl;
1.1172.2.15  raeburn  2775:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2776:                     $incourse = 1;
                   2777:                     if ($env{'form.forceedit'}) {
                   2778:                         $forceview = 1;
                   2779:                     } else {
                   2780:                         $forceedit = 1;
                   2781:                     }
                   2782:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2783:                 }
                   2784:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2785:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2786:                 if (&is_on_map($template)) {
                   2787:                     $incourse = 1;
                   2788:                     $forceview = 1;
                   2789:                     $cfile = $template;
                   2790:                 }
                   2791:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2792:                     $incourse = 1;
                   2793:                     if ($env{'form.forceedit'}) {
                   2794:                         $forceview = 1;
                   2795:                     } else {
                   2796:                         $forceedit = 1;
                   2797:                     }
                   2798:                     $cfile = $resurl;
                   2799:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2800:                 $incourse = 1;
                   2801:                 $forceview = 1;
                   2802:                 if ($symb) {
                   2803:                     my ($map,$id,$res)=&decode_symb($symb);
                   2804:                     $env{'request.symb'} = $symb;
                   2805:                     $cfile = &clutter($res);
                   2806:                 } else {
                   2807:                     $cfile = $env{'form.suppurl'};
                   2808:                     $cfile =~ s{^http://}{};
                   2809:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2810:                 }
                   2811:             }
                   2812:         }
                   2813:         if ($uploaded || $incourse) {
                   2814:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2815:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2816:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2817:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2818:             # Check that the user has permission to edit this resource
                   2819:             my $setpriv = 1;
                   2820:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2821:             if (defined($cfudom)) {
                   2822:                 $home=&homeserver($cfuname,$cfudom);
                   2823:                 $cfile=$file;
                   2824:             }
                   2825:         }
                   2826:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2827:             (($home ne '') && ($home ne 'no_host'))) {
                   2828:             my @ids=&current_machine_ids();
                   2829:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2830:                 $switchserver=1;
                   2831:             }
                   2832:         }
                   2833:     }
                   2834:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2835: }
                   2836: 
                   2837: sub is_course_upload {
                   2838:     my ($file,$cnum,$cdom) = @_;
                   2839:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2840:     $uploadpath =~ s{^\/}{};
                   2841:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2842:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2843:         return 1;
                   2844:     }
                   2845:     return;
                   2846: }
                   2847: 
                   2848: sub in_course {
                   2849:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2850:     if ($hideprivileged) {
                   2851:         my $skipuser;
1.1172.2.23  raeburn  2852:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2853:         my @possdoms = ($cdom);
                   2854:         if ($coursehash{'checkforpriv'}) {
                   2855:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2856:         }
                   2857:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2858:             $skipuser = 1;
                   2859:             if ($coursehash{'nothideprivileged'}) {
                   2860:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2861:                     my $user;
                   2862:                     if ($item =~ /:/) {
                   2863:                         $user = $item;
                   2864:                     } else {
                   2865:                         $user = join(':',split(/[\@]/,$item));
                   2866:                     }
                   2867:                     if ($user eq $uname.':'.$udom) {
                   2868:                         undef($skipuser);
                   2869:                         last;
                   2870:                     }
                   2871:                 }
                   2872:             }
                   2873:             if ($skipuser) {
                   2874:                 return 0;
                   2875:             }
                   2876:         }
                   2877:     }
                   2878:     $type ||= 'any';
                   2879:     if (!defined($cdom) || !defined($cnum)) {
                   2880:         my $cid  = $env{'request.course.id'};
                   2881:         $cdom = $env{'course.'.$cid.'.domain'};
                   2882:         $cnum = $env{'course.'.$cid.'.num'};
                   2883:     }
                   2884:     my $typesref;
                   2885:     if (($type eq 'any') || ($type eq 'all')) {
                   2886:         $typesref = ['active','previous','future'];
                   2887:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2888:         $typesref = [$type];
                   2889:     }
                   2890:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2891:                               $typesref,undef,[$cdom]);
                   2892:     my ($tmp) = keys(%roles);
                   2893:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2894:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2895:     if (@course_roles > 0) {
                   2896:         return 1;
                   2897:     }
                   2898:     return 0;
                   2899: }
                   2900: 
1.478     albertel 2901: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2902: # input: action, courseID, current domain, intended
1.637     raeburn  2903: #        path to file, source of file, instruction to parse file for objects,
                   2904: #        ref to hash for embedded objects,
                   2905: #        ref to hash for codebase of java objects.
1.1095    raeburn  2906: #        reference to scalar to accommodate mime type determined
                   2907: #          from File::MMagic if $parser = parse.
1.637     raeburn  2908: #
1.485     raeburn  2909: # output: url to file (if action was uploaddoc), 
                   2910: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2911: #
1.478     albertel 2912: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2913: # course.
1.477     raeburn  2914: #
1.478     albertel 2915: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2916: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2917: #          course's home server.
1.477     raeburn  2918: #
1.478     albertel 2919: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2920: #          be copied from $source (current location) to 
                   2921: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2922: #         and will then be copied to
                   2923: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2924: #         course's home server.
1.485     raeburn  2925: #
1.481     raeburn  2926: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2927: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2928: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2929: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2930: #         in course's home server.
1.637     raeburn  2931: #
1.477     raeburn  2932: 
                   2933: sub process_coursefile {
1.1095    raeburn  2934:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2935:         $mimetype)=@_;
1.477     raeburn  2936:     my $fetchresult;
1.638     albertel 2937:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2938:     if ($action eq 'propagate') {
1.638     albertel 2939:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2940: 			     $home);
1.481     raeburn  2941:     } else {
1.477     raeburn  2942:         my $fpath = '';
                   2943:         my $fname = $file;
1.478     albertel 2944:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2945:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2946:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2947:         if ($action eq 'copy') {
                   2948:             if ($source eq '') {
                   2949:                 $fetchresult = 'no source file';
                   2950:                 return $fetchresult;
                   2951:             } else {
                   2952:                 my $destination = $filepath.'/'.$fname;
                   2953:                 rename($source,$destination);
                   2954:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2955:                                  $home);
1.481     raeburn  2956:             }
                   2957:         } elsif ($action eq 'uploaddoc') {
                   2958:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2959:             print $fh $env{'form.'.$source};
1.481     raeburn  2960:             close($fh);
1.637     raeburn  2961:             if ($parser eq 'parse') {
1.1024    raeburn  2962:                 my $mm = new File::MMagic;
1.1095    raeburn  2963:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2964:                 if ($type eq 'text/html') {
1.1024    raeburn  2965:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2966:                     unless ($parse_result eq 'ok') {
                   2967:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2968:                     }
1.637     raeburn  2969:                 }
1.1095    raeburn  2970:                 if (ref($mimetype)) {
                   2971:                     $$mimetype = $type;
                   2972:                 } 
1.637     raeburn  2973:             }
1.477     raeburn  2974:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2975:                                  $home);
1.481     raeburn  2976:             if ($fetchresult eq 'ok') {
                   2977:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2978:             } else {
                   2979:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2980:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2981:                 return '/adm/notfound.html';
                   2982:             }
1.477     raeburn  2983:         }
                   2984:     }
1.485     raeburn  2985:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2986:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2987:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2988:     }
                   2989:     return $fetchresult;
                   2990: }
                   2991: 
1.637     raeburn  2992: sub build_filepath {
                   2993:     my ($fpath) = @_;
                   2994:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2995:     unless ($fpath eq '') {
                   2996:         my @parts=split('/',$fpath);
                   2997:         foreach my $part (@parts) {
                   2998:             $filepath.= '/'.$part;
                   2999:             if ((-e $filepath)!=1) {
                   3000:                 mkdir($filepath,0777);
                   3001:             }
                   3002:         }
                   3003:     }
                   3004:     return $filepath;
                   3005: }
                   3006: 
                   3007: sub store_edited_file {
1.638     albertel 3008:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3009:     my $file = $primary_url;
                   3010:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3011:     my $fpath = '';
                   3012:     my $fname = $file;
                   3013:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3014:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3015:     my $filepath = &build_filepath($fpath);
                   3016:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3017:     print $fh $content;
                   3018:     close($fh);
1.638     albertel 3019:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3020:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3021: 			  $home);
1.637     raeburn  3022:     if ($$fetchresult eq 'ok') {
                   3023:         return '/uploaded/'.$fpath.'/'.$fname;
                   3024:     } else {
1.638     albertel 3025:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3026: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3027:         return '/adm/notfound.html';
                   3028:     }
                   3029: }
                   3030: 
1.531     albertel 3031: sub clean_filename {
1.831     albertel 3032:     my ($fname,$args)=@_;
1.315     www      3033: # Replace Windows backslashes by forward slashes
1.257     www      3034:     $fname=~s/\\/\//g;
1.831     albertel 3035:     if (!$args->{'keep_path'}) {
                   3036:         # Get rid of everything but the actual filename
                   3037: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3038:     }
1.315     www      3039: # Replace spaces by underscores
                   3040:     $fname=~s/\s+/\_/g;
                   3041: # Replace all other weird characters by nothing
1.831     albertel 3042:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3043: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3044: # numbers
                   3045:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3046:     return $fname;
                   3047: }
1.1051    raeburn  3048: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3049: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3050: # image with the same aspect ratio as the original, but with dimensions which do 
                   3051: # not exceed $resizewidth and $resizeheight.
                   3052:  
1.984     neumanie 3053: sub resizeImage {
1.1051    raeburn  3054:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3055:     my $ima = Image::Magick->new;
                   3056:     my $resized;
                   3057:     if (-e $img_path) {
                   3058:         $ima->Read($img_path);
                   3059:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3060:             my $width = $ima->Get('width');
                   3061:             my $height = $ima->Get('height');
                   3062:             if ($width > $resizewidth) {
                   3063: 	        my $factor = $width/$resizewidth;
                   3064:                 my $newheight = $height/$factor;
                   3065:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3066:                 $resized = 1;
                   3067:             }
                   3068:         }
                   3069:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3070:             my $width = $ima->Get('width');
                   3071:             my $height = $ima->Get('height');
                   3072:             if ($height > $resizeheight) {
                   3073:                 my $factor = $height/$resizeheight;
                   3074:                 my $newwidth = $width/$factor;
                   3075:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3076:                 $resized = 1;
                   3077:             }
                   3078:         }
                   3079:         if ($resized) {
                   3080:             $ima->Write($img_path);
                   3081:         }
                   3082:     }
                   3083:     return;
1.977     amueller 3084: }
                   3085: 
1.608     albertel 3086: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3087: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3088: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3089: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3090: #                                    canceloverwrite, or ''. 
                   3091: #                   if 'coursedoc': upload to the current course
                   3092: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3093: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3094: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3095: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3096: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3097: #        $allfiles - reference to hash for embedded objects
                   3098: #        $codebase - reference to hash for codebase of java objects
                   3099: #        $desuname - username for permanent storage of uploaded file
                   3100: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3101: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3102: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3103: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3104: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3105: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3106: #                    from File::MMagic.
1.858     raeburn  3107: # 
1.686     albertel 3108: # output: url of file in userspace, or error: <message> 
                   3109: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3110: 
1.531     albertel 3111: sub userfileupload {
1.1090    raeburn  3112:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3113:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3114:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3115:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3116:     $fname=&clean_filename($fname);
1.1090    raeburn  3117:     # See if there is anything left
1.257     www      3118:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3119:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3120:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3121:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3122:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3123:         my $now = time;
1.1090    raeburn  3124:         my $filepath;
1.1095    raeburn  3125:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3126:              $filepath = 'tmp/helprequests/'.$now;
                   3127:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3128:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3129:                          '_'.$env{'user.domain'}.'/pending';
                   3130:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3131:             my ($docuname,$docudom);
                   3132:             if ($destudom) {
                   3133:                 $docudom = $destudom;
                   3134:             } else {
                   3135:                 $docudom = $env{'user.domain'};
                   3136:             }
                   3137:             if ($destuname) {
                   3138:                 $docuname = $destuname;
                   3139:             } else {
                   3140:                 $docuname = $env{'user.name'};
                   3141:             }
                   3142:             if (exists($env{'form.group'})) {
                   3143:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3144:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3145:             }
                   3146:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3147:             if ($context eq 'canceloverwrite') {
                   3148:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3149:                 if (-e  $tempfile) {
                   3150:                     my @info = stat($tempfile);
                   3151:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3152:                         unlink($tempfile);
                   3153:                     }
                   3154:                 }
                   3155:                 return;
1.523     raeburn  3156:             }
                   3157:         }
1.1090    raeburn  3158:         # Create the directory if not present
1.741     raeburn  3159:         my @parts=split(/\//,$filepath);
                   3160:         my $fullpath = $perlvar{'lonDaemons'};
                   3161:         for (my $i=0;$i<@parts;$i++) {
                   3162:             $fullpath .= '/'.$parts[$i];
                   3163:             if ((-e $fullpath)!=1) {
                   3164:                 mkdir($fullpath,0777);
                   3165:             }
                   3166:         }
                   3167:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3168:         print $fh $env{'form.'.$formname};
                   3169:         close($fh);
1.1090    raeburn  3170:         if ($context eq 'existingfile') {
                   3171:             my @info = stat($fullpath.'/'.$fname);
                   3172:             return ($fullpath.'/'.$fname,$info[9]);
                   3173:         } else {
                   3174:             return $fullpath.'/'.$fname;
                   3175:         }
1.523     raeburn  3176:     }
1.995     raeburn  3177:     if ($subdir eq 'scantron') {
                   3178:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3179:     } else {
1.995     raeburn  3180:         $fname="$subdir/$fname";
                   3181:     }
1.1090    raeburn  3182:     if ($context eq 'coursedoc') {
1.638     albertel 3183: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3184: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3185:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3186:             return &finishuserfileupload($docuname,$docudom,
                   3187: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3188: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3189:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3190:         } else {
1.1172.2.21  raeburn  3191:             if ($env{'form.folder'}) {
                   3192:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3193:             }
1.638     albertel 3194:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3195: 				       $fname,$formname,$parser,
1.1095    raeburn  3196: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3197:         }
1.719     banghart 3198:     } elsif (defined($destuname)) {
                   3199:         my $docuname=$destuname;
                   3200:         my $docudom=$destudom;
1.860     raeburn  3201: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3202: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3203:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3204:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3205:     } else {
1.638     albertel 3206:         my $docuname=$env{'user.name'};
                   3207:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3208:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3209:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3210:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3211:         }
1.860     raeburn  3212: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3213: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3214:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3215:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3216:     }
1.271     www      3217: }
                   3218: 
                   3219: sub finishuserfileupload {
1.860     raeburn  3220:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3221:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3222:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3223:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3224:   
1.860     raeburn  3225:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3226:     $file=$fname;
                   3227:     if ($fname=~m|/|) {
                   3228:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3229: 	$path.=$fnamepath.'/';
                   3230:     }
1.259     www      3231:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3232:     my $count;
                   3233:     for ($count=4;$count<=$#parts;$count++) {
                   3234:         $filepath.="/$parts[$count]";
                   3235:         if ((-e $filepath)!=1) {
                   3236: 	    mkdir($filepath,0777);
                   3237:         }
                   3238:     }
1.984     neumanie 3239: 
1.258     www      3240: # Save the file
                   3241:     {
1.701     albertel 3242: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3243: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3244: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3245: 	    return '/adm/notfound.html';
                   3246: 	}
1.1090    raeburn  3247:         if ($context eq 'overwrite') {
1.1117    foxr     3248:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3249:             my $target = $filepath.'/'.$file;
                   3250:             if (-e $source) {
                   3251:                 my @info = stat($source);
                   3252:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3253:                     unless (&File::Copy::move($source,$target)) {
                   3254:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3255:                         return "Moving from $source failed";
                   3256:                     }
                   3257:                 } else {
                   3258:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3259:                 }
                   3260:             } else {
                   3261:                 return "Temporary file: $source missing";
                   3262:             }
                   3263:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3264: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3265: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3266: 	    return '/adm/notfound.html';
                   3267: 	}
1.570     albertel 3268: 	close(FH);
1.1051    raeburn  3269:         if ($resizewidth && $resizeheight) {
                   3270:             my $mm = new File::MMagic;
                   3271:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3272:             if ($mime_type =~ m{^image/}) {
                   3273: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3274:             }  
1.977     amueller 3275: 	}
1.258     www      3276:     }
1.1152    raeburn  3277:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3278:         if (ref($mimetype)) {
                   3279:             if ($$mimetype eq '') {
                   3280:                 my $mm = new File::MMagic;
                   3281:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3282:                 $$mimetype = $type;
                   3283:             }
                   3284:         }
                   3285:     }
1.637     raeburn  3286:     if ($parser eq 'parse') {
1.1152    raeburn  3287:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3288:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3289:                                                        $allfiles,$codebase);
                   3290:             unless ($parse_result eq 'ok') {
                   3291:                 &logthis('Failed to parse '.$filepath.$file.
                   3292: 	   	         ' for embedded media: '.$parse_result); 
                   3293:             }
1.637     raeburn  3294:         }
                   3295:     }
1.860     raeburn  3296:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3297:         my $input = $filepath.'/'.$file;
                   3298:         my $output = $filepath.'/'.'tn-'.$file;
                   3299:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3300:         system("convert -sample $thumbsize $input $output");
                   3301:         if (-e $filepath.'/'.'tn-'.$file) {
                   3302:             $fetchthumb  = 1; 
                   3303:         }
                   3304:     }
1.858     raeburn  3305:  
1.259     www      3306: # Notify homeserver to grep it
                   3307: #
1.984     neumanie 3308:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3309:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3310:     if ($fetchresult eq 'ok') {
1.860     raeburn  3311:         if ($fetchthumb) {
                   3312:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3313:             if ($thumbresult ne 'ok') {
                   3314:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3315:                          $docuhome.': '.$thumbresult);
                   3316:             }
                   3317:         }
1.259     www      3318: #
1.258     www      3319: # Return the URL to it
1.494     albertel 3320:         return '/uploaded/'.$path.$file;
1.263     www      3321:     } else {
1.494     albertel 3322:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3323: 		 ': '.$fetchresult);
1.263     www      3324:         return '/adm/notfound.html';
1.858     raeburn  3325:     }
1.493     albertel 3326: }
                   3327: 
1.637     raeburn  3328: sub extract_embedded_items {
1.961     raeburn  3329:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3330:     my @state = ();
1.1164    raeburn  3331:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3332:     my %javafiles = (
                   3333:                       codebase => '',
                   3334:                       code => '',
                   3335:                       archive => ''
                   3336:                     );
                   3337:     my %mediafiles = (
                   3338:                       src => '',
                   3339:                       movie => '',
                   3340:                      );
1.648     raeburn  3341:     my $p;
                   3342:     if ($content) {
                   3343:         $p = HTML::LCParser->new($content);
                   3344:     } else {
1.961     raeburn  3345:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3346:     }
1.641     albertel 3347:     while (my $t=$p->get_token()) {
1.640     albertel 3348: 	if ($t->[0] eq 'S') {
                   3349: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3350: 	    push(@state, $tagname);
1.648     raeburn  3351:             if (lc($tagname) eq 'allow') {
                   3352:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3353:             }
1.640     albertel 3354: 	    if (lc($tagname) eq 'img') {
                   3355: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3356: 	    }
1.886     albertel 3357: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3358:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3359: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3360:                 }
1.886     albertel 3361: 	    }
1.645     raeburn  3362:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3363:                 my $src;
1.645     raeburn  3364:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3365:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3366:                 } else {
1.1164    raeburn  3367:                     if ($attr->{'src'} ne '') {
                   3368:                         $src = $attr->{'src'};
                   3369:                         &add_filetype($allfiles,$src,'src');
                   3370:                     }
                   3371:                 }
                   3372:                 my $text = $p->get_trimmed_text();
                   3373:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3374:                     my @swfargs = split(/,/,$1);
                   3375:                     foreach my $item (@swfargs) {
                   3376:                         $item =~ s/["']//g;
                   3377:                         $item =~ s/^\s+//;
                   3378:                         $item =~ s/\s+$//;
                   3379:                     }
                   3380:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3381:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3382:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3383:                         } else {
                   3384:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3385:                         }
                   3386:                     }
1.645     raeburn  3387:                 }
                   3388:             }
                   3389:             if (lc($tagname) eq 'link') {
                   3390:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3391:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3392:                 }
                   3393:             }
1.640     albertel 3394: 	    if (lc($tagname) eq 'object' ||
                   3395: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3396: 		foreach my $item (keys(%javafiles)) {
                   3397: 		    $javafiles{$item} = '';
                   3398: 		}
1.1164    raeburn  3399:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3400:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3401:                 }
1.640     albertel 3402: 	    }
                   3403: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3404: 		my $name = lc($attr->{'name'});
                   3405: 		foreach my $item (keys(%javafiles)) {
                   3406: 		    if ($name eq $item) {
                   3407: 			$javafiles{$item} = $attr->{'value'};
                   3408: 			last;
                   3409: 		    }
                   3410: 		}
1.1164    raeburn  3411:                 my $pathfrom;
1.640     albertel 3412: 		foreach my $item (keys(%mediafiles)) {
                   3413: 		    if ($name eq $item) {
1.1164    raeburn  3414:                         $pathfrom = $attr->{'value'};
                   3415:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3416: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3417: 			last;
                   3418: 		    }
                   3419: 		}
1.1164    raeburn  3420:                 if ($name eq 'flashvars') {
                   3421:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3422:                 }
                   3423:                 if ($pathfrom ne '') {
                   3424:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3425:                                          $pathfrom);
                   3426:                 }
1.640     albertel 3427: 	    }
                   3428: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3429: 		foreach my $item (keys(%javafiles)) {
                   3430: 		    if ($attr->{$item}) {
                   3431: 			$javafiles{$item} = $attr->{$item};
                   3432: 			last;
                   3433: 		    }
                   3434: 		}
                   3435: 		foreach my $item (keys(%mediafiles)) {
                   3436: 		    if ($attr->{$item}) {
                   3437: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3438: 			last;
                   3439: 		    }
                   3440: 		}
1.1164    raeburn  3441:                 if (lc($tagname) eq 'embed') {
                   3442:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3443:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3444:                                              $attr->{'src'});
                   3445:                     }
                   3446:                 }
1.640     albertel 3447: 	    }
1.1164    raeburn  3448:             if ($t->[4] =~ m{/>$}) {
                   3449:                 pop(@state);  
                   3450:             }
1.640     albertel 3451: 	} elsif ($t->[0] eq 'E') {
                   3452: 	    my ($tagname) = ($t->[1]);
                   3453: 	    if ($javafiles{'codebase'} ne '') {
                   3454: 		$javafiles{'codebase'} .= '/';
                   3455: 	    }  
                   3456: 	    if (lc($tagname) eq 'applet' ||
                   3457: 		lc($tagname) eq 'object' ||
                   3458: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3459: 		) {
                   3460: 		foreach my $item (keys(%javafiles)) {
                   3461: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3462: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3463: 			&add_filetype($allfiles,$file,$item);
                   3464: 		    }
                   3465: 		}
                   3466: 	    } 
                   3467: 	    pop @state;
                   3468: 	}
                   3469:     }
1.1164    raeburn  3470:     foreach my $id (sort(keys(%flashvars))) {
                   3471:         if ($shockwave{$id} ne '') {
                   3472:             my @pairs = split(/\&/,$flashvars{$id});
                   3473:             foreach my $pair (@pairs) {
                   3474:                 my ($key,$value) = split(/\=/,$pair);
                   3475:                 if ($key eq 'thumb') {
                   3476:                     &add_filetype($allfiles,$value,$key);
                   3477:                 } elsif ($key eq 'content') {
                   3478:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3479:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3480:                     if ($ext ne '') {
                   3481:                         &add_filetype($allfiles,$path.$value,$ext);
                   3482:                     }
                   3483:                 }
                   3484:             }
                   3485:         }
                   3486:     }
1.637     raeburn  3487:     return 'ok';
                   3488: }
                   3489: 
1.639     albertel 3490: sub add_filetype {
                   3491:     my ($allfiles,$file,$type)=@_;
                   3492:     if (exists($allfiles->{$file})) {
                   3493: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3494: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3495: 	}
                   3496:     } else {
                   3497: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3498:     }
                   3499: }
                   3500: 
1.1164    raeburn  3501: sub embedded_dependency {
                   3502:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3503:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3504:         if (($identifier ne '') &&
                   3505:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3506:             ($pathfrom ne '')) {
                   3507:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3508:             foreach my $dep (@{$related->{$identifier}}) {
                   3509:                 &add_filetype($allfiles,$path.$dep,'object');
                   3510:             }
                   3511:         }
                   3512:     }
                   3513:     return;
                   3514: }
                   3515: 
1.493     albertel 3516: sub removeuploadedurl {
1.984     neumanie 3517:     my ($url)=@_;	
                   3518:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3519:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3520: }
                   3521: 
                   3522: sub removeuserfile {
                   3523:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3524:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3525:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3526:     if ($result eq 'ok') {	
1.798     raeburn  3527:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3528:             my $metafile = $fname.'.meta';
                   3529:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3530: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3531:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3532:             my $sqlresult = 
1.823     albertel 3533:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3534:                                         'portfolio_metadata',$group,
                   3535:                                         'delete');
1.798     raeburn  3536:         }
                   3537:     }
                   3538:     return $result;
1.257     www      3539: }
1.15      www      3540: 
1.530     albertel 3541: sub mkdiruserfile {
                   3542:     my ($docuname,$docudom,$dir)=@_;
                   3543:     my $home=&homeserver($docuname,$docudom);
                   3544:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3545: }
                   3546: 
1.531     albertel 3547: sub renameuserfile {
                   3548:     my ($docuname,$docudom,$old,$new)=@_;
                   3549:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3550:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3551:                         &escape("$old").':'.&escape("$new"),$home);
                   3552:     if ($result eq 'ok') {
                   3553:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3554:             my $oldmeta = $old.'.meta';
                   3555:             my $newmeta = $new.'.meta';
                   3556:             my $metaresult = 
                   3557:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3558: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3559:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3560:             my $sqlresult = 
1.823     albertel 3561:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3562:                                         'portfolio_metadata',$group,
                   3563:                                         'delete');
1.798     raeburn  3564:         }
                   3565:     }
                   3566:     return $result;
1.531     albertel 3567: }
                   3568: 
1.14      www      3569: # ------------------------------------------------------------------------- Log
                   3570: 
                   3571: sub log {
                   3572:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3573:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3574: }
                   3575: 
                   3576: # ------------------------------------------------------------------ Course Log
1.352     www      3577: #
                   3578: # This routine flushes several buffers of non-mission-critical nature
                   3579: #
1.157     www      3580: 
                   3581: sub flushcourselogs {
1.352     www      3582:     &logthis('Flushing log buffers');
                   3583: #
                   3584: # course logs
                   3585: # This is a log of all transactions in a course, which can be used
                   3586: # for data mining purposes
                   3587: #
                   3588: # It also collects the courseid database, which lists last transaction
                   3589: # times and course titles for all courseids
                   3590: #
                   3591:     my %courseidbuffer=();
1.921     raeburn  3592:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3593:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3594: 		          &escape($courselogs{$crsid}),
                   3595: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3596: 	    delete $courselogs{$crsid};
                   3597:         } else {
                   3598:             &logthis('Failed to flush log buffer for '.$crsid);
                   3599:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3600:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3601:                         " exceeded maximum size, deleting.</font>");
                   3602:                delete $courselogs{$crsid};
                   3603:             }
1.352     www      3604:         }
1.920     raeburn  3605:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3606:             'description' => $coursedescrbuf{$crsid},
                   3607:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3608:             'type'        => $coursetypebuf{$crsid},
                   3609:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3610:         };
1.191     harris41 3611:     }
1.352     www      3612: #
                   3613: # Write course id database (reverse lookup) to homeserver of courses 
                   3614: # Is used in pickcourse
                   3615: #
1.840     albertel 3616:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3617:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3618:                                     $courseidbuffer{$crs_home},
                   3619:                                     $crs_home,'timeonly');
1.352     www      3620:     }
                   3621: #
                   3622: # File accesses
                   3623: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3624: #
1.449     matthew  3625:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3626:         if ($entry =~ /___count$/) {
                   3627:             my ($dom,$name);
1.807     albertel 3628:             ($dom,$name,undef)=
1.811     albertel 3629: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3630:             if (! defined($dom) || $dom eq '' || 
                   3631:                 ! defined($name) || $name eq '') {
1.620     albertel 3632:                 my $cid = $env{'request.course.id'};
                   3633:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3634:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3635:             }
1.450     matthew  3636:             my $value = $accesshash{$entry};
                   3637:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3638:             my %temphash=($url => $value);
1.449     matthew  3639:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3640:             if ($result eq 'ok') {
                   3641:                 delete $accesshash{$entry};
                   3642:             }
                   3643:         } else {
1.811     albertel 3644:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3645:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3646:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3647:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3648:                 delete $accesshash{$entry};
                   3649:             }
1.185     www      3650:         }
1.191     harris41 3651:     }
1.352     www      3652: #
                   3653: # Roles
                   3654: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3655: #
1.800     albertel 3656:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3657:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3658: 	    split(/\:/,$entry);
                   3659:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3660:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3661:                 $rudom,$runame) eq 'ok') {
                   3662: 	    delete $userrolehash{$entry};
                   3663:         }
                   3664:     }
1.662     raeburn  3665: #
                   3666: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3667: #
                   3668:     my %domrolebuffer = ();
1.1000    raeburn  3669:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3670:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3671:         if ($domrolebuffer{$rudom}) {
                   3672:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3673:                       '='.&escape($domainrolehash{$entry});
                   3674:         } else {
                   3675:             $domrolebuffer{$rudom}.=&escape($entry).
                   3676:                       '='.&escape($domainrolehash{$entry});
                   3677:         }
                   3678:         delete $domainrolehash{$entry};
                   3679:     }
                   3680:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3681: 	my %servers = &get_servers($dom,'library');
                   3682: 	foreach my $tryserver (keys(%servers)) {
                   3683: 	    unless (&reply('domroleput:'.$dom.':'.
                   3684: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3685: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3686: 	    }
1.662     raeburn  3687:         }
                   3688:     }
1.186     www      3689:     $dumpcount++;
1.157     www      3690: }
                   3691: 
                   3692: sub courselog {
                   3693:     my $what=shift;
1.158     www      3694:     $what=time.':'.$what;
1.620     albertel 3695:     unless ($env{'request.course.id'}) { return ''; }
                   3696:     $coursedombuf{$env{'request.course.id'}}=
                   3697:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3698:     $coursenumbuf{$env{'request.course.id'}}=
                   3699:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3700:     $coursehombuf{$env{'request.course.id'}}=
                   3701:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3702:     $coursedescrbuf{$env{'request.course.id'}}=
                   3703:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3704:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3705:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3706:     $courseownerbuf{$env{'request.course.id'}}=
                   3707:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3708:     $coursetypebuf{$env{'request.course.id'}}=
                   3709:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3710:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3711: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3712:     } else {
1.620     albertel 3713: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3714:     }
1.620     albertel 3715:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3716: 	&flushcourselogs();
                   3717:     }
1.158     www      3718: }
                   3719: 
                   3720: sub courseacclog {
                   3721:     my $fnsymb=shift;
1.620     albertel 3722:     unless ($env{'request.course.id'}) { return ''; }
                   3723:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3724:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3725:         $what.=':POST';
1.583     matthew  3726:         # FIXME: Probably ought to escape things....
1.800     albertel 3727: 	foreach my $key (keys(%env)) {
                   3728:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3729:                 my $formitem = $1;
                   3730:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3731:                     $what.=':'.$formitem.'='.$env{$key};
                   3732:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3733:                     $what.=':'.$formitem.'='.$env{$key};
                   3734:                 }
1.158     www      3735:             }
1.191     harris41 3736:         }
1.583     matthew  3737:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3738:         # FIXME: We should not be depending on a form parameter that someone
                   3739:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3740:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3741:             $what.= ':POST';
                   3742:             # FIXME: Probably ought to escape things....
                   3743:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3744:                                  'crsdiscuss') {
1.620     albertel 3745:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3746:             }
                   3747:         }
1.158     www      3748:     }
                   3749:     &courselog($what);
1.149     www      3750: }
                   3751: 
1.185     www      3752: sub countacc {
                   3753:     my $url=&declutter(shift);
1.458     matthew  3754:     return if (! defined($url) || $url eq '');
1.620     albertel 3755:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3756: #
                   3757: # Mark that this url was used in this course
                   3758: #
1.620     albertel 3759:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3760: #
                   3761: # Increase the access count for this resource in this child process
                   3762: #
1.281     www      3763:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3764:     $accesshash{$key}++;
1.185     www      3765: }
1.349     www      3766: 
1.361     www      3767: sub linklog {
                   3768:     my ($from,$to)=@_;
                   3769:     $from=&declutter($from);
                   3770:     $to=&declutter($to);
                   3771:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3772:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3773: }
1.1160    www      3774: 
                   3775: sub statslog {
                   3776:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3777:     if ($users<2) { return; }
                   3778:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3779:             'course'       => $env{'request.course.id'},
                   3780:             'sections'     => '"all"',
                   3781:             'num_students' => $users,
                   3782:             'part'         => $part,
                   3783:             'symb'         => $symb,
                   3784:             'mean_tries'   => $av_attempts,
                   3785:             'deg_of_diff'  => $degdiff});
                   3786:     foreach my $key (keys(%dynstore)) {
                   3787:         $accesshash{$key}=$dynstore{$key};
                   3788:     }
                   3789: }
1.361     www      3790:   
1.349     www      3791: sub userrolelog {
                   3792:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3793:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3794:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3795:        $userrolehash
                   3796:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3797:                     =$tend.':'.$tstart;
1.662     raeburn  3798:     }
1.1169    droeschl 3799:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3800:        $userrolehash
                   3801:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3802:                     =$tend.':'.$tstart;
                   3803:     }
1.1169    droeschl 3804:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3805:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3806:        $domainrolehash
                   3807:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3808:                     = $tend.':'.$tstart;
                   3809:     }
1.351     www      3810: }
                   3811: 
1.957     raeburn  3812: sub courserolelog {
                   3813:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3814:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3815:         my $cdom = $1;
                   3816:         my $cnum = $2;
                   3817:         my $sec = $3;
                   3818:         my $namespace = 'rolelog';
                   3819:         my %storehash = (
                   3820:                            role    => $trole,
                   3821:                            start   => $tstart,
                   3822:                            end     => $tend,
                   3823:                            selfenroll => $selfenroll,
                   3824:                            context    => $context,
                   3825:                         );
                   3826:         if ($trole eq 'gr') {
                   3827:             $namespace = 'groupslog';
                   3828:             $storehash{'group'} = $sec;
                   3829:         } else {
                   3830:             $storehash{'section'} = $sec;
                   3831:         }
                   3832:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3833:                    $domain,$cnum,$cdom);
                   3834:         if (($trole ne 'st') || ($sec ne '')) {
                   3835:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3836:         }
                   3837:     }
                   3838:     return;
                   3839: }
                   3840: 
1.1172.2.9  raeburn  3841: sub domainrolelog {
                   3842:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3843:     if ($area =~ m{^/($match_domain)/$}) {
                   3844:         my $cdom = $1;
                   3845:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3846:         my $namespace = 'rolelog';
                   3847:         my %storehash = (
                   3848:                            role    => $trole,
                   3849:                            start   => $tstart,
                   3850:                            end     => $tend,
                   3851:                            context => $context,
                   3852:                         );
                   3853:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3854:                    $domain,$domconfiguser,$cdom);
                   3855:     }
                   3856:     return;
                   3857: 
                   3858: }
                   3859: 
                   3860: sub coauthorrolelog {
                   3861:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3862:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3863:         my $audom = $1;
                   3864:         my $auname = $2;
                   3865:         my $namespace = 'rolelog';
                   3866:         my %storehash = (
                   3867:                            role    => $trole,
                   3868:                            start   => $tstart,
                   3869:                            end     => $tend,
                   3870:                            context => $context,
                   3871:                         );
                   3872:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3873:                    $domain,$auname,$audom);
                   3874:     }
                   3875:     return;
                   3876: }
                   3877: 
1.351     www      3878: sub get_course_adv_roles {
1.948     raeburn  3879:     my ($cid,$codes) = @_;
1.620     albertel 3880:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3881:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3882:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3883:     my %nothide=();
1.800     albertel 3884:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3885:         if ($user !~ /:/) {
                   3886: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3887:         } else {
                   3888:             $nothide{$user}=1;
                   3889:         }
1.470     www      3890:     }
1.1172.2.23  raeburn  3891:     my @possdoms = ($coursehash{'domain'});
                   3892:     if ($coursehash{'checkforpriv'}) {
                   3893:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3894:     }
1.351     www      3895:     my %returnhash=();
                   3896:     my %dumphash=
                   3897:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3898:     my $now=time;
1.997     raeburn  3899:     my %privileged;
1.1000    raeburn  3900:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3901: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3902:         if (($tstart) && ($tstart<0)) { next; }
                   3903:         if (($tend) && ($tend<$now)) { next; }
                   3904:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3905:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3906: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  3907:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3908:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3909: 	if ($role eq 'cr') { next; }
1.948     raeburn  3910:         if ($codes) {
                   3911:             if ($section) { $role .= ':'.$section; }
                   3912:             if ($returnhash{$role}) {
                   3913:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3914:             } else {
                   3915:                 $returnhash{$role}=$username.':'.$domain;
                   3916:             }
1.351     www      3917:         } else {
1.988     raeburn  3918:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3919:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3920:             if ($returnhash{$key}) {
                   3921: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3922:             } else {
                   3923:                 $returnhash{$key}=$username.':'.$domain;
                   3924:             }
1.351     www      3925:         }
1.948     raeburn  3926:     }
1.400     www      3927:     return %returnhash;
                   3928: }
                   3929: 
                   3930: sub get_my_roles {
1.937     raeburn  3931:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3932:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3933:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3934:     my (%dumphash,%nothide);
1.1086    raeburn  3935:     if ($context eq 'userroles') {
1.1166    raeburn  3936:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3937:     } else {
1.1172.2.23  raeburn  3938:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3939:         if ($hidepriv) {
                   3940:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3941:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3942:                 if ($user !~ /:/) {
                   3943:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3944:                 } else {
                   3945:                     $nothide{$user} = 1;
                   3946:                 }
                   3947:             }
                   3948:         }
1.858     raeburn  3949:     }
1.400     www      3950:     my %returnhash=();
                   3951:     my $now=time;
1.999     raeburn  3952:     my %privileged;
1.800     albertel 3953:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3954:         my ($role,$tend,$tstart);
                   3955:         if ($context eq 'userroles') {
1.1149    raeburn  3956:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3957: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3958:         } else {
                   3959:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3960:         }
1.400     www      3961:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3962:         my $status = 'active';
1.939     raeburn  3963:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3964:             $status = 'previous';
                   3965:         } 
                   3966:         if (($tstart) && ($now<$tstart)) {
                   3967:             $status = 'future';
                   3968:         }
                   3969:         if (ref($types) eq 'ARRAY') {
                   3970:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3971:                 next;
                   3972:             } 
                   3973:         } else {
                   3974:             if ($status ne 'active') {
                   3975:                 next;
                   3976:             }
                   3977:         }
1.867     raeburn  3978:         my ($rolecode,$username,$domain,$section,$area);
                   3979:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3980:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3981:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3982:         } else {
                   3983:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3984:         }
1.832     raeburn  3985:         if (ref($roledoms) eq 'ARRAY') {
                   3986:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3987:                 next;
                   3988:             }
                   3989:         }
                   3990:         if (ref($roles) eq 'ARRAY') {
                   3991:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3992:                 if ($role =~ /^cr\//) {
                   3993:                     if (!grep(/^cr$/,@{$roles})) {
                   3994:                         next;
                   3995:                     }
1.1104    raeburn  3996:                 } elsif ($role =~ /^gr\//) {
                   3997:                     if (!grep(/^gr$/,@{$roles})) {
                   3998:                         next;
                   3999:                     }
1.922     raeburn  4000:                 } else {
                   4001:                     next;
                   4002:                 }
1.832     raeburn  4003:             }
1.867     raeburn  4004:         }
1.937     raeburn  4005:         if ($hidepriv) {
1.1172.2.23  raeburn  4006:             my @privroles = ('dc','su');
1.999     raeburn  4007:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4008:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4009:             } else {
1.1172.2.23  raeburn  4010:                 my $possdoms = [$domain];
                   4011:                 if (ref($roledoms) eq 'ARRAY') {
                   4012:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4013:                 }
1.1172.2.23  raeburn  4014:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4015:                     if (!$nothide{$username.':'.$domain}) {
                   4016:                         next;
                   4017:                     }
                   4018:                 }
1.937     raeburn  4019:             }
                   4020:         }
1.933     raeburn  4021:         if ($withsec) {
                   4022:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4023:                 $tstart.':'.$tend;
                   4024:         } else {
                   4025:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4026:         }
1.832     raeburn  4027:     }
1.373     www      4028:     return %returnhash;
1.399     www      4029: }
                   4030: 
                   4031: # ----------------------------------------------------- Frontpage Announcements
                   4032: #
                   4033: #
                   4034: 
                   4035: sub postannounce {
                   4036:     my ($server,$text)=@_;
1.844     albertel 4037:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4038:     unless ($text=~/\w/) { $text=''; }
                   4039:     return &reply('setannounce:'.&escape($text),$server);
                   4040: }
                   4041: 
                   4042: sub getannounce {
1.448     albertel 4043: 
                   4044:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4045: 	my $announcement='';
1.800     albertel 4046: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4047: 	close($fh);
1.399     www      4048: 	if ($announcement=~/\w/) { 
                   4049: 	    return 
                   4050:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4051:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4052: 	} else {
                   4053: 	    return '';
                   4054: 	}
                   4055:     } else {
                   4056: 	return '';
                   4057:     }
1.351     www      4058: }
1.353     www      4059: 
                   4060: # ---------------------------------------------------------- Course ID routines
                   4061: # Deal with domain's nohist_courseid.db files
                   4062: #
                   4063: 
                   4064: sub courseidput {
1.921     raeburn  4065:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4066:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4067:     my $outcome;
                   4068:     if ($caller eq 'timeonly') {
                   4069:         my $cids = '';
                   4070:         foreach my $item (keys(%$storehash)) {
                   4071:             $cids.=&escape($item).'&';
                   4072:         }
                   4073:         $cids=~s/\&$//;
                   4074:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4075:                           $coursehome);       
                   4076:     } else {
                   4077:         my $items = '';
                   4078:         foreach my $item (keys(%$storehash)) {
                   4079:             $items.= &escape($item).'='.
                   4080:                      &freeze_escape($$storehash{$item}).'&';
                   4081:         }
                   4082:         $items=~s/\&$//;
                   4083:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4084:                           $coursehome);
1.918     raeburn  4085:     }
                   4086:     if ($outcome eq 'unknown_cmd') {
                   4087:         my $what;
                   4088:         foreach my $cid (keys(%$storehash)) {
                   4089:             $what .= &escape($cid).'=';
1.921     raeburn  4090:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4091:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4092:             }
                   4093:             $what =~ s/\:$/&/;
                   4094:         }
                   4095:         $what =~ s/\&$//;  
                   4096:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4097:     } else {
                   4098:         return $outcome;
                   4099:     }
1.353     www      4100: }
                   4101: 
                   4102: sub courseiddump {
1.921     raeburn  4103:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4104:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4105:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4106:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4107:     my $as_hash = 1;
                   4108:     my %returnhash;
                   4109:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4110:     my %libserv = &all_library();
                   4111:     foreach my $tryserver (keys(%libserv)) {
                   4112:         if ( (  $hostidflag == 1 
                   4113: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4114: 	     || (!defined($hostidflag)) ) {
                   4115: 
1.918     raeburn  4116: 	    if (($domfilter eq '') ||
                   4117: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4118:                 my $rep;
                   4119:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4120:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4121:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4122:                                 &escape($descfilter), &escape($instcodefilter),
                   4123:                                 &escape($ownerfilter), &escape($coursefilter),
                   4124:                                 &escape($typefilter), &escape($regexp_ok),
                   4125:                                 $as_hash, &escape($selfenrollonly),
                   4126:                                 &escape($catfilter), $showhidden, $caller,
                   4127:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4128:                                 &escape($createdbefore), &escape($createdafter),
                   4129:                                 &escape($creationcontext), $domcloner)));
                   4130:                 } else {
                   4131:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4132:                              $sincefilter.':'.&escape($descfilter).':'.
                   4133:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4134:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4135:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4136:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4137:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4138:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4139:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4140:                              &escape($creationcontext).':'.$domcloner,
                   4141:                              $tryserver);
                   4142:                 }
                   4143: 
1.918     raeburn  4144:                 my @pairs=split(/\&/,$rep);
                   4145:                 foreach my $item (@pairs) {
                   4146:                     my ($key,$value)=split(/\=/,$item,2);
                   4147:                     $key = &unescape($key);
                   4148:                     next if ($key =~ /^error: 2 /);
                   4149:                     my $result = &thaw_unescape($value);
                   4150:                     if (ref($result) eq 'HASH') {
                   4151:                         $returnhash{$key}=$result;
                   4152:                     } else {
1.921     raeburn  4153:                         my @responses = split(/:/,$value);
                   4154:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4155:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4156:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4157:                         }
1.1008    raeburn  4158:                     }
1.353     www      4159:                 }
                   4160:             }
                   4161:         }
                   4162:     }
                   4163:     return %returnhash;
                   4164: }
                   4165: 
1.1055    raeburn  4166: sub courselastaccess {
                   4167:     my ($cdom,$cnum,$hostidref) = @_;
                   4168:     my %returnhash;
                   4169:     if ($cdom && $cnum) {
                   4170:         my $chome = &homeserver($cnum,$cdom);
                   4171:         if ($chome ne 'no_host') {
                   4172:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4173:             &extract_lastaccess(\%returnhash,$rep);
                   4174:         }
                   4175:     } else {
                   4176:         if (!$cdom) { $cdom=''; }
                   4177:         my %libserv = &all_library();
                   4178:         foreach my $tryserver (keys(%libserv)) {
                   4179:             if (ref($hostidref) eq 'ARRAY') {
                   4180:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4181:             } 
                   4182:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4183:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4184:                 &extract_lastaccess(\%returnhash,$rep);
                   4185:             }
                   4186:         }
                   4187:     }
                   4188:     return %returnhash;
                   4189: }
                   4190: 
                   4191: sub extract_lastaccess {
                   4192:     my ($returnhash,$rep) = @_;
                   4193:     if (ref($returnhash) eq 'HASH') {
                   4194:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4195:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4196:                  $rep eq '') {
                   4197:             my @pairs=split(/\&/,$rep);
                   4198:             foreach my $item (@pairs) {
                   4199:                 my ($key,$value)=split(/\=/,$item,2);
                   4200:                 $key = &unescape($key);
                   4201:                 next if ($key =~ /^error: 2 /);
                   4202:                 $returnhash->{$key} = &thaw_unescape($value);
                   4203:             }
                   4204:         }
                   4205:     }
                   4206:     return;
                   4207: }
                   4208: 
1.658     raeburn  4209: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4210: 
                   4211: sub dcmailput {
1.685     raeburn  4212:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4213:     my $status = &Apache::lonnet::critical(
1.740     www      4214:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4215:        &escape($message),$server);
1.662     raeburn  4216:     return $status;
                   4217: }
                   4218: 
1.658     raeburn  4219: sub dcmaildump {
                   4220:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4221:     my %returnhash=();
1.846     albertel 4222: 
                   4223:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4224:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4225:                                                          &escape($enddate).':';
                   4226: 	my @esc_senders=map { &escape($_)} @$senders;
                   4227: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4228: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4229:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4230:             if (($key) && ($value)) {
                   4231:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4232:             }
                   4233:         }
                   4234:     }
                   4235:     return %returnhash;
                   4236: }
1.662     raeburn  4237: # ---------------------------------------------------------- Domain roles
                   4238: 
                   4239: sub get_domain_roles {
                   4240:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4241:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4242:         $startdate = '.';
                   4243:     }
1.1018    raeburn  4244:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4245:         $enddate = '.';
                   4246:     }
1.922     raeburn  4247:     my $rolelist;
                   4248:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4249:         $rolelist = join('&',@{$roles});
1.922     raeburn  4250:     }
1.662     raeburn  4251:     my %personnel = ();
1.841     albertel 4252: 
                   4253:     my %servers = &get_servers($dom,'library');
                   4254:     foreach my $tryserver (keys(%servers)) {
                   4255: 	%{$personnel{$tryserver}}=();
                   4256: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4257: 					    &escape($startdate).':'.
                   4258: 					    &escape($enddate).':'.
                   4259: 					    &escape($rolelist), $tryserver))) {
                   4260: 	    my ($key,$value) = split(/\=/,$line,2);
                   4261: 	    if (($key) && ($value)) {
                   4262: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4263: 	    }
                   4264: 	}
1.662     raeburn  4265:     }
                   4266:     return %personnel;
                   4267: }
1.658     raeburn  4268: 
1.1057    www      4269: # ----------------------------------------------------------- Interval timing 
1.149     www      4270: 
1.1153    www      4271: {
                   4272: # Caches needed for speedup of navmaps
                   4273: # We don't want to cache this for very long at all (5 seconds at most)
                   4274: # 
                   4275: # The user for whom we cache
                   4276: my $cachedkey='';
                   4277: # The cached times for this user
                   4278: my %cachedtimes=();
                   4279: # When this was last done
                   4280: my $cachedtime=();
                   4281: 
                   4282: sub load_all_first_access {
1.1154    raeburn  4283:     my ($uname,$udom)=@_;
1.1156    www      4284:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4285:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4286:         return;
                   4287:     }
                   4288:     $cachedtime=time;
                   4289:     $cachedkey=$uname.':'.$udom;
                   4290:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4291: }
                   4292: 
1.504     albertel 4293: sub get_first_access {
1.1162    raeburn  4294:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4295:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4296:     if ($argsymb) { $symb=$argsymb; }
                   4297:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4298:     if ($argmap) { $map = $argmap; }
1.926     albertel 4299:     if ($type eq 'course') {
                   4300: 	$res='course';
                   4301:     } elsif ($type eq 'map') {
1.588     albertel 4302: 	$res=&symbread($map);
                   4303:     } else {
                   4304: 	$res=$symb;
                   4305:     }
1.1153    www      4306:     &load_all_first_access($uname,$udom);
                   4307:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4308: }
                   4309: 
                   4310: sub set_first_access {
1.1162    raeburn  4311:     my ($type,$interval)=@_;
1.790     albertel 4312:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4313:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4314:     if ($type eq 'course') {
                   4315: 	$res='course';
                   4316:     } elsif ($type eq 'map') {
1.588     albertel 4317: 	$res=&symbread($map);
                   4318:     } else {
                   4319: 	$res=$symb;
                   4320:     }
1.1153    www      4321:     $cachedkey='';
1.1162    raeburn  4322:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4323:     if (!$firstaccess) {
1.1162    raeburn  4324:         my $start = time;
                   4325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4326:                           $udom,$uname);
                   4327:         if ($putres eq 'ok') {
                   4328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4329:                  $udom,$uname); 
                   4330:             &appenv(
                   4331:                      {
                   4332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4334:                      }
                   4335:                   );
                   4336:         }
                   4337:         return $putres;
1.505     albertel 4338:     }
                   4339:     return 'already_set';
1.504     albertel 4340: }
1.1153    www      4341: }
1.110     www      4342: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4343: 
                   4344: sub expirespread {
                   4345:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4346:     my $cid=$env{'request.course.id'}; 
1.110     www      4347:     if ($cid) {
                   4348:        my $now=time;
                   4349:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4350:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4351:                             $env{'course.'.$cid.'.num'}.
1.110     www      4352: 	        	    ':nohist_expirationdates:'.
                   4353:                             &escape($key).'='.$now,
1.620     albertel 4354:                             $env{'course.'.$cid.'.home'})
1.110     www      4355:     }
                   4356:     return 'ok';
1.14      www      4357: }
                   4358: 
1.109     www      4359: # ----------------------------------------------------- Devalidate Spreadsheets
                   4360: 
                   4361: sub devalidate {
1.325     www      4362:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4363:     my $cid=$env{'request.course.id'}; 
1.109     www      4364:     if ($cid) {
1.391     matthew  4365:         # delete the stored spreadsheets for
                   4366:         # - the student level sheet of this user in course's homespace
                   4367:         # - the assessment level sheet for this resource 
                   4368:         #   for this user in user's homespace
1.553     albertel 4369: 	# - current conditional state info
1.325     www      4370: 	my $key=$uname.':'.$udom.':';
1.109     www      4371:         my $status=
1.299     matthew  4372: 	    &del('nohist_calculatedsheets',
1.391     matthew  4373: 		 [$key.'studentcalc:'],
1.620     albertel 4374: 		 $env{'course.'.$cid.'.domain'},
                   4375: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4376: 		.' '.
                   4377: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4378: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4379:         unless ($status eq 'ok ok') {
                   4380:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4381:                     $uname.' at '.$udom.' for '.
1.109     www      4382: 		    $symb.': '.$status);
1.133     albertel 4383:         }
1.553     albertel 4384: 	&delenv('user.state.'.$cid);
1.109     www      4385:     }
                   4386: }
                   4387: 
1.265     albertel 4388: sub get_scalar {
                   4389:     my ($string,$end) = @_;
                   4390:     my $value;
                   4391:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4392: 	$value = $1;
                   4393:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4394: 	$value = $1;
                   4395:     }
                   4396:     return &unescape($value);
                   4397: }
                   4398: 
                   4399: sub array2str {
                   4400:   my (@array) = @_;
                   4401:   my $result=&arrayref2str(\@array);
                   4402:   $result=~s/^__ARRAY_REF__//;
                   4403:   $result=~s/__END_ARRAY_REF__$//;
                   4404:   return $result;
                   4405: }
                   4406: 
1.204     albertel 4407: sub arrayref2str {
                   4408:   my ($arrayref) = @_;
1.265     albertel 4409:   my $result='__ARRAY_REF__';
1.204     albertel 4410:   foreach my $elem (@$arrayref) {
1.265     albertel 4411:     if(ref($elem) eq 'ARRAY') {
                   4412:       $result.=&arrayref2str($elem).'&';
                   4413:     } elsif(ref($elem) eq 'HASH') {
                   4414:       $result.=&hashref2str($elem).'&';
                   4415:     } elsif(ref($elem)) {
                   4416:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4417:     } else {
                   4418:       $result.=&escape($elem).'&';
                   4419:     }
                   4420:   }
                   4421:   $result=~s/\&$//;
1.265     albertel 4422:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4423:   return $result;
                   4424: }
                   4425: 
1.168     albertel 4426: sub hash2str {
1.204     albertel 4427:   my (%hash) = @_;
                   4428:   my $result=&hashref2str(\%hash);
1.265     albertel 4429:   $result=~s/^__HASH_REF__//;
                   4430:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4431:   return $result;
                   4432: }
                   4433: 
                   4434: sub hashref2str {
                   4435:   my ($hashref)=@_;
1.265     albertel 4436:   my $result='__HASH_REF__';
1.800     albertel 4437:   foreach my $key (sort(keys(%$hashref))) {
                   4438:     if (ref($key) eq 'ARRAY') {
                   4439:       $result.=&arrayref2str($key).'=';
                   4440:     } elsif (ref($key) eq 'HASH') {
                   4441:       $result.=&hashref2str($key).'=';
                   4442:     } elsif (ref($key)) {
1.265     albertel 4443:       $result.='=';
1.800     albertel 4444:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4445:     } else {
1.1132    raeburn  4446: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4447:     }
                   4448: 
1.800     albertel 4449:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4450:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4451:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4452:       $result.=&hashref2str($hashref->{$key}).'&';
                   4453:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4454:        $result.='&';
1.800     albertel 4455:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4456:     } else {
1.800     albertel 4457:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4458:     }
                   4459:   }
1.168     albertel 4460:   $result=~s/\&$//;
1.265     albertel 4461:   $result .= '__END_HASH_REF__';
1.168     albertel 4462:   return $result;
                   4463: }
                   4464: 
                   4465: sub str2hash {
1.265     albertel 4466:     my ($string)=@_;
                   4467:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4468:     return %$hash;
                   4469: }
                   4470: 
                   4471: sub str2hashref {
1.168     albertel 4472:   my ($string) = @_;
1.265     albertel 4473: 
                   4474:   my %hash;
                   4475: 
                   4476:   if($string !~ /^__HASH_REF__/) {
                   4477:       if (! ($string eq '' || !defined($string))) {
                   4478: 	  $hash{'error'}='Not hash reference';
                   4479:       }
                   4480:       return (\%hash, $string);
                   4481:   }
                   4482: 
                   4483:   $string =~ s/^__HASH_REF__//;
                   4484: 
                   4485:   while($string !~ /^__END_HASH_REF__/) {
                   4486:       #key
                   4487:       my $key='';
                   4488:       if($string =~ /^__HASH_REF__/) {
                   4489:           ($key, $string)=&str2hashref($string);
                   4490:           if(defined($key->{'error'})) {
                   4491:               $hash{'error'}='Bad data';
                   4492:               return (\%hash, $string);
                   4493:           }
                   4494:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4495:           ($key, $string)=&str2arrayref($string);
                   4496:           if($key->[0] eq 'Array reference error') {
                   4497:               $hash{'error'}='Bad data';
                   4498:               return (\%hash, $string);
                   4499:           }
                   4500:       } else {
                   4501:           $string =~ s/^(.*?)=//;
1.267     albertel 4502: 	  $key=&unescape($1);
1.265     albertel 4503:       }
                   4504:       $string =~ s/^=//;
                   4505: 
                   4506:       #value
                   4507:       my $value='';
                   4508:       if($string =~ /^__HASH_REF__/) {
                   4509:           ($value, $string)=&str2hashref($string);
                   4510:           if(defined($value->{'error'})) {
                   4511:               $hash{'error'}='Bad data';
                   4512:               return (\%hash, $string);
                   4513:           }
                   4514:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4515:           ($value, $string)=&str2arrayref($string);
                   4516:           if($value->[0] eq 'Array reference error') {
                   4517:               $hash{'error'}='Bad data';
                   4518:               return (\%hash, $string);
                   4519:           }
                   4520:       } else {
                   4521: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4522:       }
                   4523:       $string =~ s/^&//;
                   4524: 
                   4525:       $hash{$key}=$value;
1.204     albertel 4526:   }
1.265     albertel 4527: 
                   4528:   $string =~ s/^__END_HASH_REF__//;
                   4529: 
                   4530:   return (\%hash, $string);
1.204     albertel 4531: }
                   4532: 
                   4533: sub str2array {
1.265     albertel 4534:     my ($string)=@_;
                   4535:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4536:     return @$array;
                   4537: }
                   4538: 
                   4539: sub str2arrayref {
1.204     albertel 4540:   my ($string) = @_;
1.265     albertel 4541:   my @array;
                   4542: 
                   4543:   if($string !~ /^__ARRAY_REF__/) {
                   4544:       if (! ($string eq '' || !defined($string))) {
                   4545: 	  $array[0]='Array reference error';
                   4546:       }
                   4547:       return (\@array, $string);
                   4548:   }
                   4549: 
                   4550:   $string =~ s/^__ARRAY_REF__//;
                   4551: 
                   4552:   while($string !~ /^__END_ARRAY_REF__/) {
                   4553:       my $value='';
                   4554:       if($string =~ /^__HASH_REF__/) {
                   4555:           ($value, $string)=&str2hashref($string);
                   4556:           if(defined($value->{'error'})) {
                   4557:               $array[0] ='Array reference error';
                   4558:               return (\@array, $string);
                   4559:           }
                   4560:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4561:           ($value, $string)=&str2arrayref($string);
                   4562:           if($value->[0] eq 'Array reference error') {
                   4563:               $array[0] ='Array reference error';
                   4564:               return (\@array, $string);
                   4565:           }
                   4566:       } else {
                   4567: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4568:       }
                   4569:       $string =~ s/^&//;
                   4570: 
                   4571:       push(@array, $value);
1.191     harris41 4572:   }
1.265     albertel 4573: 
                   4574:   $string =~ s/^__END_ARRAY_REF__//;
                   4575: 
                   4576:   return (\@array, $string);
1.168     albertel 4577: }
                   4578: 
1.167     albertel 4579: # -------------------------------------------------------------------Temp Store
                   4580: 
1.168     albertel 4581: sub tmpreset {
                   4582:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4583:   if (!$symb) {
                   4584:     $symb=&symbread();
1.620     albertel 4585:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4586:   }
                   4587:   $symb=escape($symb);
                   4588: 
1.620     albertel 4589:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4590:   $namespace=~s/\//\_/g;
                   4591:   $namespace=~s/\W//g;
                   4592: 
1.620     albertel 4593:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4594:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4595:   if ($domain eq 'public' && $stuname eq 'public') {
                   4596:       $stuname=$ENV{'REMOTE_ADDR'};
                   4597:   }
1.1117    foxr     4598:   my $path=LONCAPA::tempdir();
1.168     albertel 4599:   my %hash;
                   4600:   if (tie(%hash,'GDBM_File',
                   4601: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4602: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4603:     foreach my $key (keys(%hash)) {
1.180     albertel 4604:       if ($key=~ /:$symb/) {
1.168     albertel 4605: 	delete($hash{$key});
                   4606:       }
                   4607:     }
                   4608:   }
                   4609: }
                   4610: 
1.167     albertel 4611: sub tmpstore {
1.168     albertel 4612:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4613: 
                   4614:   if (!$symb) {
                   4615:     $symb=&symbread();
1.620     albertel 4616:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4617:   }
                   4618:   $symb=escape($symb);
                   4619: 
                   4620:   if (!$namespace) {
                   4621:     # I don't think we would ever want to store this for a course.
                   4622:     # it seems this will only be used if we don't have a course.
1.620     albertel 4623:     #$namespace=$env{'request.course.id'};
1.168     albertel 4624:     #if (!$namespace) {
1.620     albertel 4625:       $namespace=$env{'request.state'};
1.168     albertel 4626:     #}
                   4627:   }
                   4628:   $namespace=~s/\//\_/g;
                   4629:   $namespace=~s/\W//g;
1.620     albertel 4630:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4631:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4632:   if ($domain eq 'public' && $stuname eq 'public') {
                   4633:       $stuname=$ENV{'REMOTE_ADDR'};
                   4634:   }
1.168     albertel 4635:   my $now=time;
                   4636:   my %hash;
1.1117    foxr     4637:   my $path=LONCAPA::tempdir();
1.168     albertel 4638:   if (tie(%hash,'GDBM_File',
                   4639: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4640: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4641:     $hash{"version:$symb"}++;
                   4642:     my $version=$hash{"version:$symb"};
                   4643:     my $allkeys=''; 
                   4644:     foreach my $key (keys(%$storehash)) {
                   4645:       $allkeys.=$key.':';
1.591     albertel 4646:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4647:     }
                   4648:     $hash{"$version:$symb:timestamp"}=$now;
                   4649:     $allkeys.='timestamp';
                   4650:     $hash{"$version:keys:$symb"}=$allkeys;
                   4651:     if (untie(%hash)) {
                   4652:       return 'ok';
                   4653:     } else {
                   4654:       return "error:$!";
                   4655:     }
                   4656:   } else {
                   4657:     return "error:$!";
                   4658:   }
                   4659: }
1.167     albertel 4660: 
1.168     albertel 4661: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4662: 
1.168     albertel 4663: sub tmprestore {
                   4664:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4665: 
1.168     albertel 4666:   if (!$symb) {
                   4667:     $symb=&symbread();
1.620     albertel 4668:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4669:   }
                   4670:   $symb=escape($symb);
                   4671: 
1.620     albertel 4672:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4673: 
1.620     albertel 4674:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4675:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4676:   if ($domain eq 'public' && $stuname eq 'public') {
                   4677:       $stuname=$ENV{'REMOTE_ADDR'};
                   4678:   }
1.168     albertel 4679:   my %returnhash;
                   4680:   $namespace=~s/\//\_/g;
                   4681:   $namespace=~s/\W//g;
                   4682:   my %hash;
1.1117    foxr     4683:   my $path=LONCAPA::tempdir();
1.168     albertel 4684:   if (tie(%hash,'GDBM_File',
                   4685: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4686: 	  &GDBM_READER(),0640)) {
1.168     albertel 4687:     my $version=$hash{"version:$symb"};
                   4688:     $returnhash{'version'}=$version;
                   4689:     my $scope;
                   4690:     for ($scope=1;$scope<=$version;$scope++) {
                   4691:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4692:       my @keys=split(/:/,$vkeys);
                   4693:       my $key;
                   4694:       $returnhash{"$scope:keys"}=$vkeys;
                   4695:       foreach $key (@keys) {
1.591     albertel 4696: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4697: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4698:       }
                   4699:     }
1.168     albertel 4700:     if (!(untie(%hash))) {
                   4701:       return "error:$!";
                   4702:     }
                   4703:   } else {
                   4704:     return "error:$!";
                   4705:   }
                   4706:   return %returnhash;
1.167     albertel 4707: }
                   4708: 
1.9       www      4709: # ----------------------------------------------------------------------- Store
                   4710: 
                   4711: sub store {
1.124     www      4712:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4713:     my $home='';
                   4714: 
1.168     albertel 4715:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4716: 
1.213     www      4717:     $symb=&symbclean($symb);
1.122     albertel 4718:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4719: 
1.620     albertel 4720:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4721:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4722: 
                   4723:     &devalidate($symb,$stuname,$domain);
1.109     www      4724: 
                   4725:     $symb=escape($symb);
1.187     www      4726:     if (!$namespace) { 
1.620     albertel 4727:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4728:           return ''; 
                   4729:        } 
                   4730:     }
1.620     albertel 4731:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4732: 
                   4733:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4734:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4735: 
1.12      www      4736:     my $namevalue='';
1.800     albertel 4737:     foreach my $key (keys(%$storehash)) {
                   4738:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4739:     }
1.12      www      4740:     $namevalue=~s/\&$//;
1.187     www      4741:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4742:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4743: }
                   4744: 
1.47      www      4745: # -------------------------------------------------------------- Critical Store
                   4746: 
                   4747: sub cstore {
1.124     www      4748:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4749:     my $home='';
                   4750: 
1.168     albertel 4751:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4752: 
1.213     www      4753:     $symb=&symbclean($symb);
1.122     albertel 4754:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4755: 
1.620     albertel 4756:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4757:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4758: 
                   4759:     &devalidate($symb,$stuname,$domain);
1.109     www      4760: 
                   4761:     $symb=escape($symb);
1.187     www      4762:     if (!$namespace) { 
1.620     albertel 4763:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4764:           return ''; 
                   4765:        } 
                   4766:     }
1.620     albertel 4767:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4768: 
                   4769:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4770:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4771: 
1.47      www      4772:     my $namevalue='';
1.800     albertel 4773:     foreach my $key (keys(%$storehash)) {
                   4774:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4775:     }
1.47      www      4776:     $namevalue=~s/\&$//;
1.187     www      4777:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4778:     return critical
                   4779:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4780: }
                   4781: 
1.9       www      4782: # --------------------------------------------------------------------- Restore
                   4783: 
                   4784: sub restore {
1.124     www      4785:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4786:     my $home='';
                   4787: 
1.168     albertel 4788:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4789: 
1.122     albertel 4790:     if (!$symb) {
1.1172.2.26  raeburn  4791:         return if ($namespace eq 'courserequests');
                   4792:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4793:     } else {
1.1172.2.26  raeburn  4794:         unless ($namespace eq 'courserequests') {
                   4795:             $symb=&escape(&symbclean($symb));
                   4796:         }
1.122     albertel 4797:     }
1.188     www      4798:     if (!$namespace) { 
1.620     albertel 4799:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4800:           return ''; 
                   4801:        } 
                   4802:     }
1.620     albertel 4803:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4804:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4805:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4806:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4807: 
1.12      www      4808:     my %returnhash=();
1.800     albertel 4809:     foreach my $line (split(/\&/,$answer)) {
                   4810: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4811:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4812:     }
1.75      www      4813:     my $version;
                   4814:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4815:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4816:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4817:        }
1.75      www      4818:     }
1.13      www      4819:     return %returnhash;
1.34      www      4820: }
                   4821: 
                   4822: # ---------------------------------------------------------- Course Description
1.1118    foxr     4823: #
                   4824: #  
1.34      www      4825: 
                   4826: sub coursedescription {
1.731     albertel 4827:     my ($courseid,$args)=@_;
1.34      www      4828:     $courseid=~s/^\///;
1.49      www      4829:     $courseid=~s/\_/\//g;
1.34      www      4830:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4831:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4832:     my $normalid=$cdomain.'_'.$cnum;
                   4833:     # need to always cache even if we get errors otherwise we keep 
                   4834:     # trying and trying and trying to get the course description.
                   4835:     my %envhash=();
                   4836:     my %returnhash=();
1.731     albertel 4837:     
                   4838:     my $expiretime=600;
                   4839:     if ($env{'request.course.id'} eq $normalid) {
                   4840: 	$expiretime=120;
                   4841:     }
                   4842: 
                   4843:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4844:     if (!$args->{'freshen_cache'}
                   4845: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4846: 	foreach my $key (keys(%env)) {
                   4847: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4848: 	    my ($setting) = $1;
                   4849: 	    $returnhash{$setting} = $env{$key};
                   4850: 	}
                   4851: 	return %returnhash;
                   4852:     }
                   4853: 
1.1118    foxr     4854:     # get the data again
                   4855: 
1.731     albertel 4856:     if (!$args->{'one_time'}) {
                   4857: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4858:     }
1.811     albertel 4859: 
1.34      www      4860:     if ($chome ne 'no_host') {
1.302     albertel 4861:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4862:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4863: 	   my $username = $env{'user.name'}; # Defult username
                   4864: 	   if(defined $args->{'user'}) {
                   4865: 	       $username = $args->{'user'};
                   4866: 	   }
1.129     albertel 4867:            $returnhash{'home'}= $chome;
                   4868: 	   $returnhash{'domain'} = $cdomain;
                   4869: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4870:            if (!defined($returnhash{'type'})) {
                   4871:                $returnhash{'type'} = 'Course';
                   4872:            }
1.130     albertel 4873:            while (my ($name,$value) = each %returnhash) {
1.53      www      4874:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4875:            }
1.270     www      4876:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4877:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4878: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4879:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4880:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4881:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4882:        }
                   4883:     }
1.731     albertel 4884:     if (!$args->{'one_time'}) {
1.949     raeburn  4885: 	&appenv(\%envhash);
1.731     albertel 4886:     }
1.302     albertel 4887:     return %returnhash;
1.461     www      4888: }
                   4889: 
1.1080    raeburn  4890: sub update_released_required {
                   4891:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4892:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4893:         $cid = $env{'request.course.id'};
                   4894:         $cdom = $env{'course.'.$cid.'.domain'};
                   4895:         $cnum = $env{'course.'.$cid.'.num'};
                   4896:         $chome = $env{'course.'.$cid.'.home'};
                   4897:     }
                   4898:     if ($needsrelease) {
                   4899:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4900:         my $needsupdate;
                   4901:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4902:             $needsupdate = 1;
                   4903:         } else {
                   4904:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4905:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4906:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4907:                 $needsupdate = 1;
                   4908:             }
                   4909:         }
                   4910:         if ($needsupdate) {
                   4911:             my %needshash = (
                   4912:                              'internal.releaserequired' => $needsrelease,
                   4913:                             );
                   4914:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4915:             if ($putresult eq 'ok') {
                   4916:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4917:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4918:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4919:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4920:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4921:                 }
                   4922:             }
                   4923:         }
                   4924:     }
                   4925:     return;
                   4926: }
                   4927: 
1.461     www      4928: # -------------------------------------------------See if a user is privileged
                   4929: 
                   4930: sub privileged {
1.1172.2.23  raeburn  4931:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4932:     my $now = time;
1.1172.2.23  raeburn  4933:     my $roles;
                   4934:     if (ref($possroles) eq 'ARRAY') {
                   4935:         $roles = $possroles;
                   4936:     } else {
                   4937:         $roles = ['dc','su'];
                   4938:     }
                   4939:     if (ref($possdomains) eq 'ARRAY') {
                   4940:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   4941:         foreach my $dom (@{$possdomains}) {
                   4942:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   4943:                 (ref($privileged{$dom}) eq 'HASH')) {
                   4944:                 foreach my $role (@{$roles}) {
                   4945:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   4946:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   4947:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   4948:                             return 1 unless (($end && $end < $now) ||
                   4949:                                              ($start && $start > $now));
                   4950:                         }
                   4951:                     }
                   4952:                 }
                   4953:             }
                   4954:         }
                   4955:     } else {
                   4956:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4957:         my $now = time;
1.1170    droeschl 4958: 
1.1172.2.23  raeburn  4959:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 4960:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  4961:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   4962:                 return 1 unless ($tend && $tend < $now)
                   4963:                         or ($tstart && $tstart > $now);
1.1170    droeschl 4964:             }
1.1172.2.23  raeburn  4965:         }
                   4966:     }
1.461     www      4967:     return 0;
1.9       www      4968: }
1.1       albertel 4969: 
1.1172.2.23  raeburn  4970: sub privileged_by_domain {
                   4971:     my ($domains,$roles) = @_;
                   4972:     my %privileged = ();
                   4973:     my $cachetime = 60*60*24;
                   4974:     my $now = time;
                   4975:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   4976:         return %privileged;
                   4977:     }
                   4978:     foreach my $dom (@{$domains}) {
                   4979:         next if (ref($privileged{$dom}) eq 'HASH');
                   4980:         my $needroles;
                   4981:         foreach my $role (@{$roles}) {
                   4982:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   4983:             if (defined($cached)) {
                   4984:                 if (ref($result) eq 'HASH') {
                   4985:                     $privileged{$dom}{$role} = $result;
                   4986:                 }
                   4987:             } else {
                   4988:                 $needroles = 1;
                   4989:             }
                   4990:         }
                   4991:         if ($needroles) {
                   4992:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   4993:             $privileged{$dom} = {};
                   4994:             foreach my $server (keys(%dompersonnel)) {
                   4995:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   4996:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   4997:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   4998:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   4999:                         next if ($end && $end < $now);
                   5000:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5001:                             $dompersonnel{$server}{$item};
                   5002:                     }
                   5003:                 }
                   5004:             }
                   5005:             if (ref($privileged{$dom}) eq 'HASH') {
                   5006:                 foreach my $role (@{$roles}) {
                   5007:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5008:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5009:                     } else {
                   5010:                         my %hash = ();
                   5011:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5012:                     }
                   5013:                 }
                   5014:             }
                   5015:         }
                   5016:     }
                   5017:     return %privileged;
                   5018: }
                   5019: 
1.103     harris41 5020: # -------------------------------------------------------- Get user privileges
1.11      www      5021: 
                   5022: sub rolesinit {
1.1169    droeschl 5023:     my ($domain, $username) = @_;
                   5024:     my %userroles = ('user.login.time' => time);
                   5025:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5026: 
                   5027:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5028:     # also, blocking can be triggered by an activating timer
                   5029:     # it's saved in the user's %env.
                   5030:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5031:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5032:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5033:         %timerintchk, %timerintenv);
                   5034: 
1.1162    raeburn  5035:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5036:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5037:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5038:     }
1.1169    droeschl 5039: 
1.1162    raeburn  5040:     foreach my $key (keys(%timerinterval)) {
                   5041:         my ($cid,$rest) = split(/\0/,$key);
                   5042:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5043:     }
1.1169    droeschl 5044: 
1.11      www      5045:     my %allroles=();
1.1162    raeburn  5046:     my %allgroups=();
1.11      www      5047: 
1.1169    droeschl 5048:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5049:         my $role = $rolesdump{$area};
                   5050:         $area =~ s/\_\w\w$//;
                   5051: 
                   5052:         my ($trole, $tend, $tstart, $group_privs);
                   5053: 
                   5054:         if ($role =~ /^cr/) {
                   5055:         # Custom role, defined by a user 
                   5056:         # e.g., user.role.cr/msu/smith/mynewrole
                   5057:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5058:                 $trole = $1;
                   5059:                 ($tend, $tstart) = split('_', $2);
                   5060:             } else {
                   5061:                 $trole = $role;
                   5062:             }
                   5063:         } elsif ($role =~ m|^gr/|) {
                   5064:         # Role of member in a group, defined within a course/community
                   5065:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5066:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5067:             next if $tstart eq '-1';
                   5068:             ($trole, $group_privs) = split(/\//, $trole);
                   5069:             $group_privs = &unescape($group_privs);
                   5070:         } else {
                   5071:         # Just a normal role, defined in roles.tab
                   5072:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5073:         }
                   5074: 
                   5075:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5076:                  $username);
                   5077:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5078: 
                   5079:         # role expired or not available yet?
                   5080:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5081:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5082: 
                   5083:         next if $area eq '' or $trole eq '';
                   5084: 
                   5085:         my $spec = "$trole.$area";
                   5086:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5087: 
                   5088:         if ($trole =~ /^cr\//) {
                   5089:         # Custom role, defined by a user
                   5090:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5091:         } elsif ($trole eq 'gr') {
                   5092:         # Role of a member in a group, defined within a course/community
                   5093:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5094:             next;
                   5095:         } else {
                   5096:         # Normal role, defined in roles.tab
                   5097:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5098:         }
                   5099: 
                   5100:         my $cid = $tdomain.'_'.$trest;
                   5101:         unless ($firstaccchk{$cid}) {
                   5102:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5103:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5104:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5105:                         $coursetimerstarts{$cid}{$item}; 
                   5106:                 }
                   5107:             }
                   5108:             $firstaccchk{$cid} = 1;
                   5109:         }
                   5110:         unless ($timerintchk{$cid}) {
                   5111:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5112:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5113:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5114:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5115:                 }
1.12      www      5116:             }
1.1169    droeschl 5117:             $timerintchk{$cid} = 1;
1.191     harris41 5118:         }
1.11      www      5119:     }
1.1169    droeschl 5120: 
                   5121:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5122:         \%allroles, \%allgroups);
                   5123:     $env{'user.adv'} = $userroles{'user.adv'};
                   5124: 
1.1162    raeburn  5125:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5126: }
                   5127: 
1.567     raeburn  5128: sub set_arearole {
1.1172.2.19  raeburn  5129:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5130:     unless ($nolog) {
1.567     raeburn  5131: # log the associated role with the area
1.1172.2.19  raeburn  5132:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5133:     }
1.743     albertel 5134:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5135: }
                   5136: 
                   5137: sub custom_roleprivs {
                   5138:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5139:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5140:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5141:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5142:         my ($rdummy,$roledef)=
                   5143:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5144:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5145:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5146:             if (defined($syspriv)) {
1.1043    raeburn  5147:                 if ($trest =~ /^$match_community$/) {
                   5148:                     $syspriv =~ s/bre\&S//; 
                   5149:                 }
1.567     raeburn  5150:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5151:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5152:             }
                   5153:             if ($tdomain ne '') {
                   5154:                 if (defined($dompriv)) {
                   5155:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5156:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5157:                 }
                   5158:                 if (($trest ne '') && (defined($coursepriv))) {
                   5159:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5160:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5161:                 }
                   5162:             }
                   5163:         }
                   5164:     }
                   5165: }
                   5166: 
1.678     raeburn  5167: sub group_roleprivs {
                   5168:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5169:     my $access = 1;
                   5170:     my $now = time;
                   5171:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5172:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5173:     if ($access) {
1.811     albertel 5174:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5175:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5176:     }
                   5177: }
1.567     raeburn  5178: 
                   5179: sub standard_roleprivs {
                   5180:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5181:     if (defined($pr{$trole.':s'})) {
                   5182:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5183:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5184:     }
                   5185:     if ($tdomain ne '') {
                   5186:         if (defined($pr{$trole.':d'})) {
                   5187:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5188:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5189:         }
                   5190:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5191:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5192:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5193:         }
                   5194:     }
                   5195: }
                   5196: 
                   5197: sub set_userprivs {
1.1064    raeburn  5198:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5199:     my $author=0;
                   5200:     my $adv=0;
1.678     raeburn  5201:     my %grouproles = ();
                   5202:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5203:         my @groupkeys; 
1.1000    raeburn  5204:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5205:             push(@groupkeys,$role);
                   5206:         }
                   5207:         if (ref($groups_roles) eq 'HASH') {
                   5208:             foreach my $key (keys(%{$groups_roles})) {
                   5209:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5210:                     push(@groupkeys,$key);
                   5211:                 }
                   5212:             }
                   5213:         }
                   5214:         if (@groupkeys > 0) {
                   5215:             foreach my $role (@groupkeys) {
                   5216:                 my ($trole,$area,$sec,$extendedarea);
                   5217:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5218:                     $trole = $1;
                   5219:                     $area = $2;
                   5220:                     $sec = $3;
                   5221:                     $extendedarea = $area.$sec;
                   5222:                     if (exists($$allgroups{$area})) {
                   5223:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5224:                             my $spec = $trole.'.'.$extendedarea;
                   5225:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5226:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5227:                         }
1.678     raeburn  5228:                     }
                   5229:                 }
                   5230:             }
                   5231:         }
                   5232:     }
1.800     albertel 5233:     foreach my $group (keys(%grouproles)) {
                   5234:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5235:     }
1.800     albertel 5236:     foreach my $role (keys(%{$allroles})) {
                   5237:         my %thesepriv;
1.941     raeburn  5238:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5239:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5240:             if ($item ne '') {
                   5241:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5242:                 if ($restrictions eq '') {
                   5243:                     $thesepriv{$privilege}='F';
                   5244:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5245:                     $thesepriv{$privilege}.=$restrictions;
                   5246:                 }
                   5247:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5248:             }
                   5249:         }
                   5250:         my $thesestr='';
1.1104    raeburn  5251:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5252: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5253: 	}
                   5254:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5255:     }
                   5256:     return ($author,$adv);
                   5257: }
                   5258: 
1.994     raeburn  5259: sub role_status {
1.1104    raeburn  5260:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5261:     my @pwhere = ();
                   5262:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5263:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5264:         unless (!defined($$role) || $$role eq '') {
                   5265:             $$where=join('.',@pwhere);
                   5266:             $$trolecode=$$role.'.'.$$where;
                   5267:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5268:             $$tstatus='is';
1.1104    raeburn  5269:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5270:                 $$tstatus='future';
1.1034    raeburn  5271:                 if ($$tstart<$now) {
                   5272:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5273:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5274:                             my (%allroles,%allgroups,$group_privs,
                   5275:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5276:                             my %userroles = (
                   5277:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5278:                             );
1.1064    raeburn  5279:                             @rolecodes = ('cm'); 
1.1002    raeburn  5280:                             my $spec=$$role.'.'.$$where;
                   5281:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5282:                             if ($$role =~ /^cr\//) {
                   5283:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5284:                                 push(@rolecodes,'cr');
1.1002    raeburn  5285:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5286:                                 push(@rolecodes,$$role);
1.1002    raeburn  5287:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5288:                                                     $env{'user.name'});
1.1064    raeburn  5289:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5290:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5291:                                 $group_privs = &unescape($group_privs);
                   5292:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5293:                                 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  5294:                                 &get_groups_roles($tdomain,$trest,
                   5295:                                                   \%course_roles,\@rolecodes,
                   5296:                                                   \%groups_roles);
1.1002    raeburn  5297:                             } else {
1.1064    raeburn  5298:                                 push(@rolecodes,$$role);
1.1002    raeburn  5299:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5300:                             }
1.1064    raeburn  5301:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5302:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5303:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5304:                         }
                   5305:                     }
1.1034    raeburn  5306:                     $$tstatus = 'is';
1.1002    raeburn  5307:                 }
1.994     raeburn  5308:             }
                   5309:             if ($$tend) {
1.1104    raeburn  5310:                 if ($$tend<$update) {
1.994     raeburn  5311:                     $$tstatus='expired';
                   5312:                 } elsif ($$tend<$now) {
                   5313:                     $$tstatus='will_not';
                   5314:                 }
                   5315:             }
                   5316:         }
                   5317:     }
                   5318: }
                   5319: 
1.1104    raeburn  5320: sub get_groups_roles {
                   5321:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5322:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5323:                   (ref($rolecodes) eq 'ARRAY') && 
                   5324:                   (ref($groups_roles) eq 'HASH')); 
                   5325:     if (keys(%{$cdom_courseroles}) > 0) {
                   5326:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5327:         if ($cdom ne '' && $cnum ne '') {
                   5328:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5329:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5330:                     my $crsrole = $1;
                   5331:                     my $crssec = $2;
                   5332:                     if ($crsrole =~ /^cr/) {
                   5333:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5334:                             push(@{$rolecodes},'cr');
                   5335:                         }
                   5336:                     } else {
                   5337:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5338:                             push(@{$rolecodes},$crsrole);
                   5339:                         }
                   5340:                     }
                   5341:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5342:                     if ($crssec ne '') {
                   5343:                         $rolekey .= "/$crssec";
                   5344:                     }
                   5345:                     $rolekey .= './';
                   5346:                     $groups_roles->{$rolekey} = $rolecodes;
                   5347:                 }
                   5348:             }
                   5349:         }
                   5350:     }
                   5351:     return;
                   5352: }
                   5353: 
                   5354: sub delete_env_groupprivs {
                   5355:     my ($where,$courseroles,$possroles) = @_;
                   5356:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5357:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5358:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5359:         %{$courseroles->{$udom}} =
                   5360:             &get_my_roles('','','userroles',['active'],
                   5361:                           $possroles,[$udom],1);
                   5362:     }
                   5363:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5364:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5365:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5366:             my $area = '/'.$cdom.'/'.$cnum;
                   5367:             my $privkey = "user.priv.$crsrole.$area";
                   5368:             if ($crssec ne '') {
                   5369:                 $privkey .= '/'.$crssec;
                   5370:             }
                   5371:             $privkey .= ".$area/$group";
                   5372:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5373:         }
                   5374:     }
                   5375:     return;
                   5376: }
                   5377: 
1.994     raeburn  5378: sub check_adhoc_privs {
1.1104    raeburn  5379:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5380:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5381:     my $setprivs;
1.994     raeburn  5382:     if ($env{$cckey}) {
                   5383:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5384:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5385:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5386:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5387:             $setprivs = 1;
1.994     raeburn  5388:         }
                   5389:     } else {
1.1088    raeburn  5390:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5391:         $setprivs = 1;
1.994     raeburn  5392:     }
1.1172.2.9  raeburn  5393:     return $setprivs;
1.994     raeburn  5394: }
                   5395: 
                   5396: sub set_adhoc_privileges {
                   5397: # role can be cc or ca
1.1088    raeburn  5398:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5399:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5400:     my $spec = $role.'.'.$area;
                   5401:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5402:                                   $env{'user.name'},1);
1.994     raeburn  5403:     my %ccrole = ();
                   5404:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5405:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5406:     &appenv(\%userroles,[$role,'cm']);
                   5407:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5408:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5409:         &appenv( {'request.role'        => $spec,
                   5410:                   'request.role.domain' => $dcdom,
                   5411:                   'request.course.sec'  => ''
                   5412:                  }
                   5413:                );
                   5414:         my $tadv=0;
                   5415:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5416:         &appenv({'request.role.adv'    => $tadv});
                   5417:     }
1.994     raeburn  5418: }
                   5419: 
1.12      www      5420: # --------------------------------------------------------------- get interface
                   5421: 
                   5422: sub get {
1.131     albertel 5423:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5424:    my $items='';
1.800     albertel 5425:    foreach my $item (@$storearr) {
                   5426:        $items.=&escape($item).'&';
1.191     harris41 5427:    }
1.12      www      5428:    $items=~s/\&$//;
1.620     albertel 5429:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5430:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5431:    my $uhome=&homeserver($uname,$udomain);
                   5432: 
1.133     albertel 5433:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5434:    my @pairs=split(/\&/,$rep);
1.273     albertel 5435:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5436:      return @pairs;
                   5437:    }
1.15      www      5438:    my %returnhash=();
1.42      www      5439:    my $i=0;
1.800     albertel 5440:    foreach my $item (@$storearr) {
                   5441:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5442:       $i++;
1.191     harris41 5443:    }
1.15      www      5444:    return %returnhash;
1.27      www      5445: }
                   5446: 
                   5447: # --------------------------------------------------------------- del interface
                   5448: 
                   5449: sub del {
1.133     albertel 5450:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5451:    my $items='';
1.800     albertel 5452:    foreach my $item (@$storearr) {
                   5453:        $items.=&escape($item).'&';
1.191     harris41 5454:    }
1.984     neumanie 5455: 
1.27      www      5456:    $items=~s/\&$//;
1.620     albertel 5457:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5458:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5459:    my $uhome=&homeserver($uname,$udomain);
                   5460:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5461: }
                   5462: 
                   5463: # -------------------------------------------------------------- dump interface
                   5464: 
1.1172.2.22  raeburn  5465: sub unserialize {
                   5466:     my ($rep, $escapedkeys) = @_;
                   5467: 
                   5468:     return {} if $rep =~ /^error/;
                   5469: 
                   5470:     my %returnhash=();
                   5471:     foreach my $item (split(/\&/,$rep)) {
                   5472:         my ($key, $value) = split(/=/, $item, 2);
                   5473:         $key = unescape($key) unless $escapedkeys;
                   5474:         next if $key =~ /^error: 2 /;
                   5475:         $returnhash{$key} = &thaw_unescape($value);
                   5476:     }
                   5477:     return \%returnhash;
                   5478: }
                   5479: 
                   5480: # see Lond::dump_with_regexp
                   5481: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5482: sub dump {
1.1172.2.22  raeburn  5483:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5484:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5485:     if (!$uname) { $uname=$env{'user.name'}; }
                   5486:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5487: 
1.1172.2.22  raeburn  5488:     my $reply;
                   5489:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5490:         # user is hosted on this machine
                   5491:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5492:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5493:         return %{&unserialize($reply, $escapedkeys)};
                   5494:     }
1.755     albertel 5495:     if ($regexp) {
                   5496: 	$regexp=&escape($regexp);
                   5497:     } else {
                   5498: 	$regexp='.';
                   5499:     }
1.1166    raeburn  5500:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5501:     my @pairs=split(/\&/,$rep);
                   5502:     my %returnhash=();
1.1098    foxr     5503:     if (!($rep =~ /^error/ )) {
                   5504: 	foreach my $item (@pairs) {
                   5505: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5506:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5507: 	    next if ($key =~ /^error: 2 /);
                   5508: 	    $returnhash{$key}=&thaw_unescape($value);
                   5509: 	}
1.755     albertel 5510:     }
                   5511:     return %returnhash;
1.407     www      5512: }
                   5513: 
1.1098    foxr     5514: 
1.717     albertel 5515: # --------------------------------------------------------- dumpstore interface
                   5516: 
                   5517: sub dumpstore {
                   5518:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5519:    # same as dump but keys must be escaped. They may contain colon separated
                   5520:    # lists of values that may themself contain colons (e.g. symbs).
                   5521:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5522: }
                   5523: 
1.407     www      5524: # -------------------------------------------------------------- keys interface
                   5525: 
                   5526: sub getkeys {
                   5527:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5528:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5529:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5530:    my $uhome=&homeserver($uname,$udomain);
                   5531:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5532:    my @keyarray=();
1.800     albertel 5533:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5534:       next if ($key =~ /^error: 2 /);
1.800     albertel 5535:       push(@keyarray,&unescape($key));
1.407     www      5536:    }
                   5537:    return @keyarray;
1.318     matthew  5538: }
                   5539: 
1.319     matthew  5540: # --------------------------------------------------------------- currentdump
                   5541: sub currentdump {
1.328     matthew  5542:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5543:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5544:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5545:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5546:    my $uhome = &homeserver($sname,$sdom);
                   5547:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5548:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5549:    #
1.318     matthew  5550:    my %returnhash=();
1.319     matthew  5551:    #
                   5552:    if ($rep eq "unknown_cmd") { 
                   5553:        # an old lond will not know currentdump
                   5554:        # Do a dump and make it look like a currentdump
1.822     albertel 5555:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5556:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5557:        my %hash = @tmp;
                   5558:        @tmp=();
1.424     matthew  5559:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5560:    } else {
                   5561:        my @pairs=split(/\&/,$rep);
1.800     albertel 5562:        foreach my $pair (@pairs) {
                   5563:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5564:            my ($symb,$param) = split(/:/,$key);
                   5565:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5566:                                                         &thaw_unescape($value);
1.319     matthew  5567:        }
1.191     harris41 5568:    }
1.12      www      5569:    return %returnhash;
1.424     matthew  5570: }
                   5571: 
                   5572: sub convert_dump_to_currentdump{
                   5573:     my %hash = %{shift()};
                   5574:     my %returnhash;
                   5575:     # Code ripped from lond, essentially.  The only difference
                   5576:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5577:     # we might run in to problems with parameter names =~ /^v\./
                   5578:     while (my ($key,$value) = each(%hash)) {
                   5579:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5580: 	$symb  = &unescape($symb);
                   5581: 	$param = &unescape($param);
1.424     matthew  5582:         next if ($v eq 'version' || $symb eq 'keys');
                   5583:         next if (exists($returnhash{$symb}) &&
                   5584:                  exists($returnhash{$symb}->{$param}) &&
                   5585:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5586:         $returnhash{$symb}->{$param}=$value;
                   5587:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5588:     }
                   5589:     #
                   5590:     # Remove all of the keys in the hashes which keep track of
                   5591:     # the version of the parameter.
                   5592:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5593:         # use a foreach because we are going to delete from the hash.
                   5594:         foreach my $key (keys(%$param_hash)) {
                   5595:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5596:         }
                   5597:     }
                   5598:     return \%returnhash;
1.12      www      5599: }
                   5600: 
1.627     albertel 5601: # ------------------------------------------------------ critical inc interface
                   5602: 
                   5603: sub cinc {
                   5604:     return &inc(@_,'critical');
                   5605: }
                   5606: 
1.449     matthew  5607: # --------------------------------------------------------------- inc interface
                   5608: 
                   5609: sub inc {
1.627     albertel 5610:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5611:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5612:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5613:     my $uhome=&homeserver($uname,$udomain);
                   5614:     my $items='';
                   5615:     if (! ref($store)) {
                   5616:         # got a single value, so use that instead
                   5617:         $items = &escape($store).'=&';
                   5618:     } elsif (ref($store) eq 'SCALAR') {
                   5619:         $items = &escape($$store).'=&';        
                   5620:     } elsif (ref($store) eq 'ARRAY') {
                   5621:         $items = join('=&',map {&escape($_);} @{$store});
                   5622:     } elsif (ref($store) eq 'HASH') {
                   5623:         while (my($key,$value) = each(%{$store})) {
                   5624:             $items.= &escape($key).'='.&escape($value).'&';
                   5625:         }
                   5626:     }
                   5627:     $items=~s/\&$//;
1.627     albertel 5628:     if ($critical) {
                   5629: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5630:     } else {
                   5631: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5632:     }
1.449     matthew  5633: }
                   5634: 
1.12      www      5635: # --------------------------------------------------------------- put interface
                   5636: 
                   5637: sub put {
1.134     albertel 5638:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5640:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5641:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5642:    my $items='';
1.800     albertel 5643:    foreach my $item (keys(%$storehash)) {
                   5644:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5645:    }
1.12      www      5646:    $items=~s/\&$//;
1.134     albertel 5647:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5648: }
                   5649: 
1.631     albertel 5650: # ------------------------------------------------------------ newput interface
                   5651: 
                   5652: sub newput {
                   5653:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5655:    if (!$uname) { $uname=$env{'user.name'}; }
                   5656:    my $uhome=&homeserver($uname,$udomain);
                   5657:    my $items='';
                   5658:    foreach my $key (keys(%$storehash)) {
                   5659:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5660:    }
                   5661:    $items=~s/\&$//;
                   5662:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5663: }
                   5664: 
                   5665: # ---------------------------------------------------------  putstore interface
                   5666: 
1.524     raeburn  5667: sub putstore {
1.715     albertel 5668:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5669:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5670:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5671:    my $uhome=&homeserver($uname,$udomain);
                   5672:    my $items='';
1.715     albertel 5673:    foreach my $key (keys(%$storehash)) {
                   5674:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5675:    }
1.715     albertel 5676:    $items=~s/\&$//;
1.716     albertel 5677:    my $esc_symb=&escape($symb);
                   5678:    my $esc_v=&escape($version);
1.715     albertel 5679:    my $reply =
1.716     albertel 5680:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5681: 	      $uhome);
                   5682:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5683:        # gfall back to way things use to be done
1.715     albertel 5684:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5685: 			    $uname);
1.524     raeburn  5686:    }
1.715     albertel 5687:    return $reply;
                   5688: }
                   5689: 
                   5690: sub old_putstore {
1.716     albertel 5691:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5692:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5693:     if (!$uname) { $uname=$env{'user.name'}; }
                   5694:     my $uhome=&homeserver($uname,$udomain);
                   5695:     my %newstorehash;
1.800     albertel 5696:     foreach my $item (keys(%$storehash)) {
                   5697: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5698: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5699:     }
                   5700:     my $items='';
                   5701:     my %allitems = ();
1.800     albertel 5702:     foreach my $item (keys(%newstorehash)) {
                   5703: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5704: 	    my $key = $1.':keys:'.$2;
                   5705: 	    $allitems{$key} .= $3.':';
                   5706: 	}
1.800     albertel 5707: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5708:     }
1.800     albertel 5709:     foreach my $item (keys(%allitems)) {
                   5710: 	$allitems{$item} =~ s/\:$//;
                   5711: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5712:     }
                   5713:     $items=~s/\&$//;
                   5714:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5715: }
                   5716: 
1.47      www      5717: # ------------------------------------------------------ critical put interface
                   5718: 
                   5719: sub cput {
1.134     albertel 5720:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5721:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5722:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5723:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5724:    my $items='';
1.800     albertel 5725:    foreach my $item (keys(%$storehash)) {
                   5726:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5727:    }
1.47      www      5728:    $items=~s/\&$//;
1.134     albertel 5729:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5730: }
                   5731: 
                   5732: # -------------------------------------------------------------- eget interface
                   5733: 
                   5734: sub eget {
1.133     albertel 5735:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5736:    my $items='';
1.800     albertel 5737:    foreach my $item (@$storearr) {
                   5738:        $items.=&escape($item).'&';
1.191     harris41 5739:    }
1.12      www      5740:    $items=~s/\&$//;
1.620     albertel 5741:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5742:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5743:    my $uhome=&homeserver($uname,$udomain);
                   5744:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5745:    my @pairs=split(/\&/,$rep);
                   5746:    my %returnhash=();
1.42      www      5747:    my $i=0;
1.800     albertel 5748:    foreach my $item (@$storearr) {
                   5749:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5750:       $i++;
1.191     harris41 5751:    }
1.12      www      5752:    return %returnhash;
                   5753: }
                   5754: 
1.667     albertel 5755: # ------------------------------------------------------------ tmpput interface
                   5756: sub tmpput {
1.802     raeburn  5757:     my ($storehash,$server,$context)=@_;
1.667     albertel 5758:     my $items='';
1.800     albertel 5759:     foreach my $item (keys(%$storehash)) {
                   5760: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5761:     }
                   5762:     $items=~s/\&$//;
1.802     raeburn  5763:     if (defined($context)) {
                   5764:         $items .= ':'.&escape($context);
                   5765:     }
1.667     albertel 5766:     return &reply("tmpput:$items",$server);
                   5767: }
                   5768: 
                   5769: # ------------------------------------------------------------ tmpget interface
                   5770: sub tmpget {
1.688     albertel 5771:     my ($token,$server)=@_;
                   5772:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5773:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5774:     my %returnhash;
                   5775:     foreach my $item (split(/\&/,$rep)) {
                   5776: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5777:         next if ($key =~ /^error: 2 /);
1.667     albertel 5778: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5779:     }
                   5780:     return %returnhash;
                   5781: }
                   5782: 
1.1113    raeburn  5783: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5784: sub tmpdel {
                   5785:     my ($token,$server)=@_;
                   5786:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5787:     return &reply("tmpdel:$token",$server);
                   5788: }
                   5789: 
1.1172.2.13  raeburn  5790: # ------------------------------------------------------------ get_timebased_id
                   5791: 
                   5792: sub get_timebased_id {
                   5793:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5794:         $maxtries) = @_;
                   5795:     my ($newid,$error,$dellock);
                   5796:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5797:         return ('','ok','invalid call to get suffix');
                   5798:     }
                   5799: 
                   5800: # set defaults for any optional args for which values were not supplied
                   5801:     if ($who eq '') {
                   5802:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5803:     }
                   5804:     if (!$locktries) {
                   5805:         $locktries = 3;
                   5806:     }
                   5807:     if (!$maxtries) {
                   5808:         $maxtries = 10;
                   5809:     }
                   5810: 
                   5811:     if (($cdom eq '') || ($cnum eq '')) {
                   5812:         if ($env{'request.course.id'}) {
                   5813:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5814:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5815:         }
                   5816:         if (($cdom eq '') || ($cnum eq '')) {
                   5817:             return ('','ok','call to get suffix not in course context');
                   5818:         }
                   5819:     }
                   5820: 
                   5821: # construct locking item
                   5822:     my $lockhash = {
                   5823:                       $prefix."\0".'locked_'.$keyid => $who,
                   5824:                    };
                   5825:     my $tries = 0;
                   5826: 
                   5827: # attempt to get lock on nohist_$namespace file
                   5828:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5829:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5830:         $tries ++;
                   5831:         sleep 1;
                   5832:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5833:     }
                   5834: 
                   5835: # attempt to get unique identifier, based on current timestamp
                   5836:     if ($gotlock eq 'ok') {
                   5837:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5838:         my $id = time;
                   5839:         $newid = $id;
                   5840:         my $idtries = 0;
                   5841:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5842:             if ($idtype eq 'concat') {
                   5843:                 $newid = $id.$idtries;
                   5844:             } else {
                   5845:                 $newid ++;
                   5846:             }
                   5847:             $idtries ++;
                   5848:         }
                   5849:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5850:             my %new_item =  (
                   5851:                               $prefix."\0".$newid => $who,
                   5852:                             );
                   5853:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5854:                                                  $cdom,$cnum);
                   5855:             if ($putresult ne 'ok') {
                   5856:                 undef($newid);
                   5857:                 $error = 'error saving new item: '.$putresult;
                   5858:             }
                   5859:         } else {
                   5860:              $error = ('error: no unique suffix available for the new item ');
                   5861:         }
                   5862: #  remove lock
                   5863:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5864:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5865:     } else {
                   5866:         $error = "error: could not obtain lockfile\n";
                   5867:         $dellock = 'ok';
                   5868:     }
                   5869:     return ($newid,$dellock,$error);
                   5870: }
                   5871: 
1.765     albertel 5872: # -------------------------------------------------- portfolio access checking
                   5873: 
                   5874: sub portfolio_access {
1.766     albertel 5875:     my ($requrl) = @_;
1.765     albertel 5876:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5877:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5878:     if ($result) {
                   5879:         my %setters;
                   5880:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5881:             my ($startblock,$endblock) =
                   5882:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5883:             if ($startblock && $endblock) {
                   5884:                 return 'B';
                   5885:             }
                   5886:         } else {
                   5887:             my ($startblock,$endblock) =
                   5888:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5889:             if ($startblock && $endblock) {
                   5890:                 return 'B';
                   5891:             }
                   5892:         }
                   5893:     }
1.765     albertel 5894:     if ($result eq 'ok') {
1.766     albertel 5895:        return 'F';
1.765     albertel 5896:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5897:        return 'A';
1.765     albertel 5898:     }
1.766     albertel 5899:     return '';
1.765     albertel 5900: }
                   5901: 
                   5902: sub get_portfolio_access {
1.767     albertel 5903:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5904: 
                   5905:     if (!ref($access_hash)) {
                   5906: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5907: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5908: 						   $file_name);
                   5909: 	$access_hash = $access_controls{$file_name};
                   5910:     }
                   5911: 
1.765     albertel 5912:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5913:     my $now = time;
                   5914:     if (ref($access_hash) eq 'HASH') {
                   5915:         foreach my $key (keys(%{$access_hash})) {
                   5916:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5917:             if ($start > $now) {
                   5918:                 next;
                   5919:             }
                   5920:             if ($end && $end<$now) {
                   5921:                 next;
                   5922:             }
                   5923:             if ($scope eq 'public') {
                   5924:                 $public = $key;
                   5925:                 last;
                   5926:             } elsif ($scope eq 'guest') {
                   5927:                 $guest = $key;
                   5928:             } elsif ($scope eq 'domains') {
                   5929:                 push(@domains,$key);
                   5930:             } elsif ($scope eq 'users') {
                   5931:                 push(@users,$key);
                   5932:             } elsif ($scope eq 'course') {
                   5933:                 push(@courses,$key);
                   5934:             } elsif ($scope eq 'group') {
                   5935:                 push(@groups,$key);
                   5936:             }
                   5937:         }
                   5938:         if ($public) {
                   5939:             return 'ok';
                   5940:         }
                   5941:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5942:             if ($guest) {
                   5943:                 return $guest;
                   5944:             }
                   5945:         } else {
                   5946:             if (@domains > 0) {
                   5947:                 foreach my $domkey (@domains) {
                   5948:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5949:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5950:                             return 'ok';
                   5951:                         }
                   5952:                     }
                   5953:                 }
                   5954:             }
                   5955:             if (@users > 0) {
                   5956:                 foreach my $userkey (@users) {
1.865     raeburn  5957:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5958:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5959:                             if (ref($item) eq 'HASH') {
                   5960:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5961:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5962:                                     return 'ok';
                   5963:                                 }
                   5964:                             }
                   5965:                         }
                   5966:                     } 
1.765     albertel 5967:                 }
                   5968:             }
                   5969:             my %roleshash;
                   5970:             my @courses_and_groups = @courses;
                   5971:             push(@courses_and_groups,@groups); 
                   5972:             if (@courses_and_groups > 0) {
                   5973:                 my (%allgroups,%allroles); 
                   5974:                 my ($start,$end,$role,$sec,$group);
                   5975:                 foreach my $envkey (%env) {
1.1060    raeburn  5976:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5977:                         my $cid = $2.'_'.$3; 
                   5978:                         if ($1 eq 'gr') {
                   5979:                             $group = $4;
                   5980:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5981:                         } else {
                   5982:                             if ($4 eq '') {
                   5983:                                 $sec = 'none';
                   5984:                             } else {
                   5985:                                 $sec = $4;
                   5986:                             }
                   5987:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5988:                         }
1.811     albertel 5989:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5990:                         my $cid = $2.'_'.$3;
                   5991:                         if ($4 eq '') {
                   5992:                             $sec = 'none';
                   5993:                         } else {
                   5994:                             $sec = $4;
                   5995:                         }
                   5996:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5997:                     }
                   5998:                 }
                   5999:                 if (keys(%allroles) == 0) {
                   6000:                     return;
                   6001:                 }
                   6002:                 foreach my $key (@courses_and_groups) {
                   6003:                     my %content = %{$$access_hash{$key}};
                   6004:                     my $cnum = $content{'number'};
                   6005:                     my $cdom = $content{'domain'};
                   6006:                     my $cid = $cdom.'_'.$cnum;
                   6007:                     if (!exists($allroles{$cid})) {
                   6008:                         next;
                   6009:                     }    
                   6010:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6011:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6012:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6013:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6014:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6015:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6016:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6017:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6018:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6019:                                         if (grep/^all$/,@sections) {
                   6020:                                             return 'ok';
                   6021:                                         } else {
                   6022:                                             if (grep/^$sec$/,@sections) {
                   6023:                                                 return 'ok';
                   6024:                                             }
                   6025:                                         }
                   6026:                                     }
                   6027:                                 }
                   6028:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6029:                                     if (grep/^none$/,@groups) {
                   6030:                                         return 'ok';
                   6031:                                     }
                   6032:                                 } else {
                   6033:                                     if (grep/^all$/,@groups) {
                   6034:                                         return 'ok';
                   6035:                                     } 
                   6036:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6037:                                         if (grep/^$group$/,@groups) {
                   6038:                                             return 'ok';
                   6039:                                         }
                   6040:                                     }
                   6041:                                 } 
                   6042:                             }
                   6043:                         }
                   6044:                     }
                   6045:                 }
                   6046:             }
                   6047:             if ($guest) {
                   6048:                 return $guest;
                   6049:             }
                   6050:         }
                   6051:     }
                   6052:     return;
                   6053: }
                   6054: 
                   6055: sub course_group_datechecker {
                   6056:     my ($dates,$now,$status) = @_;
                   6057:     my ($start,$end) = split(/\./,$dates);
                   6058:     if (!$start && !$end) {
                   6059:         return 'ok';
                   6060:     }
                   6061:     if (grep/^active$/,@{$status}) {
                   6062:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6063:             return 'ok';
                   6064:         }
                   6065:     }
                   6066:     if (grep/^previous$/,@{$status}) {
                   6067:         if ($end > $now ) {
                   6068:             return 'ok';
                   6069:         }
                   6070:     }
                   6071:     if (grep/^future$/,@{$status}) {
                   6072:         if ($start > $now) {
                   6073:             return 'ok';
                   6074:         }
                   6075:     }
                   6076:     return; 
                   6077: }
                   6078: 
                   6079: sub parse_portfolio_url {
                   6080:     my ($url) = @_;
                   6081: 
                   6082:     my ($type,$udom,$unum,$group,$file_name);
                   6083:     
1.823     albertel 6084:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6085: 	$type = 1;
                   6086:         $udom = $1;
                   6087:         $unum = $2;
                   6088:         $file_name = $3;
1.823     albertel 6089:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6090: 	$type = 2;
                   6091:         $udom = $1;
                   6092:         $unum = $2;
                   6093:         $group = $3;
                   6094:         $file_name = $3.'/'.$4;
                   6095:     }
                   6096:     if (wantarray) {
                   6097: 	return ($type,$udom,$unum,$file_name,$group);
                   6098:     }
                   6099:     return $type;
                   6100: }
                   6101: 
                   6102: sub is_portfolio_url {
                   6103:     my ($url) = @_;
                   6104:     return scalar(&parse_portfolio_url($url));
                   6105: }
                   6106: 
1.798     raeburn  6107: sub is_portfolio_file {
                   6108:     my ($file) = @_;
1.820     raeburn  6109:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6110:         return 1;
                   6111:     }
                   6112:     return;
                   6113: }
                   6114: 
1.976     raeburn  6115: sub usertools_access {
1.1084    raeburn  6116:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6117:     my ($access,%tools);
                   6118:     if ($context eq '') {
                   6119:         $context = 'tools';
                   6120:     }
                   6121:     if ($context eq 'requestcourses') {
                   6122:         %tools = (
                   6123:                       official   => 1,
                   6124:                       unofficial => 1,
1.1006    raeburn  6125:                       community  => 1,
1.985     raeburn  6126:                  );
1.1172.2.9  raeburn  6127:     } elsif ($context eq 'requestauthor') {
                   6128:         %tools = (
                   6129:                       requestauthor => 1,
                   6130:                  );
1.985     raeburn  6131:     } else {
                   6132:         %tools = (
                   6133:                       aboutme   => 1,
                   6134:                       blog      => 1,
1.1172.2.6  raeburn  6135:                       webdav    => 1,
1.985     raeburn  6136:                       portfolio => 1,
                   6137:                  );
                   6138:     }
1.976     raeburn  6139:     return if (!defined($tools{$tool}));
                   6140: 
                   6141:     if ((!defined($udom)) || (!defined($uname))) {
                   6142:         $udom = $env{'user.domain'};
                   6143:         $uname = $env{'user.name'};
                   6144:     }
                   6145: 
1.978     raeburn  6146:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6147:         if ($action ne 'reload') {
1.985     raeburn  6148:             if ($context eq 'requestcourses') {
                   6149:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6150:             } elsif ($context eq 'requestauthor') {
                   6151:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6152:             } else {
                   6153:                 return $env{'environment.availabletools.'.$tool};
                   6154:             }
                   6155:         }
1.976     raeburn  6156:     }
                   6157: 
1.1172.2.9  raeburn  6158:     my ($toolstatus,$inststatus,$envkey);
                   6159:     if ($context eq 'requestauthor') {
                   6160:         $envkey = $context;
                   6161:     } else {
                   6162:         $envkey = $context.'.'.$tool;
                   6163:     }
1.976     raeburn  6164: 
1.985     raeburn  6165:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6166:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6167:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6168:         $inststatus = $env{'environment.inststatus'};
                   6169:     } else {
1.1084    raeburn  6170:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6171:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6172:             $inststatus = $userenvref->{'inststatus'};
                   6173:         } else {
1.1172.2.9  raeburn  6174:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6175:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6176:             $inststatus = $userenv{'inststatus'};
                   6177:         }
1.976     raeburn  6178:     }
                   6179: 
                   6180:     if ($toolstatus ne '') {
                   6181:         if ($toolstatus) {
                   6182:             $access = 1;
                   6183:         } else {
                   6184:             $access = 0;
                   6185:         }
                   6186:         return $access;
                   6187:     }
                   6188: 
1.1084    raeburn  6189:     my ($is_adv,%domdef);
                   6190:     if (ref($is_advref) eq 'HASH') {
                   6191:         $is_adv = $is_advref->{'is_adv'};
                   6192:     } else {
                   6193:         $is_adv = &is_advanced_user($udom,$uname);
                   6194:     }
                   6195:     if (ref($domdefref) eq 'HASH') {
                   6196:         %domdef = %{$domdefref};
                   6197:     } else {
                   6198:         %domdef = &get_domain_defaults($udom);
                   6199:     }
1.976     raeburn  6200:     if (ref($domdef{$tool}) eq 'HASH') {
                   6201:         if ($is_adv) {
                   6202:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6203:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6204:                     $access = 1;
                   6205:                 } else {
                   6206:                     $access = 0;
                   6207:                 }
                   6208:                 return $access;
                   6209:             }
                   6210:         }
                   6211:         if ($inststatus ne '') {
                   6212:             my ($hasaccess,$hasnoaccess);
                   6213:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6214:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6215:                     if ($domdef{$tool}{$affiliation}) {
                   6216:                         $hasaccess = 1;
                   6217:                     } else {
                   6218:                         $hasnoaccess = 1;
                   6219:                     }
                   6220:                 }
                   6221:             }
                   6222:             if ($hasaccess || $hasnoaccess) {
                   6223:                 if ($hasaccess) {
                   6224:                     $access = 1;
                   6225:                 } elsif ($hasnoaccess) {
                   6226:                     $access = 0; 
                   6227:                 }
                   6228:                 return $access;
                   6229:             }
                   6230:         } else {
                   6231:             if ($domdef{$tool}{'default'} ne '') {
                   6232:                 if ($domdef{$tool}{'default'}) {
                   6233:                     $access = 1;
                   6234:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6235:                     $access = 0;
                   6236:                 }
                   6237:                 return $access;
                   6238:             }
                   6239:         }
                   6240:     } else {
1.1172.2.6  raeburn  6241:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6242:             $access = 1;
                   6243:         } else {
                   6244:             $access = 0;
                   6245:         }
1.976     raeburn  6246:         return $access;
                   6247:     }
                   6248: }
                   6249: 
1.1050    raeburn  6250: sub is_course_owner {
                   6251:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6252:     if (($udom eq '') || ($uname eq '')) {
                   6253:         $udom = $env{'user.domain'};
                   6254:         $uname = $env{'user.name'};
                   6255:     }
                   6256:     unless (($udom eq '') || ($uname eq '')) {
                   6257:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6258:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6259:                 return 1;
                   6260:             } else {
                   6261:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6262:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6263:                     return 1;
                   6264:                 }
                   6265:             }
                   6266:         }
                   6267:     }
                   6268:     return;
                   6269: }
                   6270: 
1.976     raeburn  6271: sub is_advanced_user {
                   6272:     my ($udom,$uname) = @_;
1.1085    raeburn  6273:     if ($udom ne '' && $uname ne '') {
                   6274:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6275:             if (wantarray) {
                   6276:                 return ($env{'user.adv'},$env{'user.author'});
                   6277:             } else {
                   6278:                 return $env{'user.adv'};
                   6279:             }
1.1085    raeburn  6280:         }
                   6281:     }
1.976     raeburn  6282:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6283:     my %allroles;
1.1128    raeburn  6284:     my ($is_adv,$is_author);
1.976     raeburn  6285:     foreach my $role (keys(%roleshash)) {
                   6286:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6287:         my $area = '/'.$tdomain.'/'.$trest;
                   6288:         if ($sec ne '') {
                   6289:             $area .= '/'.$sec;
                   6290:         }
                   6291:         if (($area ne '') && ($trole ne '')) {
                   6292:             my $spec=$trole.'.'.$area;
                   6293:             if ($trole =~ /^cr\//) {
                   6294:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6295:             } elsif ($trole ne 'gr') {
                   6296:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6297:             }
1.1128    raeburn  6298:             if ($trole eq 'au') {
                   6299:                 $is_author = 1;
                   6300:             }
1.976     raeburn  6301:         }
                   6302:     }
                   6303:     foreach my $role (keys(%allroles)) {
                   6304:         last if ($is_adv);
                   6305:         foreach my $item (split(/:/,$allroles{$role})) {
                   6306:             if ($item ne '') {
                   6307:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6308:                 if ($privilege eq 'adv') {
                   6309:                     $is_adv = 1;
                   6310:                     last;
                   6311:                 }
                   6312:             }
                   6313:         }
                   6314:     }
1.1128    raeburn  6315:     if (wantarray) {
                   6316:         return ($is_adv,$is_author);
                   6317:     }
1.976     raeburn  6318:     return $is_adv;
                   6319: }
1.798     raeburn  6320: 
1.1035    raeburn  6321: sub check_can_request {
1.1036    raeburn  6322:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6323:     my $canreq = 0;
                   6324:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6325:     my @options = ('approval','validate','autolimit');
                   6326:     my $optregex = join('|',@options);
                   6327:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6328:         foreach my $type (@{$types}) {
                   6329:             if (&usertools_access($env{'user.name'},
                   6330:                                   $env{'user.domain'},
                   6331:                                   $type,undef,'requestcourses')) {
                   6332:                 $canreq ++;
1.1036    raeburn  6333:                 if (ref($request_domains) eq 'HASH') {
                   6334:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6335:                 }
1.1035    raeburn  6336:                 if ($dom eq $env{'user.domain'}) {
                   6337:                     $can_request->{$type} = 1;
                   6338:                 }
                   6339:             }
                   6340:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6341:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6342:                 if (@curr > 0) {
1.1036    raeburn  6343:                     foreach my $item (@curr) {
                   6344:                         if (ref($request_domains) eq 'HASH') {
                   6345:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6346:                             if ($otherdom ne '') {
                   6347:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6348:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6349:                                         push(@{$request_domains->{$type}},$otherdom);
                   6350:                                     }
                   6351:                                 } else {
                   6352:                                     push(@{$request_domains->{$type}},$otherdom);
                   6353:                                 }
                   6354:                             }
                   6355:                         }
                   6356:                     }
                   6357:                     unless($dom eq $env{'user.domain'}) {
                   6358:                         $canreq ++;
1.1035    raeburn  6359:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6360:                             $can_request->{$type} = 1;
                   6361:                         }
                   6362:                     }
                   6363:                 }
                   6364:             }
                   6365:         }
                   6366:     }
                   6367:     return $canreq;
                   6368: }
                   6369: 
1.341     www      6370: # ---------------------------------------------- Custom access rule evaluation
                   6371: 
                   6372: sub customaccess {
                   6373:     my ($priv,$uri)=@_;
1.807     albertel 6374:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6375:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6376:     $udom = &LONCAPA::clean_domain($udom);
                   6377:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6378:     my $access=0;
1.800     albertel 6379:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6380: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6381: 	if ($type eq 'user') {
                   6382: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6383: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6384: 		if ($tdom) {
                   6385: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6386: 		}
1.896     albertel 6387: 		if ($tuname) {
                   6388: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6389: 		}
                   6390: 		$access=($effect eq 'allow');
                   6391: 		last;
                   6392: 	    }
                   6393: 	} else {
                   6394: 	    if ($role) {
                   6395: 		if ($role ne $urole) { next; }
                   6396: 	    }
                   6397: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6398: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6399: 		if ($tdom) {
                   6400: 		    if ($tdom ne $udom) { next; }
                   6401: 		}
                   6402: 		if ($tcrs) {
                   6403: 		    if ($tcrs ne $ucrs) { next; }
                   6404: 		}
                   6405: 		if ($tsec) {
                   6406: 		    if ($tsec ne $usec) { next; }
                   6407: 		}
                   6408: 		$access=($effect eq 'allow');
                   6409: 		last;
                   6410: 	    }
                   6411: 	    if ($realm eq '' && $role eq '') {
                   6412: 		$access=($effect eq 'allow');
                   6413: 	    }
1.402     bowersj2 6414: 	}
1.341     www      6415:     }
                   6416:     return $access;
                   6417: }
                   6418: 
1.103     harris41 6419: # ------------------------------------------------- Check for a user privilege
1.12      www      6420: 
                   6421: sub allowed {
1.810     raeburn  6422:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6423:     my $ver_orguri=$uri;
1.439     www      6424:     $uri=&deversion($uri);
1.152     www      6425:     my $orguri=$uri;
1.52      www      6426:     $uri=&declutter($uri);
1.809     raeburn  6427: 
1.810     raeburn  6428:     if ($priv eq 'evb') {
                   6429: # Evade communication block restrictions for specified role in a course
                   6430:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6431:             return $1;
                   6432:         } else {
                   6433:             return;
                   6434:         }
                   6435:     }
                   6436: 
1.620     albertel 6437:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6438: # Free bre access to adm and meta resources
1.775     albertel 6439:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6440: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6441: 	&& ($priv eq 'bre')) {
1.14      www      6442: 	return 'F';
1.159     www      6443:     }
                   6444: 
1.545     banghart 6445: # Free bre access to user's own portfolio contents
1.714     raeburn  6446:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6447:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6448: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6449:         my %setters;
                   6450:         my ($startblock,$endblock) = 
                   6451:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6452:         if ($startblock && $endblock) {
                   6453:             return 'B';
                   6454:         } else {
                   6455:             return 'F';
                   6456:         }
1.545     banghart 6457:     }
                   6458: 
1.762     raeburn  6459: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6460:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6461:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6462:         if (exists($env{'request.course.id'})) {
                   6463:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6464:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6465:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6466:                 my $courseprivid=$env{'request.course.id'};
                   6467:                 $courseprivid=~s/\_/\//;
                   6468:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6469:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6470:                     return $1; 
1.762     raeburn  6471:                 } else {
                   6472:                     if ($env{'request.course.sec'}) {
                   6473:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6474:                     }
                   6475:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6476:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6477:                         return $2;
                   6478:                     }
1.714     raeburn  6479:                 }
                   6480:             }
                   6481:         }
                   6482:     }
                   6483: 
1.159     www      6484: # Free bre to public access
                   6485: 
                   6486:     if ($priv eq 'bre') {
1.238     www      6487:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6488: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6489:            return 'F'; 
                   6490:         }
1.238     www      6491:         if ($copyright eq 'priv') {
                   6492:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6493: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6494: 		return '';
                   6495:             }
                   6496:         }
                   6497:         if ($copyright eq 'domain') {
                   6498:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6499: 	    unless (($env{'user.domain'} eq $1) ||
                   6500:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6501: 		return '';
                   6502:             }
1.262     matthew  6503:         }
1.620     albertel 6504:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6505:             # Library role, so allow browsing of resources in this domain.
                   6506:             return 'F';
1.238     www      6507:         }
1.341     www      6508:         if ($copyright eq 'custom') {
                   6509: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6510:         }
1.14      www      6511:     }
1.264     matthew  6512:     # Domain coordinator is trying to create a course
1.620     albertel 6513:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6514:         # uri is the requested domain in this case.
                   6515:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6516:         # a role of dc for the domain in question.
1.620     albertel 6517:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6518:     }
1.29      www      6519: 
1.52      www      6520:     my $thisallowed='';
                   6521:     my $statecond=0;
                   6522:     my $courseprivid='';
                   6523: 
1.1039    raeburn  6524:     my $ownaccess;
1.1043    raeburn  6525:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6526:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6527:         if ($uri eq '') {
                   6528:             $ownaccess = 1;
                   6529:         } else {
                   6530:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6531:                 my $udom = $env{'user.domain'};
                   6532:                 my $uname = $env{'user.name'};
                   6533:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6534:                     $ownaccess = 1;
1.1040    raeburn  6535:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6536:                     unless ($uri =~ m{\.\./}) {
                   6537:                         $ownaccess = 1;
                   6538:                     }
                   6539:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6540:                     my $now = time;
                   6541:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6542:                         my $adom = $1;
                   6543:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6544:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6545:                                 my ($start,$end) = split('.',$env{$key});
                   6546:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6547:                                     $ownaccess = 1;
                   6548:                                     last;
                   6549:                                 }
                   6550:                             }
                   6551:                         }
                   6552:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6553:                         my $adom = $1;
                   6554:                         my $aname = $2;
1.1042    raeburn  6555:                         foreach my $role ('ca','aa') { 
                   6556:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6557:                                 my ($start,$end) =
                   6558:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6559:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6560:                                     $ownaccess = 1;
                   6561:                                     last;
                   6562:                                 }
1.1039    raeburn  6563:                             }
                   6564:                         }
                   6565:                     }
                   6566:                 }
                   6567:             }
                   6568:         }
                   6569:     }
                   6570: 
1.52      www      6571: # Course
                   6572: 
1.620     albertel 6573:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6574:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6575:             $thisallowed.=$1;
                   6576:         }
1.52      www      6577:     }
1.29      www      6578: 
1.52      www      6579: # Domain
                   6580: 
1.620     albertel 6581:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6582:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6583:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6584:             $thisallowed.=$1;
                   6585:         }
1.12      www      6586:     }
1.52      www      6587: 
1.1141    raeburn  6588: # User who is not author or co-author might still be able to edit
                   6589: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6590:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6591:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6592:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6593:             $thisallowed.=$1;
                   6594:         }
                   6595:     }
                   6596: 
1.52      www      6597: # Course: uri itself is a course
1.66      www      6598:     my $courseuri=$uri;
                   6599:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6600:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6601: 
1.620     albertel 6602:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6603:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6604:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6605:             $thisallowed.=$1;
                   6606:         }
1.12      www      6607:     }
1.29      www      6608: 
1.665     albertel 6609: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6610: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6611:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6612: 	$thisallowed='';
1.671     raeburn  6613:         my ($match)=&is_on_map($uri);
                   6614:         if ($match) {
                   6615:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6616:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6617:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6618:                 if (@blockers > 0) {
                   6619:                     $thisallowed = 'B';
                   6620:                 } else {
                   6621:                     $thisallowed.=$1;
                   6622:                 }
1.671     raeburn  6623:             }
                   6624:         } else {
1.705     albertel 6625:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6626:             if ($refuri) {
                   6627:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6628:                     $thisallowed='F';
1.671     raeburn  6629:                 } else {
                   6630:                     $refuri=&declutter($refuri);
                   6631:                     my ($match) = &is_on_map($refuri);
                   6632:                     if ($match) {
1.1162    raeburn  6633:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6634:                         if (@blockers > 0) {
                   6635:                             $thisallowed = 'B';
                   6636:                         } else {
                   6637:                             $thisallowed='F';
                   6638:                         }
1.671     raeburn  6639:                     }
1.669     raeburn  6640:                 }
1.671     raeburn  6641:             }
                   6642:         }
1.314     www      6643:     }
1.492     albertel 6644: 
1.766     albertel 6645:     if ($priv eq 'bre'
                   6646: 	&& $thisallowed ne 'F' 
                   6647: 	&& $thisallowed ne '2'
                   6648: 	&& &is_portfolio_url($uri)) {
                   6649: 	$thisallowed = &portfolio_access($uri);
                   6650:     }
                   6651:     
1.52      www      6652: # Full access at system, domain or course-wide level? Exit.
1.29      www      6653:     if ($thisallowed=~/F/) {
                   6654: 	return 'F';
                   6655:     }
                   6656: 
1.52      www      6657: # If this is generating or modifying users, exit with special codes
1.29      www      6658: 
1.643     www      6659:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6660: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6661: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6662: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6663: 	    unless ($auname) { return $thisallowed; }
                   6664: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6665: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6666: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6667: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6668: 	}
1.52      www      6669: 	return $thisallowed;
                   6670:     }
                   6671: #
1.103     harris41 6672: # Gathered so far: system, domain and course wide privileges
1.52      www      6673: #
                   6674: # Course: See if uri or referer is an individual resource that is part of 
                   6675: # the course
                   6676: 
1.620     albertel 6677:     if ($env{'request.course.id'}) {
1.232     www      6678: 
1.620     albertel 6679:        $courseprivid=$env{'request.course.id'};
                   6680:        if ($env{'request.course.sec'}) {
                   6681:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6682:        }
                   6683:        $courseprivid=~s/\_/\//;
                   6684:        my $checkreferer=1;
1.232     www      6685:        my ($match,$cond)=&is_on_map($uri);
                   6686:        if ($match) {
                   6687:            $statecond=$cond;
1.620     albertel 6688:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6689:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6690:                my $value = $1;
                   6691:                if ($priv eq 'bre') {
                   6692:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6693:                    if (@blockers > 0) {
                   6694:                        $thisallowed = 'B';
                   6695:                    } else {
                   6696:                        $thisallowed.=$value;
                   6697:                    }
                   6698:                } else {
                   6699:                    $thisallowed.=$value;
                   6700:                }
1.52      www      6701:                $checkreferer=0;
                   6702:            }
1.29      www      6703:        }
1.83      www      6704:        
1.148     www      6705:        if ($checkreferer) {
1.620     albertel 6706: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6707:             unless ($refuri) {
1.800     albertel 6708:                 foreach my $key (keys(%env)) {
                   6709: 		    if ($key=~/^httpref\..*\*/) {
                   6710: 			my $pattern=$key;
1.156     www      6711:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6712:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6713:                         $pattern=~s/\//\\\//g;
1.152     www      6714:                         if ($orguri=~/$pattern/) {
1.800     albertel 6715: 			    $refuri=$env{$key};
1.148     www      6716:                         }
                   6717:                     }
1.191     harris41 6718:                 }
1.148     www      6719:             }
1.232     www      6720: 
1.148     www      6721:          if ($refuri) { 
1.152     www      6722: 	  $refuri=&declutter($refuri);
1.232     www      6723:           my ($match,$cond)=&is_on_map($refuri);
                   6724:             if ($match) {
                   6725:               my $refstatecond=$cond;
1.620     albertel 6726:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6727:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6728:                   my $value = $1;
                   6729:                   if ($priv eq 'bre') {
                   6730:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6731:                       if (@blockers > 0) {
                   6732:                           $thisallowed = 'B';
                   6733:                       } else {
                   6734:                           $thisallowed.=$value;
                   6735:                       }
                   6736:                   } else {
                   6737:                       $thisallowed.=$value;
                   6738:                   }
1.53      www      6739:                   $uri=$refuri;
                   6740:                   $statecond=$refstatecond;
1.52      www      6741:               }
                   6742:           }
1.148     www      6743:         }
1.29      www      6744:        }
1.52      www      6745:    }
1.29      www      6746: 
1.52      www      6747: #
1.103     harris41 6748: # Gathered now: all privileges that could apply, and condition number
1.52      www      6749: # 
                   6750: #
                   6751: # Full or no access?
                   6752: #
1.29      www      6753: 
1.52      www      6754:     if ($thisallowed=~/F/) {
                   6755: 	return 'F';
                   6756:     }
1.29      www      6757: 
1.52      www      6758:     unless ($thisallowed) {
                   6759:         return '';
                   6760:     }
1.29      www      6761: 
1.52      www      6762: # Restrictions exist, deal with them
                   6763: #
                   6764: #   C:according to course preferences
                   6765: #   R:according to resource settings
                   6766: #   L:unless locked
                   6767: #   X:according to user session state
                   6768: #
                   6769: 
                   6770: # Possibly locked functionality, check all courses
1.54      www      6771: # Locks might take effect only after 10 minutes cache expiration for other
                   6772: # courses, and 2 minutes for current course
1.52      www      6773: 
                   6774:     my $envkey;
                   6775:     if ($thisallowed=~/L/) {
1.1000    raeburn  6776:         foreach $envkey (keys(%env)) {
1.54      www      6777:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6778:                my $courseid=$2;
                   6779:                my $roleid=$1.'.'.$2;
1.92      www      6780:                $courseid=~s/^\///;
1.54      www      6781:                my $expiretime=600;
1.620     albertel 6782:                if ($env{'request.role'} eq $roleid) {
1.54      www      6783: 		  $expiretime=120;
                   6784:                }
                   6785: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6786:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6787:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6788: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6789:                }
1.620     albertel 6790:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6791:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6792: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6793:                        &log($env{'user.domain'},$env{'user.name'},
                   6794:                             $env{'user.home'},
1.57      www      6795:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6796:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6797:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6798: 		       return '';
                   6799:                    }
                   6800:                }
1.620     albertel 6801:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6802:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6803: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6804:                        &log($env{'user.domain'},$env{'user.name'},
                   6805:                             $env{'user.home'},
1.57      www      6806:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6807:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6808:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6809: 		       return '';
                   6810:                    }
                   6811:                }
                   6812: 	   }
1.29      www      6813:        }
1.52      www      6814:     }
                   6815:    
                   6816: #
                   6817: # Rest of the restrictions depend on selected course
                   6818: #
                   6819: 
1.620     albertel 6820:     unless ($env{'request.course.id'}) {
1.766     albertel 6821: 	if ($thisallowed eq 'A') {
                   6822: 	    return 'A';
1.814     raeburn  6823:         } elsif ($thisallowed eq 'B') {
                   6824:             return 'B';
1.766     albertel 6825: 	} else {
                   6826: 	    return '1';
                   6827: 	}
1.52      www      6828:     }
1.29      www      6829: 
1.52      www      6830: #
                   6831: # Now user is definitely in a course
                   6832: #
1.53      www      6833: 
                   6834: 
                   6835: # Course preferences
                   6836: 
                   6837:    if ($thisallowed=~/C/) {
1.620     albertel 6838:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6839:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6840:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6841: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6842: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6843: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6844: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6845: 			$env{'request.course.id'});
                   6846: 	   }
1.237     www      6847:            return '';
                   6848:        }
                   6849: 
1.620     albertel 6850:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6851: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6852: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6853: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6854: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6855: 			$env{'request.course.id'});
                   6856: 	   }
1.54      www      6857:            return '';
                   6858:        }
1.53      www      6859:    }
                   6860: 
                   6861: # Resource preferences
                   6862: 
                   6863:    if ($thisallowed=~/R/) {
1.620     albertel 6864:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6865:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6866: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6867: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6868: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6869: 	   }
                   6870: 	   return '';
1.54      www      6871:        }
1.53      www      6872:    }
1.30      www      6873: 
1.246     www      6874: # Restricted by state or randomout?
1.30      www      6875: 
1.52      www      6876:    if ($thisallowed=~/X/) {
1.620     albertel 6877:       if ($env{'acc.randomout'}) {
1.579     albertel 6878: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6879:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6880:             return ''; 
                   6881:          }
1.247     www      6882:       }
                   6883:       if (&condval($statecond)) {
1.52      www      6884: 	 return '2';
                   6885:       } else {
                   6886:          return '';
                   6887:       }
                   6888:    }
1.30      www      6889: 
1.766     albertel 6890:     if ($thisallowed eq 'A') {
                   6891: 	return 'A';
1.814     raeburn  6892:     } elsif ($thisallowed eq 'B') {
                   6893:         return 'B';
1.766     albertel 6894:     }
1.52      www      6895:    return 'F';
1.232     www      6896: }
1.1162    raeburn  6897: 
1.1172.2.13  raeburn  6898: # ------------------------------------------- Check construction space access
                   6899: 
                   6900: sub constructaccess {
                   6901:     my ($url,$setpriv)=@_;
                   6902: 
                   6903: # We do not allow editing of previous versions of files
                   6904:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6905: 
                   6906: # Get username and domain from URL
                   6907:     my ($ownername,$ownerdomain,$ownerhome);
                   6908: 
                   6909:     ($ownerdomain,$ownername) =
                   6910:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6911: 
                   6912: # The URL does not really point to any authorspace, forget it
                   6913:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6914: 
                   6915: # Now we need to see if the user has access to the authorspace of
                   6916: # $ownername at $ownerdomain
                   6917: 
                   6918:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6919: # Real author for this?
                   6920:        $ownerhome = $env{'user.home'};
                   6921:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6922:           return ($ownername,$ownerdomain,$ownerhome);
                   6923:        }
                   6924:     } else {
                   6925: # Co-author for this?
                   6926:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6927:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6928:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6929:             return ($ownername,$ownerdomain,$ownerhome);
                   6930:         }
                   6931:     }
                   6932: 
                   6933: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6934: # we might as well leave
                   6935:    unless ($setpriv) { return ''; }
                   6936: 
                   6937: # Backdoor access?
                   6938:     my $allowed=&allowed('eco',$ownerdomain);
                   6939: # Nope
                   6940:     unless ($allowed) { return ''; }
                   6941: # Looks like we may have access, but could be locked by the owner of the construction space
                   6942:     if ($allowed eq 'U') {
                   6943:         my %blocked=&get('environment',['domcoord.author'],
                   6944:                          $ownerdomain,$ownername);
                   6945: # Is blocked by owner
                   6946:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6947:     }
                   6948:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6949: # Grant temporary access
                   6950:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6951:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6952:         if (!$update) { $update = $then; }
                   6953:         my $refresh=$env{'user.refresh.time'};
                   6954:         if (!$refresh) { $refresh = $update; }
                   6955:         my $now = time;
                   6956:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6957:                            $now,'ca','constructaccess');
                   6958:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6959:         return($ownername,$ownerdomain,$ownerhome);
                   6960:     }
                   6961: # No business here
                   6962:     return '';
                   6963: }
                   6964: 
1.1162    raeburn  6965: sub get_comm_blocks {
                   6966:     my ($cdom,$cnum) = @_;
                   6967:     if ($cdom eq '' || $cnum eq '') {
                   6968:         return unless ($env{'request.course.id'});
                   6969:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6970:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6971:     }
                   6972:     my %commblocks;
                   6973:     my $hashid=$cdom.'_'.$cnum;
                   6974:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6975:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6976:         %commblocks = %{$blocksref};
                   6977:     } else {
                   6978:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6979:         my $cachetime = 600;
                   6980:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6981:     }
                   6982:     return %commblocks;
                   6983: }
                   6984: 
                   6985: sub has_comm_blocking {
                   6986:     my ($priv,$symb,$uri,$blocks) = @_;
                   6987:     return unless ($env{'request.course.id'});
                   6988:     return unless ($priv eq 'bre');
                   6989:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6990:     my %commblocks;
                   6991:     if (ref($blocks) eq 'HASH') {
                   6992:         %commblocks = %{$blocks};
                   6993:     } else {
                   6994:         %commblocks = &get_comm_blocks();
                   6995:     }
                   6996:     return unless (keys(%commblocks) > 0);
                   6997:     if (!$symb) { $symb=&symbread($uri,1); }
                   6998:     my ($map,$resid,undef)=&decode_symb($symb);
                   6999:     my %tocheck = (
                   7000:                     maps      => $map,
                   7001:                     resources => $symb,
                   7002:                   );
                   7003:     my @blockers;
                   7004:     my $now = time;
1.1163    raeburn  7005:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7006:     foreach my $block (keys(%commblocks)) {
                   7007:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7008:             my ($start,$end) = ($1,$2);
                   7009:             if ($start <= $now && $end >= $now) {
                   7010:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7011:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7012:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7013:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7014:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7015:                                     push(@blockers,$block);
                   7016:                                 }
                   7017:                             }
                   7018:                         }
                   7019:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7020:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7021:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7022:                                     push(@blockers,$block);
                   7023:                                 }
                   7024:                             }
                   7025:                         }
                   7026:                     }
                   7027:                 }
                   7028:             }
                   7029:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7030:             my $item = $1;
1.1163    raeburn  7031:             my @to_test;
1.1162    raeburn  7032:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7033:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7034:                     my $check_interval;
                   7035:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7036:                         my @interval;
                   7037:                         my $type = 'map';
                   7038:                         if ($item eq 'course') {
                   7039:                             $type = 'course';
                   7040:                             @interval=&EXT("resource.0.interval");
                   7041:                         } else {
                   7042:                             if ($item =~ /___\d+___/) {
                   7043:                                 $type = 'resource';
                   7044:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7045:                                 if (ref($navmap)) {                        
                   7046:                                     my $res = $navmap->getBySymb($item); 
                   7047:                                     push(@to_test,$res);
                   7048:                                 }
1.1162    raeburn  7049:                             } else {
                   7050:                                 my $mapsymb = &symbread($item,1);
                   7051:                                 if ($mapsymb) {
                   7052:                                     if (ref($navmap)) {
                   7053:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7054:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7055:                                         foreach my $res (@to_test) {
1.1162    raeburn  7056:                                             my $symb = $res->symb();
                   7057:                                             next if ($symb eq $mapsymb);
                   7058:                                             if ($symb ne '') {
                   7059:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7060:                                                 last;
                   7061:                                             }
                   7062:                                         }
                   7063:                                     }
                   7064:                                 }
                   7065:                             }
                   7066:                         }
                   7067:                         if ($interval[0] =~ /\d+/) {
                   7068:                             my $first_access;
                   7069:                             if ($type eq 'resource') {
                   7070:                                 $first_access=&get_first_access($interval[1],$item);
                   7071:                             } elsif ($type eq 'map') {
                   7072:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7073:                             } else {
                   7074:                                 $first_access=&get_first_access($interval[1]);
                   7075:                             }
                   7076:                             if ($first_access) {
                   7077:                                 my $timesup = $first_access+$interval[0];
                   7078:                                 if ($timesup > $now) {
1.1163    raeburn  7079:                                     foreach my $res (@to_test) {
                   7080:                                         if ($res->is_problem()) {
                   7081:                                             if ($res->completable()) {
                   7082:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7083:                                                     push(@blockers,$block);
                   7084:                                                 }
                   7085:                                                 last;
                   7086:                                             }
                   7087:                                         }
1.1162    raeburn  7088:                                     }
                   7089:                                 }
                   7090:                             }
                   7091:                         }
                   7092:                     }
                   7093:                 }
                   7094:             }
                   7095:         }
                   7096:     }
                   7097:     return @blockers;
                   7098: }
                   7099: 
                   7100: sub check_docs_block {
                   7101:     my ($docsblock,$tocheck) =@_;
                   7102:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7103:         return;
                   7104:     }
                   7105:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7106:         if ($tocheck->{'maps'}) {
                   7107:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7108:                 return 1;
                   7109:             }
                   7110:         }
                   7111:     }
                   7112:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7113:         if ($tocheck->{'resources'}) {
                   7114:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7115:                 return 1;
                   7116:             }
                   7117:         }
                   7118:     }
                   7119:     return;
                   7120: }
                   7121: 
1.1133    foxr     7122: #
                   7123: #   Removes the versino from a URI and
                   7124: #   splits it in to its filename and path to the filename.
                   7125: #   Seems like File::Basename could have done this more clearly.
                   7126: #   Parameters:
                   7127: #      $uri   - input URI
                   7128: #   Returns:
                   7129: #     Two element list consisting of 
                   7130: #     $pathname  - the URI up to and excluding the trailing /
                   7131: #     $filename  - The part of the URI following the last /
                   7132: #  NOTE:
                   7133: #    Another realization of this is simply:
                   7134: #    use File::Basename;
                   7135: #    ...
                   7136: #    $uri = shift;
                   7137: #    $filename = basename($uri);
                   7138: #    $path     = dirname($uri);
                   7139: #    return ($filename, $path);
                   7140: #
                   7141: #     The implementation below is probably faster however.
                   7142: #
1.710     albertel 7143: sub split_uri_for_cond {
                   7144:     my $uri=&deversion(&declutter(shift));
                   7145:     my @uriparts=split(/\//,$uri);
                   7146:     my $filename=pop(@uriparts);
                   7147:     my $pathname=join('/',@uriparts);
                   7148:     return ($pathname,$filename);
                   7149: }
1.232     www      7150: # --------------------------------------------------- Is a resource on the map?
                   7151: 
                   7152: sub is_on_map {
1.710     albertel 7153:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7154:     #Trying to find the conditional for the file
1.620     albertel 7155:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7156: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7157:     if ($match) {
1.289     bowersj2 7158: 	return (1,$1);
                   7159:     } else {
1.434     www      7160: 	return (0,0);
1.289     bowersj2 7161:     }
1.12      www      7162: }
                   7163: 
1.427     www      7164: # --------------------------------------------------------- Get symb from alias
                   7165: 
                   7166: sub get_symb_from_alias {
                   7167:     my $symb=shift;
                   7168:     my ($map,$resid,$url)=&decode_symb($symb);
                   7169: # Already is a symb
                   7170:     if ($url) { return $symb; }
                   7171: # Must be an alias
                   7172:     my $aliassymb='';
                   7173:     my %bighash;
1.620     albertel 7174:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7175:                             &GDBM_READER(),0640)) {
                   7176:         my $rid=$bighash{'mapalias_'.$symb};
                   7177: 	if ($rid) {
                   7178: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7179: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7180: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7181: 	}
                   7182:         untie %bighash;
                   7183:     }
                   7184:     return $aliassymb;
                   7185: }
                   7186: 
1.12      www      7187: # ----------------------------------------------------------------- Define Role
                   7188: 
                   7189: sub definerole {
                   7190:   if (allowed('mcr','/')) {
                   7191:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7192:     foreach my $role (split(':',$sysrole)) {
                   7193: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7194:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7195:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7196: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7197:                return "refused:s:$crole&$cqual"; 
                   7198:             }
                   7199:         }
1.191     harris41 7200:     }
1.800     albertel 7201:     foreach my $role (split(':',$domrole)) {
                   7202: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7203:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7204:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7205: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7206:                return "refused:d:$crole&$cqual"; 
                   7207:             }
                   7208:         }
1.191     harris41 7209:     }
1.800     albertel 7210:     foreach my $role (split(':',$courole)) {
                   7211: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7212:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7213:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7214: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7215:                return "refused:c:$crole&$cqual"; 
                   7216:             }
                   7217:         }
1.191     harris41 7218:     }
1.620     albertel 7219:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7220:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7221: 	        "rolesdef_$rolename=".
                   7222:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7223:     return reply($command,$env{'user.home'});
1.12      www      7224:   } else {
                   7225:     return 'refused';
                   7226:   }
1.105     harris41 7227: }
                   7228: 
                   7229: # ---------------- Make a metadata query against the network of library servers
                   7230: 
                   7231: sub metadata_query {
1.244     matthew  7232:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7233:     my %rhash;
1.845     albertel 7234:     my %libserv = &all_library();
1.244     matthew  7235:     my @server_list = (defined($server_array) ? @$server_array
                   7236:                                               : keys(%libserv) );
                   7237:     for my $server (@server_list) {
1.118     harris41 7238: 	unless ($custom or $customshow) {
                   7239: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7240: 	    $rhash{$server}=$reply;
                   7241: 	}
                   7242: 	else {
                   7243: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7244: 			     &escape($custom).':'.&escape($customshow),
                   7245: 			     $server);
                   7246: 	    $rhash{$server}=$reply;
                   7247: 	}
1.112     harris41 7248:     }
1.118     harris41 7249:     return \%rhash;
1.240     www      7250: }
                   7251: 
                   7252: # ----------------------------------------- Send log queries and wait for reply
                   7253: 
                   7254: sub log_query {
                   7255:     my ($uname,$udom,$query,%filters)=@_;
                   7256:     my $uhome=&homeserver($uname,$udom);
                   7257:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7258:     my $uhost=&hostname($uhome);
1.800     albertel 7259:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7260:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7261:                        $uhome);
1.479     albertel 7262:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7263:     return get_query_reply($queryid);
                   7264: }
                   7265: 
1.818     raeburn  7266: # -------------------------- Update MySQL table for portfolio file
                   7267: 
                   7268: sub update_portfolio_table {
1.821     raeburn  7269:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7270:     if ($group ne '') {
                   7271:         $file_name =~s /^\Q$group\E//;
                   7272:     }
1.818     raeburn  7273:     my $homeserver = &homeserver($uname,$udom);
                   7274:     my $queryid=
1.821     raeburn  7275:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7276:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7277:     my $reply = &get_query_reply($queryid);
                   7278:     return $reply;
                   7279: }
                   7280: 
1.899     raeburn  7281: # -------------------------- Update MySQL allusers table
                   7282: 
                   7283: sub update_allusers_table {
                   7284:     my ($uname,$udom,$names) = @_;
                   7285:     my $homeserver = &homeserver($uname,$udom);
                   7286:     my $queryid=
                   7287:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7288:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7289:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7290:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7291:                'generation='.&escape($names->{'generation'}).'%%'.
                   7292:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7293:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7294:     return;
1.899     raeburn  7295: }
                   7296: 
1.508     raeburn  7297: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7298: 
                   7299: sub fetch_enrollment_query {
1.511     raeburn  7300:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7301:     my $homeserver;
1.547     raeburn  7302:     my $maxtries = 1;
1.508     raeburn  7303:     if ($context eq 'automated') {
                   7304:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7305:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7306:     } else {
                   7307:         $homeserver = &homeserver($cnum,$dom);
                   7308:     }
1.838     albertel 7309:     my $host=&hostname($homeserver);
1.506     raeburn  7310:     my $cmd = '';
1.1000    raeburn  7311:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7312:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7313:     }
                   7314:     $cmd =~ s/%%$//;
                   7315:     $cmd = &escape($cmd);
                   7316:     my $query = 'fetchenrollment';
1.620     albertel 7317:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7318:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7319:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7320:         return 'error: '.$queryid;
                   7321:     }
1.506     raeburn  7322:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7323:     my $tries = 1;
                   7324:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7325:         $reply = &get_query_reply($queryid);
                   7326:         $tries ++;
                   7327:     }
1.526     raeburn  7328:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7329:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7330:     } else {
1.901     albertel 7331:         my @responses = split(/:/,$reply);
1.515     raeburn  7332:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7333:             foreach my $line (@responses) {
                   7334:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7335:                 $$replyref{$key} = $value;
                   7336:             }
                   7337:         } else {
1.1117    foxr     7338:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7339:             foreach my $line (@responses) {
                   7340:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7341:                 $$replyref{$key} = $value;
                   7342:                 if ($value > 0) {
1.800     albertel 7343:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7344:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7345:                         my $destname = $pathname.'/'.$filename;
                   7346:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7347:                         if ($xml_classlist =~ /^error/) {
                   7348:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7349:                         } else {
1.506     raeburn  7350:                             if ( open(FILE,">$destname") ) {
                   7351:                                 print FILE &unescape($xml_classlist);
                   7352:                                 close(FILE);
1.526     raeburn  7353:                             } else {
                   7354:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7355:                             }
                   7356:                         }
                   7357:                     }
                   7358:                 }
                   7359:             }
                   7360:         }
                   7361:         return 'ok';
                   7362:     }
                   7363:     return 'error';
                   7364: }
                   7365: 
1.242     www      7366: sub get_query_reply {
                   7367:     my $queryid=shift;
1.1117    foxr     7368:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7369:     my $reply='';
                   7370:     for (1..100) {
                   7371: 	sleep 2;
                   7372:         if (-e $replyfile.'.end') {
1.448     albertel 7373: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7374: 		$reply = join('',<$fh>);
                   7375: 		close($fh);
1.240     www      7376: 	   } else { return 'error: reply_file_error'; }
1.242     www      7377:            return &unescape($reply);
                   7378: 	}
1.240     www      7379:     }
1.242     www      7380:     return 'timeout:'.$queryid;
1.240     www      7381: }
                   7382: 
                   7383: sub courselog_query {
1.241     www      7384: #
                   7385: # possible filters:
                   7386: # url: url or symb
                   7387: # username
                   7388: # domain
                   7389: # action: view, submit, grade
                   7390: # start: timestamp
                   7391: # end: timestamp
                   7392: #
1.240     www      7393:     my (%filters)=@_;
1.620     albertel 7394:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7395:     if ($filters{'url'}) {
                   7396: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7397:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7398:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7399:     }
1.620     albertel 7400:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7401:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7402:     return &log_query($cname,$cdom,'courselog',%filters);
                   7403: }
                   7404: 
                   7405: sub userlog_query {
1.858     raeburn  7406: #
                   7407: # possible filters:
                   7408: # action: log check role
                   7409: # start: timestamp
                   7410: # end: timestamp
                   7411: #
1.240     www      7412:     my ($uname,$udom,%filters)=@_;
                   7413:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7414: }
                   7415: 
1.506     raeburn  7416: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7417: 
                   7418: sub auto_run {
1.508     raeburn  7419:     my ($cnum,$cdom) = @_;
1.876     raeburn  7420:     my $response = 0;
                   7421:     my $settings;
                   7422:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7423:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7424:         $settings = $domconfig{'autoenroll'};
                   7425:         if ($settings->{'run'} eq '1') {
                   7426:             $response = 1;
                   7427:         }
                   7428:     } else {
1.934     raeburn  7429:         my $homeserver;
                   7430:         if (&is_course($cdom,$cnum)) {
                   7431:             $homeserver = &homeserver($cnum,$cdom);
                   7432:         } else {
                   7433:             $homeserver = &domain($cdom,'primary');
                   7434:         }
                   7435:         if ($homeserver ne 'no_host') {
                   7436:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7437:         }
1.876     raeburn  7438:     }
1.506     raeburn  7439:     return $response;
                   7440: }
1.776     albertel 7441: 
1.506     raeburn  7442: sub auto_get_sections {
1.508     raeburn  7443:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7444:     my $homeserver;
                   7445:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7446:         $homeserver = &homeserver($cnum,$cdom);
                   7447:     }
                   7448:     if (!defined($homeserver)) { 
                   7449:         if ($cdom =~ /^$match_domain$/) {
                   7450:             $homeserver = &domain($cdom,'primary');
                   7451:         }
                   7452:     }
                   7453:     my @secs;
                   7454:     if (defined($homeserver)) {
                   7455:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7456:         unless ($response eq 'refused') {
                   7457:             @secs = split(/:/,$response);
                   7458:         }
1.506     raeburn  7459:     }
                   7460:     return @secs;
                   7461: }
1.776     albertel 7462: 
1.506     raeburn  7463: sub auto_new_course {
1.1099    raeburn  7464:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7465:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7466:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7467:     return $response;
                   7468: }
1.776     albertel 7469: 
1.506     raeburn  7470: sub auto_validate_courseID {
1.508     raeburn  7471:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7472:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7473:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7474:     return $response;
                   7475: }
1.776     albertel 7476: 
1.1007    raeburn  7477: sub auto_validate_instcode {
1.1020    raeburn  7478:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7479:     my ($homeserver,$response);
                   7480:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7481:         $homeserver = &homeserver($cnum,$cdom);
                   7482:     }
                   7483:     if (!defined($homeserver)) {
                   7484:         if ($cdom =~ /^$match_domain$/) {
                   7485:             $homeserver = &domain($cdom,'primary');
                   7486:         }
                   7487:     }
1.1065    raeburn  7488:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7489:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7490:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7491:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7492: }
                   7493: 
1.506     raeburn  7494: sub auto_create_password {
1.873     raeburn  7495:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7496:     my ($homeserver,$response);
1.506     raeburn  7497:     my $create_passwd = 0;
                   7498:     my $authchk = '';
1.873     raeburn  7499:     if ($udom =~ /^$match_domain$/) {
                   7500:         $homeserver = &domain($udom,'primary');
                   7501:     }
                   7502:     if ($homeserver eq '') {
                   7503:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7504:             $homeserver = &homeserver($cnum,$cdom);
                   7505:         }
                   7506:     }
                   7507:     if ($homeserver eq '') {
                   7508:         $authchk = 'nodomain';
1.506     raeburn  7509:     } else {
1.873     raeburn  7510:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7511:         if ($response eq 'refused') {
                   7512:             $authchk = 'refused';
                   7513:         } else {
1.901     albertel 7514:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7515:         }
1.506     raeburn  7516:     }
                   7517:     return ($authparam,$create_passwd,$authchk);
                   7518: }
                   7519: 
1.706     raeburn  7520: sub auto_photo_permission {
                   7521:     my ($cnum,$cdom,$students) = @_;
                   7522:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7523:     my ($outcome,$perm_reqd,$conditions) = 
                   7524: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7525:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7526: 	return (undef,undef);
                   7527:     }
1.706     raeburn  7528:     return ($outcome,$perm_reqd,$conditions);
                   7529: }
                   7530: 
                   7531: sub auto_checkphotos {
                   7532:     my ($uname,$udom,$pid) = @_;
                   7533:     my $homeserver = &homeserver($uname,$udom);
                   7534:     my ($result,$resulttype);
                   7535:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7536: 				   &escape($uname).':'.&escape($pid),
                   7537: 				   $homeserver));
1.709     albertel 7538:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7539: 	return (undef,undef);
                   7540:     }
1.706     raeburn  7541:     if ($outcome) {
                   7542:         ($result,$resulttype) = split(/:/,$outcome);
                   7543:     } 
                   7544:     return ($result,$resulttype);
                   7545: }
                   7546: 
                   7547: sub auto_photochoice {
                   7548:     my ($cnum,$cdom) = @_;
                   7549:     my $homeserver = &homeserver($cnum,$cdom);
                   7550:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7551: 						       &escape($cdom),
                   7552: 						       $homeserver)));
1.709     albertel 7553:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7554: 	return (undef,undef);
                   7555:     }
1.706     raeburn  7556:     return ($update,$comment);
                   7557: }
                   7558: 
                   7559: sub auto_photoupdate {
                   7560:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7561:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7562:     my $host=&hostname($homeserver);
1.706     raeburn  7563:     my $cmd = '';
                   7564:     my $maxtries = 1;
1.800     albertel 7565:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7566:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7567:     }
                   7568:     $cmd =~ s/%%$//;
                   7569:     $cmd = &escape($cmd);
                   7570:     my $query = 'institutionalphotos';
                   7571:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7572:     unless ($queryid=~/^\Q$host\E\_/) {
                   7573:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7574:         return 'error: '.$queryid;
                   7575:     }
                   7576:     my $reply = &get_query_reply($queryid);
                   7577:     my $tries = 1;
                   7578:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7579:         $reply = &get_query_reply($queryid);
                   7580:         $tries ++;
                   7581:     }
                   7582:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7583:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7584:     } else {
                   7585:         my @responses = split(/:/,$reply);
                   7586:         my $outcome = shift(@responses); 
                   7587:         foreach my $item (@responses) {
                   7588:             my ($key,$value) = split(/=/,$item);
                   7589:             $$photo{$key} = $value;
                   7590:         }
                   7591:         return $outcome;
                   7592:     }
                   7593:     return 'error';
                   7594: }
                   7595: 
1.521     raeburn  7596: sub auto_instcode_format {
1.793     albertel 7597:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7598: 	$cat_order) = @_;
1.521     raeburn  7599:     my $courses = '';
1.772     raeburn  7600:     my @homeservers;
1.521     raeburn  7601:     if ($caller eq 'global') {
1.841     albertel 7602: 	my %servers = &get_servers($codedom,'library');
                   7603: 	foreach my $tryserver (keys(%servers)) {
                   7604: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7605: 		push(@homeservers,$tryserver);
                   7606: 	    }
1.584     raeburn  7607:         }
1.1022    raeburn  7608:     } elsif ($caller eq 'requests') {
                   7609:         if ($codedom =~ /^$match_domain$/) {
                   7610:             my $chome = &domain($codedom,'primary');
                   7611:             unless ($chome eq 'no_host') {
                   7612:                 push(@homeservers,$chome);
                   7613:             }
                   7614:         }
1.521     raeburn  7615:     } else {
1.772     raeburn  7616:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7617:     }
1.793     albertel 7618:     foreach my $code (keys(%{$instcodes})) {
                   7619:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7620:     }
                   7621:     chop($courses);
1.772     raeburn  7622:     my $ok_response = 0;
                   7623:     my $response;
                   7624:     while (@homeservers > 0 && $ok_response == 0) {
                   7625:         my $server = shift(@homeservers); 
                   7626:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7627:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7628:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7629: 		split(/:/,$response);
1.772     raeburn  7630:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7631:             push(@{$codetitles},&str2array($codetitles_str));
                   7632:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7633:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7634:             $ok_response = 1;
                   7635:         }
                   7636:     }
                   7637:     if ($ok_response) {
1.521     raeburn  7638:         return 'ok';
1.772     raeburn  7639:     } else {
                   7640:         return $response;
1.521     raeburn  7641:     }
                   7642: }
                   7643: 
1.792     raeburn  7644: sub auto_instcode_defaults {
                   7645:     my ($domain,$returnhash,$code_order) = @_;
                   7646:     my @homeservers;
1.841     albertel 7647: 
                   7648:     my %servers = &get_servers($domain,'library');
                   7649:     foreach my $tryserver (keys(%servers)) {
                   7650: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7651: 	    push(@homeservers,$tryserver);
                   7652: 	}
1.792     raeburn  7653:     }
1.841     albertel 7654: 
1.792     raeburn  7655:     my $response;
1.841     albertel 7656:     foreach my $server (@homeservers) {
1.792     raeburn  7657:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7658:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7659: 	
                   7660: 	foreach my $pair (split(/\&/,$response)) {
                   7661: 	    my ($name,$value)=split(/\=/,$pair);
                   7662: 	    if ($name eq 'code_order') {
                   7663: 		@{$code_order} = split(/\&/,&unescape($value));
                   7664: 	    } else {
                   7665: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7666: 	    }
                   7667: 	}
                   7668: 	return 'ok';
1.792     raeburn  7669:     }
1.841     albertel 7670: 
                   7671:     return $response;
1.1003    raeburn  7672: }
                   7673: 
                   7674: sub auto_possible_instcodes {
1.1007    raeburn  7675:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7676:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7677:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7678:         return;
                   7679:     }
1.1003    raeburn  7680:     my (@homeservers,$uhome);
                   7681:     if (defined(&domain($domain,'primary'))) {
                   7682:         $uhome=&domain($domain,'primary');
                   7683:         push(@homeservers,&domain($domain,'primary'));
                   7684:     } else {
                   7685:         my %servers = &get_servers($domain,'library');
                   7686:         foreach my $tryserver (keys(%servers)) {
                   7687:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7688:                 push(@homeservers,$tryserver);
                   7689:             }
                   7690:         }
                   7691:     }
                   7692:     my $response;
                   7693:     foreach my $server (@homeservers) {
                   7694:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7695:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7696:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7697:             split(':',$response);
                   7698:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7699:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7700:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7701:             my ($name,$value)=split('=',$item);
                   7702:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7703:         }
                   7704:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7705:             my ($name,$value)=split('=',$item);
                   7706:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7707:         }
                   7708:         return 'ok';
                   7709:     }
                   7710:     return $response;
                   7711: }
1.792     raeburn  7712: 
1.1010    raeburn  7713: sub auto_courserequest_checks {
                   7714:     my ($dom) = @_;
1.1020    raeburn  7715:     my ($homeserver,%validations);
                   7716:     if ($dom =~ /^$match_domain$/) {
                   7717:         $homeserver = &domain($dom,'primary');
                   7718:     }
                   7719:     unless ($homeserver eq 'no_host') {
                   7720:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7721:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7722:             my @items = split(/&/,$response);
                   7723:             foreach my $item (@items) {
                   7724:                 my ($key,$value) = split('=',$item);
                   7725:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7726:             }
                   7727:         }
                   7728:     }
1.1010    raeburn  7729:     return %validations; 
                   7730: }
                   7731: 
1.1020    raeburn  7732: sub auto_courserequest_validation {
                   7733:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7734:     my ($homeserver,$response);
                   7735:     if ($dom =~ /^$match_domain$/) {
                   7736:         $homeserver = &domain($dom,'primary');
                   7737:     }
                   7738:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7739:           
1.1020    raeburn  7740:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7741:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7742:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7743:                                     $homeserver));
                   7744:     }
                   7745:     return $response;
                   7746: }
                   7747: 
1.777     albertel 7748: sub auto_validate_class_sec {
1.918     raeburn  7749:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7750:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7751:     my $ownerlist;
                   7752:     if (ref($owners) eq 'ARRAY') {
                   7753:         $ownerlist = join(',',@{$owners});
                   7754:     } else {
                   7755:         $ownerlist = $owners;
                   7756:     }
1.773     raeburn  7757:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7758:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7759:     return $response;
                   7760: }
                   7761: 
1.679     raeburn  7762: # ------------------------------------------------------- Course Group routines
                   7763: 
                   7764: sub get_coursegroups {
1.809     raeburn  7765:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7766:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7767: }
                   7768: 
1.679     raeburn  7769: sub modify_coursegroup {
                   7770:     my ($cdom,$cnum,$groupsettings) = @_;
                   7771:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7772: }
                   7773: 
1.809     raeburn  7774: sub toggle_coursegroup_status {
                   7775:     my ($cdom,$cnum,$group,$action) = @_;
                   7776:     my ($from_namespace,$to_namespace);
                   7777:     if ($action eq 'delete') {
                   7778:         $from_namespace = 'coursegroups';
                   7779:         $to_namespace = 'deleted_groups';
                   7780:     } else {
                   7781:         $from_namespace = 'deleted_groups';
                   7782:         $to_namespace = 'coursegroups';
                   7783:     }
                   7784:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7785:     if (my $tmp = &error(%curr_group)) {
                   7786:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7787:         return ('read error',$tmp);
                   7788:     } else {
                   7789:         my %savedsettings = %curr_group; 
1.809     raeburn  7790:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7791:         my $deloutcome;
                   7792:         if ($result eq 'ok') {
1.809     raeburn  7793:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7794:         } else {
                   7795:             return ('write error',$result);
                   7796:         }
                   7797:         if ($deloutcome eq 'ok') {
                   7798:             return 'ok';
                   7799:         } else {
                   7800:             return ('delete error',$deloutcome);
                   7801:         }
                   7802:     }
                   7803: }
                   7804: 
1.679     raeburn  7805: sub modify_group_roles {
1.957     raeburn  7806:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7807:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7808:     my $role = 'gr/'.&escape($userprivs);
                   7809:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7810:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7811:     if ($result eq 'ok') {
                   7812:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7813:     }
1.679     raeburn  7814:     return $result;
                   7815: }
                   7816: 
                   7817: sub modify_coursegroup_membership {
                   7818:     my ($cdom,$cnum,$membership) = @_;
                   7819:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7820:     return $result;
                   7821: }
                   7822: 
1.682     raeburn  7823: sub get_active_groups {
                   7824:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7825:     my $now = time;
                   7826:     my %groups = ();
                   7827:     foreach my $key (keys(%env)) {
1.811     albertel 7828:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7829:             my ($start,$end) = split(/\./,$env{$key});
                   7830:             if (($end!=0) && ($end<$now)) { next; }
                   7831:             if (($start!=0) && ($start>$now)) { next; }
                   7832:             if ($1 eq $cdom && $2 eq $cnum) {
                   7833:                 $groups{$3} = $env{$key} ;
                   7834:             }
                   7835:         }
                   7836:     }
                   7837:     return %groups;
                   7838: }
                   7839: 
1.683     raeburn  7840: sub get_group_membership {
                   7841:     my ($cdom,$cnum,$group) = @_;
                   7842:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7843: }
                   7844: 
                   7845: sub get_users_groups {
                   7846:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7847:     my @usersgroups;
1.683     raeburn  7848:     my $cachetime=1800;
                   7849: 
                   7850:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7851:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7852:     if (defined($cached)) {
1.734     albertel 7853:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7854:     } else {  
                   7855:         $grouplist = '';
1.816     raeburn  7856:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7857:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7858:         my $access_end = $env{'course.'.$courseid.
                   7859:                               '.default_enrollment_end_date'};
                   7860:         my $now = time;
                   7861:         foreach my $key (keys(%roleshash)) {
                   7862:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7863:                 my $group = $1;
                   7864:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7865:                     my $start = $2;
                   7866:                     my $end = $1;
                   7867:                     if ($start == -1) { next; } # deleted from group
                   7868:                     if (($start!=0) && ($start>$now)) { next; }
                   7869:                     if (($end!=0) && ($end<$now)) {
                   7870:                         if ($access_end && $access_end < $now) {
                   7871:                             if ($access_end - $end < 86400) {
                   7872:                                 push(@usersgroups,$group);
1.733     raeburn  7873:                             }
                   7874:                         }
1.817     raeburn  7875:                         next;
1.733     raeburn  7876:                     }
1.817     raeburn  7877:                     push(@usersgroups,$group);
1.683     raeburn  7878:                 }
                   7879:             }
                   7880:         }
1.817     raeburn  7881:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7882:         $grouplist = join(':',@usersgroups);
                   7883:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7884:     }
1.733     raeburn  7885:     return @usersgroups;
1.683     raeburn  7886: }
                   7887: 
                   7888: sub devalidate_getgroups_cache {
                   7889:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7890:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7891: 
1.683     raeburn  7892:     my $hashid="$udom:$uname:$courseid";
                   7893:     &devalidate_cache_new('getgroups',$hashid);
                   7894: }
                   7895: 
1.12      www      7896: # ------------------------------------------------------------------ Plain Text
                   7897: 
                   7898: sub plaintext {
1.988     raeburn  7899:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7900:     if ($short =~ m{^cr/}) {
1.758     albertel 7901: 	return (split('/',$short))[-1];
                   7902:     }
1.742     raeburn  7903:     if (!defined($cid)) {
                   7904:         $cid = $env{'request.course.id'};
                   7905:     }
                   7906:     my %rolenames = (
1.1008    raeburn  7907:                       Course    => 'std',
                   7908:                       Community => 'alt1',
1.742     raeburn  7909:                     );
1.1037    raeburn  7910:     if ($cid ne '') {
                   7911:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7912:             unless ($forcedefault) {
                   7913:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7914:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7915:                 return &Apache::lonlocal::mt($roletext);
                   7916:             }
                   7917:         }
                   7918:     }
                   7919:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7920:         (defined($rolenames{$type})) && 
                   7921:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7922:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7923:     } elsif ($cid ne '') {
                   7924:         my $crstype = $env{'course.'.$cid.'.type'};
                   7925:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7926:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7927:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7928:         }
1.742     raeburn  7929:     }
1.1037    raeburn  7930:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7931: }
                   7932: 
                   7933: # ----------------------------------------------------------------- Assign Role
                   7934: 
                   7935: sub assignrole {
1.957     raeburn  7936:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7937:         $context)=@_;
1.21      www      7938:     my $mrole;
                   7939:     if ($role =~ /^cr\//) {
1.393     www      7940:         my $cwosec=$url;
1.811     albertel 7941:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7942: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7943:            my $refused = 1;
                   7944:            if ($context eq 'requestcourses') {
                   7945:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7946:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7947:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7948:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7949:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7950:                            if ($crsenv{'internal.courseowner'} eq
                   7951:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7952:                                $refused = '';
                   7953:                            }
                   7954:                        }
                   7955:                    }
                   7956:                }
                   7957:            }
                   7958:            if ($refused) {
                   7959:                &logthis('Refused custom assignrole: '.
                   7960:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7961:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7962:                return 'refused';
                   7963:            }
1.104     www      7964:         }
1.21      www      7965:         $mrole='cr';
1.678     raeburn  7966:     } elsif ($role =~ /^gr\//) {
                   7967:         my $cwogrp=$url;
1.811     albertel 7968:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7969:         unless (&allowed('mdg',$cwogrp)) {
                   7970:             &logthis('Refused group assignrole: '.
                   7971:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7972:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7973:             return 'refused';
                   7974:         }
                   7975:         $mrole='gr';
1.21      www      7976:     } else {
1.82      www      7977:         my $cwosec=$url;
1.811     albertel 7978:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7979:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7980:             my $refused;
                   7981:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7982:                 if (!(&allowed('c'.$role,$url))) {
                   7983:                     $refused = 1;
                   7984:                 }
                   7985:             } else {
                   7986:                 $refused = 1;
                   7987:             }
1.947     raeburn  7988:             if ($refused) {
1.1045    raeburn  7989:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7990:                 if (!$selfenroll && $context eq 'course') {
                   7991:                     my %crsenv;
                   7992:                     if ($role eq 'cc' || $role eq 'co') {
                   7993:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7994:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7995:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7996:                                 if ($crsenv{'internal.courseowner'} eq 
                   7997:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7998:                                     $refused = '';
                   7999:                                 }
                   8000:                             }
                   8001:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8002:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8003:                                 if ($crsenv{'internal.courseowner'} eq 
                   8004:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8005:                                     $refused = '';
                   8006:                                 }
                   8007:                             }
                   8008:                         }
                   8009:                     }
                   8010:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8011:                     $refused = '';
1.1017    raeburn  8012:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8013:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8014:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8015:                         my $wrongcc;
                   8016:                         if ($cnum =~ /^$match_community$/) {
                   8017:                             $wrongcc = 1 if ($role eq 'cc');
                   8018:                         } else {
                   8019:                             $wrongcc = 1 if ($role eq 'co');
                   8020:                         }
                   8021:                         unless ($wrongcc) {
                   8022:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8023:                             if ($crsenv{'internal.courseowner'} eq 
                   8024:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8025:                                 $refused = '';
                   8026:                             }
1.1017    raeburn  8027:                         }
                   8028:                     }
1.1172.2.9  raeburn  8029:                 } elsif ($context eq 'requestauthor') {
                   8030:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8031:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8032:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8033:                             $refused = '';
                   8034:                         } else {
                   8035:                             my %domdefaults = &get_domain_defaults($udom);
                   8036:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8037:                                 my $checkbystatus;
                   8038:                                 if ($env{'user.adv'}) {
                   8039:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8040:                                     if ($disposition eq 'automatic') {
                   8041:                                         $refused = '';
                   8042:                                     } elsif ($disposition eq '') {
                   8043:                                         $checkbystatus = 1;
                   8044:                                     }
                   8045:                                 } else {
                   8046:                                     $checkbystatus = 1;
                   8047:                                 }
                   8048:                                 if ($checkbystatus) {
                   8049:                                     if ($env{'environment.inststatus'}) {
                   8050:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8051:                                         foreach my $type (@inststatuses) {
                   8052:                                             if (($type ne '') &&
                   8053:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8054:                                                 $refused = '';
                   8055:                                             }
                   8056:                                         }
                   8057:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8058:                                         $refused = '';
                   8059:                                     }
                   8060:                                 }
                   8061:                             }
                   8062:                         }
                   8063:                     }
1.1017    raeburn  8064:                 }
                   8065:                 if ($refused) {
1.947     raeburn  8066:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8067:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8068: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8069:                     return 'refused';
                   8070:                 }
1.932     raeburn  8071:             }
1.1131    raeburn  8072:         } elsif ($role eq 'au') {
                   8073:             if ($url ne '/'.$udom.'/') {
                   8074:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8075:                          ' to assign author role for '.$uname.':'.$udom.
                   8076:                          ' in domain: '.$url.' refused (wrong domain).');
                   8077:                 return 'refused';
                   8078:             }
1.104     www      8079:         }
1.21      www      8080:         $mrole=$role;
                   8081:     }
1.620     albertel 8082:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8083:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8084:     if ($end) { $command.='_'.$end; }
1.21      www      8085:     if ($start) {
                   8086: 	if ($end) { 
1.81      www      8087:            $command.='_'.$start; 
1.21      www      8088:         } else {
1.81      www      8089:            $command.='_0_'.$start;
1.21      www      8090:         }
                   8091:     }
1.739     raeburn  8092:     my $origstart = $start;
                   8093:     my $origend = $end;
1.957     raeburn  8094:     my $delflag;
1.357     www      8095: # actually delete
                   8096:     if ($deleteflag) {
1.373     www      8097: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8098: # modify command to delete the role
1.620     albertel 8099:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8100:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8101: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8102: # set start and finish to negative values for userrolelog
                   8103:            $start=-1;
                   8104:            $end=-1;
1.957     raeburn  8105:            $delflag = 1;
1.357     www      8106:         }
                   8107:     }
                   8108: # send command
1.349     www      8109:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8110: # log new user role if status is ok
1.349     www      8111:     if ($answer eq 'ok') {
1.663     raeburn  8112: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8113:         if (($role eq 'cc') || ($role eq 'in') ||
                   8114:             ($role eq 'ep') || ($role eq 'ad') ||
                   8115:             ($role eq 'ta') || ($role eq 'st') ||
                   8116:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8117:             ($role eq 'co')) {
1.1172.2.13  raeburn  8118: # for course roles, perform group memberships changes triggered by role change.
                   8119:             unless ($role =~ /^gr/) {
                   8120:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8121:                                                  $origstart,$selfenroll,$context);
                   8122:             }
1.1172.2.9  raeburn  8123:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8124:                            $selfenroll,$context);
                   8125:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8126:                  ($role eq 'au') || ($role eq 'dc')) {
                   8127:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8128:                            $context);
                   8129:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8130:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8131:                              $context);
                   8132:         }
1.1053    raeburn  8133:         if ($role eq 'cc') {
                   8134:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8135:         }
1.349     www      8136:     }
                   8137:     return $answer;
1.169     harris41 8138: }
                   8139: 
1.1053    raeburn  8140: sub autoupdate_coowners {
                   8141:     my ($url,$end,$start,$uname,$udom) = @_;
                   8142:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8143:     if (($cdom ne '') && ($cnum ne '')) {
                   8144:         my $now = time;
                   8145:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8146:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8147:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8148:             my $instcode = $coursehash{'internal.coursecode'};
                   8149:             if ($instcode ne '') {
1.1056    raeburn  8150:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8151:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8152:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8153:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8154:                         if ($result eq 'valid') {
                   8155:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8156:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8157:                                     push(@newcoowners,$coowner);
                   8158:                                 }
                   8159:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8160:                                     push(@newcoowners,$uname.':'.$udom);
                   8161:                                 }
                   8162:                                 @newcoowners = sort(@newcoowners);
                   8163:                             } else {
                   8164:                                 push(@newcoowners,$uname.':'.$udom);
                   8165:                             }
                   8166:                         } else {
                   8167:                             if ($coursehash{'internal.co-owners'}) {
                   8168:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8169:                                     unless ($coowner eq $uname.':'.$udom) {
                   8170:                                         push(@newcoowners,$coowner);
                   8171:                                     }
                   8172:                                 }
                   8173:                                 unless (@newcoowners > 0) {
                   8174:                                     $delcoowners = 1;
                   8175:                                     $coowners = '';
                   8176:                                 }
                   8177:                             }
                   8178:                         }
                   8179:                         if (@newcoowners || $delcoowners) {
                   8180:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8181:                                             $delcoowners,@newcoowners);
                   8182:                         }
                   8183:                     }
                   8184:                 }
                   8185:             }
                   8186:         }
                   8187:     }
                   8188: }
                   8189: 
                   8190: sub store_coowners {
                   8191:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8192:     my $cid = $cdom.'_'.$cnum;
                   8193:     my ($coowners,$delresult,$putresult);
                   8194:     if (@newcoowners) {
                   8195:         $coowners = join(',',@newcoowners);
                   8196:         my %coownershash = (
                   8197:                             'internal.co-owners' => $coowners,
                   8198:                            );
                   8199:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8200:         if ($putresult eq 'ok') {
                   8201:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8202:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8203:             }
                   8204:         }
                   8205:     }
                   8206:     if ($delcoowners) {
                   8207:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8208:         if ($delresult eq 'ok') {
                   8209:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8210:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8211:             }
                   8212:         }
                   8213:     }
                   8214:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8215:         my %crsinfo =
                   8216:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8217:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8218:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8219:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8220:         }
                   8221:     }
                   8222: }
                   8223: 
1.169     harris41 8224: # -------------------------------------------------- Modify user authentication
1.197     www      8225: # Overrides without validation
                   8226: 
1.169     harris41 8227: sub modifyuserauth {
                   8228:     my ($udom,$uname,$umode,$upass)=@_;
                   8229:     my $uhome=&homeserver($uname,$udom);
1.197     www      8230:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8231:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8232:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8233:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8234:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8235: 		     &escape($upass),$uhome);
1.620     albertel 8236:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8237:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8238:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8239:     &log($udom,,$uname,$uhome,
1.620     albertel 8240:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8241:                                      $env{'user.name'}.', '.$umode.
1.197     www      8242:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8243:     unless ($reply eq 'ok') {
1.197     www      8244:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8245: 	return 'error: '.$reply;
                   8246:     }   
1.170     harris41 8247:     return 'ok';
1.80      www      8248: }
                   8249: 
1.81      www      8250: # --------------------------------------------------------------- Modify a user
1.80      www      8251: 
1.81      www      8252: sub modifyuser {
1.206     matthew  8253:     my ($udom,    $uname, $uid,
                   8254:         $umode,   $upass, $first,
                   8255:         $middle,  $last,  $gene,
1.1058    raeburn  8256:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8257:     $udom= &LONCAPA::clean_domain($udom);
                   8258:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8259:     my $showcandelete = 'none';
                   8260:     if (ref($candelete) eq 'ARRAY') {
                   8261:         if (@{$candelete} > 0) {
                   8262:             $showcandelete = join(', ',@{$candelete});
                   8263:         }
                   8264:     }
1.81      www      8265:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8266:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8267: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8268:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8269:                                      ' desiredhome not specified'). 
1.620     albertel 8270:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8271:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8272:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8273:     my $newuser;
                   8274:     if ($uhome eq 'no_host') {
                   8275:         $newuser = 1;
                   8276:     }
1.80      www      8277: # ----------------------------------------------------------------- Create User
1.406     albertel 8278:     if (($uhome eq 'no_host') && 
                   8279: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8280:         my $unhome='';
1.844     albertel 8281:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8282:             $unhome = $desiredhome;
1.620     albertel 8283: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8284: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8285:         } else { # load balancing routine for determining $unhome
1.81      www      8286:             my $loadm=10000000;
1.841     albertel 8287: 	    my %servers = &get_servers($udom,'library');
                   8288: 	    foreach my $tryserver (keys(%servers)) {
                   8289: 		my $answer=reply('load',$tryserver);
                   8290: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8291: 		    $loadm=$answer;
                   8292: 		    $unhome=$tryserver;
                   8293: 		}
1.80      www      8294: 	    }
                   8295:         }
                   8296:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8297: 	    return 'error: unable to find a home server for '.$uname.
                   8298:                    ' in domain '.$udom;
1.80      www      8299:         }
                   8300:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8301:                          &escape($upass),$unhome);
                   8302: 	unless ($reply eq 'ok') {
                   8303:             return 'error: '.$reply;
                   8304:         }   
1.230     stredwic 8305:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8306:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8307: 	    return 'error: unable verify users home machine.';
1.80      www      8308:         }
1.209     matthew  8309:     }   # End of creation of new user
1.80      www      8310: # ---------------------------------------------------------------------- Add ID
                   8311:     if ($uid) {
                   8312:        $uid=~tr/A-Z/a-z/;
                   8313:        my %uidhash=&idrget($udom,$uname);
1.196     www      8314:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8315:          && (!$forceid)) {
1.80      www      8316: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8317: 	      return 'error: user id "'.$uid.'" does not match '.
                   8318:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8319:           }
                   8320:        } else {
                   8321: 	  &idput($udom,($uname => $uid));
                   8322:        }
                   8323:     }
                   8324: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8325:     my @tmp=&get('environment',
1.899     raeburn  8326: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8327:                     'permanentemail','inststatus'],
1.134     albertel 8328: 		   $udom,$uname);
1.1075    raeburn  8329:     my (%names,%oldnames);
1.313     matthew  8330:     if ($tmp[0] =~ m/^error:.*/) { 
                   8331:         %names=(); 
                   8332:     } else {
                   8333:         %names = @tmp;
1.1075    raeburn  8334:         %oldnames = %names;
1.313     matthew  8335:     }
1.388     www      8336: #
1.1058    raeburn  8337: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8338: # of users did not contain them), do not overwrite existing values
                   8339: # unless field is in $candelete array ref.  
                   8340: #
                   8341: 
                   8342:     my @fields = ('firstname','middlename','lastname','generation',
                   8343:                   'permanentemail','id');
                   8344:     my %newvalues;
                   8345:     if (ref($candelete) eq 'ARRAY') {
                   8346:         foreach my $field (@fields) {
                   8347:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8348:                 if ($field eq 'firstname') {
                   8349:                     $names{$field} = $first;
                   8350:                 } elsif ($field eq 'middlename') {
                   8351:                     $names{$field} = $middle;
                   8352:                 } elsif ($field eq 'lastname') {
                   8353:                     $names{$field} = $last;
                   8354:                 } elsif ($field eq 'generation') { 
                   8355:                     $names{$field} = $gene;
                   8356:                 } elsif ($field eq 'permanentemail') {
                   8357:                     $names{$field} = $email;
                   8358:                 } elsif ($field eq 'id') {
                   8359:                     $names{$field}  = $uid;
                   8360:                 }
                   8361:             }
                   8362:         }
                   8363:     }
1.388     www      8364:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8365:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8366:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8367:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8368:     if ($email) {
                   8369:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8370:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8371:     }
1.899     raeburn  8372:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8373:     if (defined($inststatus)) {
                   8374:         $names{'inststatus'} = '';
                   8375:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8376:         if (ref($usertypes) eq 'HASH') {
                   8377:             my @okstatuses; 
                   8378:             foreach my $item (split(/:/,$inststatus)) {
                   8379:                 if (defined($usertypes->{$item})) {
                   8380:                     push(@okstatuses,$item);  
                   8381:                 }
                   8382:             }
                   8383:             if (@okstatuses) {
                   8384:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8385:             }
                   8386:         }
                   8387:     }
1.1075    raeburn  8388:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8389:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8390:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8391:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8392:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8393:     } else {
                   8394:         $logmsg .= ' during self creation';
                   8395:     }
1.1075    raeburn  8396:     my $changed;
                   8397:     if ($newuser) {
                   8398:         $changed = 1;
                   8399:     } else {
                   8400:         foreach my $field (@fields) {
                   8401:             if ($names{$field} ne $oldnames{$field}) {
                   8402:                 $changed = 1;
                   8403:                 last;
                   8404:             }
                   8405:         }
                   8406:     }
                   8407:     unless ($changed) {
                   8408:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8409:         &logthis($logmsg);
                   8410:         return 'ok';
                   8411:     }
                   8412:     my $reply = &put('environment', \%names, $udom,$uname);
                   8413:     if ($reply ne 'ok') { 
                   8414:         return 'error: '.$reply;
                   8415:     }
1.1087    raeburn  8416:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8417:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8418:     }
1.1075    raeburn  8419:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8420:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8421:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8422:     &logthis($logmsg);
1.134     albertel 8423:     return 'ok';
1.80      www      8424: }
                   8425: 
1.81      www      8426: # -------------------------------------------------------------- Modify student
1.80      www      8427: 
1.81      www      8428: sub modifystudent {
                   8429:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8430:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8431:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8432:     if (!$cid) {
1.620     albertel 8433: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8434: 	    return 'not_in_class';
                   8435: 	}
1.80      www      8436:     }
                   8437: # --------------------------------------------------------------- Make the user
1.81      www      8438:     my $reply=&modifyuser
1.209     matthew  8439: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8440:          $desiredhome,$email,$inststatus);
1.80      www      8441:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8442:     # This will cause &modify_student_enrollment to get the uid from the
                   8443:     # students environment
                   8444:     $uid = undef if (!$forceid);
1.455     albertel 8445:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8446: 					$gene,$usec,$end,$start,$type,$locktype,
                   8447:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8448:     return $reply;
                   8449: }
                   8450: 
                   8451: sub modify_student_enrollment {
1.1172.2.23  raeburn  8452:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8453:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8454:     my ($cdom,$cnum,$chome);
                   8455:     if (!$cid) {
1.620     albertel 8456: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8457: 	    return 'not_in_class';
                   8458: 	}
1.620     albertel 8459: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8460: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8461:     } else {
                   8462: 	($cdom,$cnum)=split(/_/,$cid);
                   8463:     }
1.620     albertel 8464:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8465:     if (!$chome) {
1.457     raeburn  8466: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8467:     }
1.455     albertel 8468:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8469:     # Make sure the user exists
1.81      www      8470:     my $uhome=&homeserver($uname,$udom);
                   8471:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8472: 	return 'error: no such user';
                   8473:     }
1.297     matthew  8474:     # Get student data if we were not given enough information
                   8475:     if (!defined($first)  || $first  eq '' || 
                   8476:         !defined($last)   || $last   eq '' || 
                   8477:         !defined($uid)    || $uid    eq '' || 
                   8478:         !defined($middle) || $middle eq '' || 
                   8479:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8480:         # They did not supply us with enough data to enroll the student, so
                   8481:         # we need to pick up more information.
1.297     matthew  8482:         my %tmp = &get('environment',
1.294     matthew  8483:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8484:                        ,$udom,$uname);
                   8485: 
1.800     albertel 8486:         #foreach my $key (keys(%tmp)) {
                   8487:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8488:         #}
1.294     matthew  8489:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8490:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8491:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8492:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8493:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8494:     }
1.556     albertel 8495:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8496:     my $user = "$uname:$udom";
                   8497:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8498:     my $reply=cput('classlist',
1.1148    raeburn  8499: 		   {$user => 
1.1172.2.19  raeburn  8500: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8501: 		   $cdom,$cnum);
1.1148    raeburn  8502:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8503:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8504:     } else { 
1.81      www      8505: 	return 'error: '.$reply;
                   8506:     }
1.297     matthew  8507:     # Add student role to user
1.83      www      8508:     my $uurl='/'.$cid;
1.81      www      8509:     $uurl=~s/\_/\//g;
                   8510:     if ($usec) {
                   8511: 	$uurl.='/'.$usec;
                   8512:     }
1.1148    raeburn  8513:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8514:                              $selfenroll,$context);
                   8515:     if ($result ne 'ok') {
                   8516:         if ($old_entry{$user} ne '') {
                   8517:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8518:         } else {
                   8519:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8520:         }
                   8521:     }
                   8522:     return $result; 
1.21      www      8523: }
                   8524: 
1.556     albertel 8525: sub format_name {
                   8526:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8527:     my $name;
                   8528:     if ($first ne 'lastname') {
                   8529: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8530:     } else {
                   8531: 	if ($lastname=~/\S/) {
                   8532: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8533: 	    $name=~s/\s+,/,/;
                   8534: 	} else {
                   8535: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8536: 	}
                   8537:     }
                   8538:     $name=~s/^\s+//;
                   8539:     $name=~s/\s+$//;
                   8540:     $name=~s/\s+/ /g;
                   8541:     return $name;
                   8542: }
                   8543: 
1.84      www      8544: # ------------------------------------------------- Write to course preferences
                   8545: 
                   8546: sub writecoursepref {
                   8547:     my ($courseid,%prefs)=@_;
                   8548:     $courseid=~s/^\///;
                   8549:     $courseid=~s/\_/\//g;
                   8550:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8551:     my $chome=homeserver($cnum,$cdomain);
                   8552:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8553: 	return 'error: no such course';
                   8554:     }
                   8555:     my $cstring='';
1.800     albertel 8556:     foreach my $pref (keys(%prefs)) {
                   8557: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8558:     }
1.84      www      8559:     $cstring=~s/\&$//;
                   8560:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8561: }
                   8562: 
                   8563: # ---------------------------------------------------------- Make/modify course
                   8564: 
                   8565: sub createcourse {
1.741     raeburn  8566:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8567:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8568:     $url=&declutter($url);
                   8569:     my $cid='';
1.1028    raeburn  8570:     if ($context eq 'requestcourses') {
                   8571:         my $can_create = 0;
                   8572:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8573:         if ($udom eq $ownerdom) {
                   8574:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8575:                                   $context)) {
                   8576:                 $can_create = 1;
                   8577:             }
                   8578:         } else {
                   8579:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8580:                                            $category);
                   8581:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8582:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8583:                 if (@curr > 0) {
                   8584:                     my @options = qw(approval validate autolimit);
                   8585:                     my $optregex = join('|',@options);
                   8586:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8587:                         $can_create = 1;
                   8588:                     }
                   8589:                 }
                   8590:             }
                   8591:         }
                   8592:         if ($can_create) {
                   8593:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8594:                 unless (&allowed('ccc',$udom)) {
                   8595:                     return 'refused'; 
                   8596:                 }
1.1017    raeburn  8597:             }
                   8598:         } else {
                   8599:             return 'refused';
                   8600:         }
1.1028    raeburn  8601:     } elsif (!&allowed('ccc',$udom)) {
                   8602:         return 'refused';
1.84      www      8603:     }
1.1011    raeburn  8604: # --------------------------------------------------------------- Get Unique ID
                   8605:     my $uname;
                   8606:     if ($cnum =~ /^$match_courseid$/) {
                   8607:         my $chome=&homeserver($cnum,$udom,'true');
                   8608:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8609:             $uname = $cnum;
                   8610:         } else {
1.1038    raeburn  8611:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8612:         }
                   8613:     } else {
1.1038    raeburn  8614:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8615:     }
                   8616:     return $uname if ($uname =~ /^error/);
                   8617: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8618:     if (!defined($course_server)) {
                   8619:         if (defined(&domain($udom,'primary'))) {
                   8620:             $course_server = &domain($udom,'primary');
                   8621:         } else {
                   8622:             $course_server = $env{'user.home'}; 
                   8623:         }
                   8624:     }
                   8625:     my %host_servers =
                   8626:         &Apache::lonnet::get_servers($udom,'library');
                   8627:     unless ($host_servers{$course_server}) {
                   8628:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8629:     }
1.84      www      8630: # ------------------------------------------------------------- Make the course
                   8631:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8632:                       $course_server);
1.84      www      8633:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8634:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8635:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8636: 	return 'error: no such course';
                   8637:     }
1.271     www      8638: # ----------------------------------------------------------------- Course made
1.516     raeburn  8639: # log existence
1.1029    raeburn  8640:     my $now = time;
1.918     raeburn  8641:     my $newcourse = {
                   8642:                     $udom.'_'.$uname => {
1.921     raeburn  8643:                                      description => $description,
                   8644:                                      inst_code   => $inst_code,
                   8645:                                      owner       => $course_owner,
                   8646:                                      type        => $crstype,
1.1029    raeburn  8647:                                      creator     => $env{'user.name'}.':'.
                   8648:                                                     $env{'user.domain'},
                   8649:                                      created     => $now,
                   8650:                                      context     => $context,
1.918     raeburn  8651:                                                 },
                   8652:                     };
1.921     raeburn  8653:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8654: # set toplevel url
1.271     www      8655:     my $topurl=$url;
                   8656:     unless ($nonstandard) {
                   8657: # ------------------------------------------ For standard courses, make top url
                   8658:         my $mapurl=&clutter($url);
1.278     www      8659:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8660:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8661: <map>
                   8662: <resource id="1" type="start"></resource>
                   8663: <resource id="2" src="$mapurl"></resource>
                   8664: <resource id="3" type="finish"></resource>
                   8665: <link index="1" from="1" to="2"></link>
                   8666: <link index="2" from="2" to="3"></link>
                   8667: </map>
                   8668: ENDINITMAP
                   8669:         $topurl=&declutter(
1.638     albertel 8670:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8671:                           );
                   8672:     }
                   8673: # ----------------------------------------------------------- Write preferences
1.84      www      8674:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8675:                      ('description'              => $description,
                   8676:                       'url'                      => $topurl,
                   8677:                       'internal.creator'         => $env{'user.name'}.':'.
                   8678:                                                     $env{'user.domain'},
                   8679:                       'internal.created'         => $now,
                   8680:                       'internal.creationcontext' => $context)
                   8681:                     );
1.84      www      8682:     return '/'.$udom.'/'.$uname;
                   8683: }
                   8684: 
1.1011    raeburn  8685: # ------------------------------------------------------------------- Create ID
                   8686: sub generate_coursenum {
1.1038    raeburn  8687:     my ($udom,$crstype) = @_;
1.1011    raeburn  8688:     my $domdesc = &domain($udom);
                   8689:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8690:     my $first;
                   8691:     if ($crstype eq 'Community') {
                   8692:         $first = '0';
                   8693:     } else {
                   8694:         $first = int(1+rand(9)); 
                   8695:     } 
                   8696:     my $uname=$first.
1.1011    raeburn  8697:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8698:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8699:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8700: # ----------------------------------------------- Make sure that does not exist
                   8701:     my $uhome=&homeserver($uname,$udom,'true');
                   8702:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8703:         if ($crstype eq 'Community') {
                   8704:             $first = '0';
                   8705:         } else {
                   8706:             $first = int(1+rand(9));
                   8707:         }
                   8708:         $uname=$first.
1.1011    raeburn  8709:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8710:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8711:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8712:         $uhome=&homeserver($uname,$udom,'true');
                   8713:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8714:             return 'error: unable to generate unique course-ID';
                   8715:         }
                   8716:     }
                   8717:     return $uname;
                   8718: }
                   8719: 
1.813     albertel 8720: sub is_course {
1.1167    droeschl 8721:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8722:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8723: 
                   8724:     return unless $cdom and $cnum;
                   8725: 
                   8726:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8727:         '.');
                   8728: 
1.1172.2.23  raeburn  8729:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8730:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8731: }
                   8732: 
1.1015    raeburn  8733: sub store_userdata {
                   8734:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8735:     my $result;
1.1016    raeburn  8736:     if ($datakey ne '') {
1.1013    raeburn  8737:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8738:             if ($udom eq '' || $uname eq '') {
                   8739:                 $udom = $env{'user.domain'};
                   8740:                 $uname = $env{'user.name'};
                   8741:             }
                   8742:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8743:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8744:                 $result = 'error: no_host';
                   8745:             } else {
                   8746:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8747:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8748: 
                   8749:                 my $namevalue='';
                   8750:                 foreach my $key (keys(%{$storehash})) {
                   8751:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8752:                 }
                   8753:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  8754:                 unless ($namespace eq 'courserequests') {
                   8755:                     $datakey = &escape($datakey);
                   8756:                 }
1.1105    raeburn  8757:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8758:                                   $namevalue,$uhome);
1.1013    raeburn  8759:             }
                   8760:         } else {
                   8761:             $result = 'error: data to store was not a hash reference'; 
                   8762:         }
                   8763:     } else {
                   8764:         $result= 'error: invalid requestkey'; 
                   8765:     }
                   8766:     return $result;
                   8767: }
                   8768: 
1.21      www      8769: # ---------------------------------------------------------- Assign Custom Role
                   8770: 
                   8771: sub assigncustomrole {
1.957     raeburn  8772:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8773:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8774:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8775: }
                   8776: 
                   8777: # ----------------------------------------------------------------- Revoke Role
                   8778: 
                   8779: sub revokerole {
1.957     raeburn  8780:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8781:     my $now=time;
1.965     raeburn  8782:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8783: }
                   8784: 
                   8785: # ---------------------------------------------------------- Revoke Custom Role
                   8786: 
                   8787: sub revokecustomrole {
1.957     raeburn  8788:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8789:     my $now=time;
1.357     www      8790:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8791:            $deleteflag,$selfenroll,$context);
1.17      www      8792: }
                   8793: 
1.533     banghart 8794: # ------------------------------------------------------------ Disk usage
1.535     albertel 8795: sub diskusage {
1.955     raeburn  8796:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8797:     $directorypath =~ s/\/$//;
                   8798:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8799:                        .&escape($getpropath).':'.&escape($uname).':'
                   8800:                        .&escape($udom),homeserver($uname,$udom));
                   8801:     if ($listing eq 'unknown_cmd') {
                   8802:         if ($getpropath) {
                   8803:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8804:         }
                   8805:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8806:     }
1.514     albertel 8807:     return $listing;
1.512     banghart 8808: }
                   8809: 
1.566     banghart 8810: sub is_locked {
1.1096    raeburn  8811:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8812:     my @check;
                   8813:     my $is_locked;
1.1093    raeburn  8814:     push (@check,$file_name);
1.613     albertel 8815:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8816: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8817:     my ($tmp)=keys(%locked);
                   8818:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8819:     
1.566     banghart 8820:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8821:         $is_locked = 'false';
                   8822:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8823:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8824:                $is_locked = 'true';
1.1096    raeburn  8825:                if (ref($which) eq 'ARRAY') {
                   8826:                    push(@{$which},$entry);
                   8827:                } else {
                   8828:                    last;
                   8829:                }
1.745     raeburn  8830:            }
                   8831:        }
1.566     banghart 8832:     } else {
                   8833:         $is_locked = 'false';
                   8834:     }
1.1093    raeburn  8835:     return $is_locked;
1.566     banghart 8836: }
                   8837: 
1.759     albertel 8838: sub declutter_portfile {
                   8839:     my ($file) = @_;
1.833     albertel 8840:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8841:     return $file;
                   8842: }
                   8843: 
1.559     banghart 8844: # ------------------------------------------------------------- Mark as Read Only
                   8845: 
                   8846: sub mark_as_readonly {
                   8847:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8848:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8849:     my ($tmp)=keys(%current_permissions);
                   8850:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8851:     foreach my $file (@{$files}) {
1.759     albertel 8852: 	$file = &declutter_portfile($file);
1.561     banghart 8853:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8854:     }
1.613     albertel 8855:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8856:     return;
                   8857: }
                   8858: 
1.572     banghart 8859: # ------------------------------------------------------------Save Selected Files
                   8860: 
                   8861: sub save_selected_files {
                   8862:     my ($user, $path, @files) = @_;
                   8863:     my $filename = $user."savedfiles";
1.573     banghart 8864:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8865:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8866:     foreach my $file (@files) {
1.620     albertel 8867:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8868:     }
                   8869:     foreach my $file (@other_files) {
1.574     banghart 8870:         print (OUT $file."\n");
1.572     banghart 8871:     }
1.574     banghart 8872:     close (OUT);
1.572     banghart 8873:     return 'ok';
                   8874: }
                   8875: 
1.574     banghart 8876: sub clear_selected_files {
                   8877:     my ($user) = @_;
                   8878:     my $filename = $user."savedfiles";
1.1117    foxr     8879:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8880:     print (OUT undef);
                   8881:     close (OUT);
                   8882:     return ("ok");    
                   8883: }
                   8884: 
1.572     banghart 8885: sub files_in_path {
                   8886:     my ($user, $path) = @_;
                   8887:     my $filename = $user."savedfiles";
                   8888:     my %return_files;
1.1117    foxr     8889:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8890:     while (my $line_in = <IN>) {
1.574     banghart 8891:         chomp ($line_in);
                   8892:         my @paths_and_file = split (m!/!, $line_in);
                   8893:         my $file_part = pop (@paths_and_file);
                   8894:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8895:         $path_part.='/';
                   8896:         my $path_and_file = $path_part.$file_part;
                   8897:         if ($path_part eq $path) {
                   8898:             $return_files{$file_part}= 'selected';
                   8899:         }
                   8900:     }
1.574     banghart 8901:     close (IN);
                   8902:     return (\%return_files);
1.572     banghart 8903: }
                   8904: 
                   8905: # called in portfolio select mode, to show files selected NOT in current directory
                   8906: sub files_not_in_path {
                   8907:     my ($user, $path) = @_;
                   8908:     my $filename = $user."savedfiles";
                   8909:     my @return_files;
                   8910:     my $path_part;
1.1117    foxr     8911:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8912:     while (my $line = <IN>) {
1.572     banghart 8913:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8914:         my @paths_and_file = split(m|/|, $line);
                   8915:         my $file_part = pop(@paths_and_file);
                   8916:         chomp($file_part);
                   8917:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8918:         $path_part .= '/';
                   8919:         my $path_and_file = $path_part.$file_part;
                   8920:         if ($path_part ne $path) {
1.800     albertel 8921:             push(@return_files, ($path_and_file));
1.572     banghart 8922:         }
                   8923:     }
1.800     albertel 8924:     close(OUT);
1.574     banghart 8925:     return (@return_files);
1.572     banghart 8926: }
                   8927: 
1.745     raeburn  8928: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8929: 
1.745     raeburn  8930: sub get_portfile_permissions {
                   8931:     my ($domain,$user) = @_;
1.613     albertel 8932:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8933:     my ($tmp)=keys(%current_permissions);
                   8934:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8935:     return \%current_permissions;
                   8936: }
                   8937: 
                   8938: #---------------------------------------------Get portfolio file access controls
                   8939: 
1.749     raeburn  8940: sub get_access_controls {
1.745     raeburn  8941:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8942:     my %access;
                   8943:     my $real_file = $file;
                   8944:     $file =~ s/\.meta$//;
1.745     raeburn  8945:     if (defined($file)) {
1.749     raeburn  8946:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8947:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8948:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8949:             }
                   8950:         }
1.745     raeburn  8951:     } else {
1.749     raeburn  8952:         foreach my $key (keys(%{$current_permissions})) {
                   8953:             if ($key =~ /\0accesscontrol$/) {
                   8954:                 if (defined($group)) {
                   8955:                     if ($key !~ m-^\Q$group\E/-) {
                   8956:                         next;
                   8957:                     }
                   8958:                 }
                   8959:                 my ($fullpath) = split(/\0/,$key);
                   8960:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8961:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8962:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8963:                     }
                   8964:                 }
                   8965:             }
                   8966:         }
                   8967:     }
                   8968:     return %access;
                   8969: }
                   8970: 
                   8971: sub modify_access_controls {
                   8972:     my ($file_name,$changes,$domain,$user)=@_;
                   8973:     my ($outcome,$deloutcome);
                   8974:     my %store_permissions;
                   8975:     my %new_values;
                   8976:     my %new_control;
                   8977:     my %translation;
                   8978:     my @deletions = ();
                   8979:     my $now = time;
                   8980:     if (exists($$changes{'activate'})) {
                   8981:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8982:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8983:             my $numnew = scalar(@newitems);
                   8984:             for (my $i=0; $i<$numnew; $i++) {
                   8985:                 my $newkey = $newitems[$i];
                   8986:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8987:                 if ($newkey =~ /^\d+:/) { 
                   8988:                     $newkey =~ s/^(\d+)/$newid/;
                   8989:                     $translation{$1} = $newid;
                   8990:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8991:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8992:                     $translation{$1} = $newid;
                   8993:                 }
1.749     raeburn  8994:                 $new_values{$file_name."\0".$newkey} = 
                   8995:                                           $$changes{'activate'}{$newitems[$i]};
                   8996:                 $new_control{$newkey} = $now;
                   8997:             }
                   8998:         }
                   8999:     }
                   9000:     my %todelete;
                   9001:     my %changed_items;
                   9002:     foreach my $action ('delete','update') {
                   9003:         if (exists($$changes{$action})) {
                   9004:             if (ref($$changes{$action}) eq 'HASH') {
                   9005:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9006:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9007:                     if ($action eq 'delete') { 
                   9008:                         $todelete{$itemnum} = 1;
                   9009:                     } else {
                   9010:                         $changed_items{$itemnum} = $key;
                   9011:                     }
                   9012:                 }
1.745     raeburn  9013:             }
                   9014:         }
1.749     raeburn  9015:     }
                   9016:     # get lock on access controls for file.
                   9017:     my $lockhash = {
                   9018:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9019:                                                        ':'.$env{'user.domain'},
                   9020:                    }; 
                   9021:     my $tries = 0;
                   9022:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9023:    
                   9024:     while (($gotlock ne 'ok') && $tries <3) {
                   9025:         $tries ++;
                   9026:         sleep 1;
                   9027:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9028:     }
                   9029:     if ($gotlock eq 'ok') {
                   9030:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9031:         my ($tmp)=keys(%curr_permissions);
                   9032:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9033:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9034:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9035:             if (ref($curr_controls) eq 'HASH') {
                   9036:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9037:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9038:                     if (defined($todelete{$itemnum})) {
                   9039:                         push(@deletions,$file_name."\0".$control_item);
                   9040:                     } else {
                   9041:                         if (defined($changed_items{$itemnum})) {
                   9042:                             $new_control{$changed_items{$itemnum}} = $now;
                   9043:                             push(@deletions,$file_name."\0".$control_item);
                   9044:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9045:                         } else {
                   9046:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9047:                         }
                   9048:                     }
1.745     raeburn  9049:                 }
                   9050:             }
                   9051:         }
1.970     raeburn  9052:         my ($group);
                   9053:         if (&is_course($domain,$user)) {
                   9054:             ($group,my $file) = split(/\//,$file_name,2);
                   9055:         }
1.749     raeburn  9056:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9057:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9058:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9059:         #  remove lock
                   9060:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9061:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9062:         my $sqlresult =
1.970     raeburn  9063:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9064:                                     $group);
1.749     raeburn  9065:     } else {
                   9066:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9067:     }
1.749     raeburn  9068:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9069: }
                   9070: 
1.827     raeburn  9071: sub make_public_indefinitely {
                   9072:     my ($requrl) = @_;
                   9073:     my $now = time;
                   9074:     my $action = 'activate';
                   9075:     my $aclnum = 0;
                   9076:     if (&is_portfolio_url($requrl)) {
                   9077:         my (undef,$udom,$unum,$file_name,$group) =
                   9078:             &parse_portfolio_url($requrl);
                   9079:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9080:         my %access_controls = &get_access_controls($current_perms,
                   9081:                                                    $group,$file_name);
                   9082:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9083:             my ($num,$scope,$end,$start) = 
                   9084:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9085:             if ($scope eq 'public') {
                   9086:                 if ($start <= $now && $end == 0) {
                   9087:                     $action = 'none';
                   9088:                 } else {
                   9089:                     $action = 'update';
                   9090:                     $aclnum = $num;
                   9091:                 }
                   9092:                 last;
                   9093:             }
                   9094:         }
                   9095:         if ($action eq 'none') {
                   9096:              return 'ok';
                   9097:         } else {
                   9098:             my %changes;
                   9099:             my $newend = 0;
                   9100:             my $newstart = $now;
                   9101:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9102:             $changes{$action}{$newkey} = {
                   9103:                 type => 'public',
                   9104:                 time => {
                   9105:                     start => $newstart,
                   9106:                     end   => $newend,
                   9107:                 },
                   9108:             };
                   9109:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9110:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9111:             return $outcome;
                   9112:         }
                   9113:     } else {
                   9114:         return 'invalid';
                   9115:     }
                   9116: }
                   9117: 
1.745     raeburn  9118: #------------------------------------------------------Get Marked as Read Only
                   9119: 
                   9120: sub get_marked_as_readonly {
                   9121:     my ($domain,$user,$what,$group) = @_;
                   9122:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9123:     my @readonly_files;
1.629     banghart 9124:     my $cmp1=$what;
                   9125:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9126:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9127:         if (defined($group)) {
                   9128:             if ($file_name !~ m-^\Q$group\E/-) {
                   9129:                 next;
                   9130:             }
                   9131:         }
1.561     banghart 9132:         if (ref($value) eq "ARRAY"){
                   9133:             foreach my $stored_what (@{$value}) {
1.629     banghart 9134:                 my $cmp2=$stored_what;
1.759     albertel 9135:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9136:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9137:                 }
1.629     banghart 9138:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9139:                     push(@readonly_files, $file_name);
1.745     raeburn  9140:                     last;
1.563     banghart 9141:                 } elsif (!defined($what)) {
                   9142:                     push(@readonly_files, $file_name);
1.745     raeburn  9143:                     last;
1.561     banghart 9144:                 }
                   9145:             }
1.745     raeburn  9146:         }
1.561     banghart 9147:     }
                   9148:     return @readonly_files;
                   9149: }
1.577     banghart 9150: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9151: 
1.577     banghart 9152: sub get_marked_as_readonly_hash {
1.745     raeburn  9153:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9154:     my %readonly_files;
1.745     raeburn  9155:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9156:         if (defined($group)) {
                   9157:             if ($file_name !~ m-^\Q$group\E/-) {
                   9158:                 next;
                   9159:             }
                   9160:         }
1.577     banghart 9161:         if (ref($value) eq "ARRAY"){
                   9162:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9163:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9164:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9165:                         if ($lock_descriptor eq 'graded') {
                   9166:                             $readonly_files{$file_name} = 'graded';
                   9167:                         } elsif ($lock_descriptor eq 'handback') {
                   9168:                             $readonly_files{$file_name} = 'handback';
                   9169:                         } else {
                   9170:                             if (!exists($readonly_files{$file_name})) {
                   9171:                                 $readonly_files{$file_name} = 'locked';
                   9172:                             }
                   9173:                         }
1.745     raeburn  9174:                     }
1.750     banghart 9175:                 } 
1.577     banghart 9176:             }
                   9177:         } 
                   9178:     }
                   9179:     return %readonly_files;
                   9180: }
1.559     banghart 9181: # ------------------------------------------------------------ Unmark as Read Only
                   9182: 
                   9183: sub unmark_as_readonly {
1.629     banghart 9184:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9185:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9186:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9187:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9188:     my $symb_crs = $what;
                   9189:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9190:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9191:     my ($tmp)=keys(%current_permissions);
                   9192:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9193:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9194:     foreach my $file (@readonly_files) {
1.759     albertel 9195: 	my $clean_file = &declutter_portfile($file);
                   9196: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9197: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9198:         my @new_locks;
                   9199:         my @del_keys;
                   9200:         if (ref($current_locks) eq "ARRAY"){
                   9201:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9202:                 my $compare=$locker;
1.749     raeburn  9203:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9204:                     $compare=join('',@{$locker});
1.746     raeburn  9205:                     if ($compare ne $symb_crs) {
                   9206:                         push(@new_locks, $locker);
                   9207:                     }
1.563     banghart 9208:                 }
                   9209:             }
1.650     albertel 9210:             if (scalar(@new_locks) > 0) {
1.563     banghart 9211:                 $current_permissions{$file} = \@new_locks;
                   9212:             } else {
                   9213:                 push(@del_keys, $file);
1.613     albertel 9214:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9215:                 delete($current_permissions{$file});
1.563     banghart 9216:             }
                   9217:         }
1.561     banghart 9218:     }
1.613     albertel 9219:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9220:     return;
                   9221: }
1.512     banghart 9222: 
1.17      www      9223: # ------------------------------------------------------------ Directory lister
                   9224: 
                   9225: sub dirlist {
1.955     raeburn  9226:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9227:     $uri=~s/^\///;
                   9228:     $uri=~s/\/$//;
1.253     stredwic 9229:     my ($udom, $uname);
1.955     raeburn  9230:     if ($getuserdir) {
1.253     stredwic 9231:         $udom = $userdomain;
                   9232:         $uname = $username;
1.955     raeburn  9233:     } else {
                   9234:         (undef,$udom,$uname)=split(/\//,$uri);
                   9235:         if(defined($userdomain)) {
                   9236:             $udom = $userdomain;
                   9237:         }
                   9238:         if(defined($username)) {
                   9239:             $uname = $username;
                   9240:         }
1.253     stredwic 9241:     }
1.955     raeburn  9242:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9243: 
1.955     raeburn  9244:     $dirRoot = $perlvar{'lonDocRoot'};
                   9245:     if (defined($getpropath)) {
                   9246:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9247:         $dirRoot =~ s/\/$//;
1.955     raeburn  9248:     } elsif (defined($getuserdir)) {
                   9249:         my $subdir=$uname.'__';
                   9250:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9251:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9252:                    ."/$udom/$subdir/$uname";
                   9253:     } elsif (defined($alternateRoot)) {
                   9254:         $dirRoot = $alternateRoot;
1.751     banghart 9255:     }
1.253     stredwic 9256: 
                   9257:     if($udom) {
                   9258:         if($uname) {
1.1135    raeburn  9259:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9260:             if ($uhome eq 'no_host') {
                   9261:                 return ([],'no_host');
                   9262:             }
1.955     raeburn  9263:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9264:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9265:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9266:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9267:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9268:             } else {
                   9269:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9270:             }
1.605     matthew  9271:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9272:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9273:                 @listing_results = split(/:/,$listing);
                   9274:             } else {
                   9275:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9276:             }
1.1135    raeburn  9277:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9278:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9279:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9280:                 return ([],$listing);
                   9281:             } else {
                   9282:                 return (\@listing_results);
1.1135    raeburn  9283:             }
1.955     raeburn  9284:         } elsif(!$alternateRoot) {
1.1136    raeburn  9285:             my (%allusers,%listerror);
1.841     albertel 9286: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9287:  	    foreach my $tryserver (keys(%servers)) {
                   9288:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9289:                                   &escape($udom),$tryserver);
                   9290:                 if ($listing eq 'unknown_cmd') {
                   9291: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9292: 				      $udom, $tryserver);
                   9293:                 } else {
                   9294:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9295:                 }
1.841     albertel 9296: 		if ($listing eq 'unknown_cmd') {
                   9297: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9298: 				      $udom, $tryserver);
                   9299: 		    @listing_results = split(/:/,$listing);
                   9300: 		} else {
                   9301: 		    @listing_results =
                   9302: 			map { &unescape($_); } split(/:/,$listing);
                   9303: 		}
1.1136    raeburn  9304:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9305:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9306:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9307:                     $listerror{$tryserver} = $listing;
                   9308:                 } else {
1.841     albertel 9309: 		    foreach my $line (@listing_results) {
                   9310: 			my ($entry) = split(/&/,$line,2);
                   9311: 			$allusers{$entry} = 1;
                   9312: 		    }
                   9313: 		}
1.253     stredwic 9314:             }
1.1136    raeburn  9315:             my @alluserslist=();
1.800     albertel 9316:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9317:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9318:             }
1.1136    raeburn  9319:             return (\@alluserslist);
1.253     stredwic 9320:         } else {
1.1136    raeburn  9321:             return ([],'missing username');
1.253     stredwic 9322:         }
1.955     raeburn  9323:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9324:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9325:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9326:         return (\@all_domains);
1.955     raeburn  9327:     } else {
1.1136    raeburn  9328:         return ([],'missing domain');
1.275     stredwic 9329:     }
                   9330: }
                   9331: 
                   9332: # --------------------------------------------- GetFileTimestamp
                   9333: # This function utilizes dirlist and returns the date stamp for
                   9334: # when it was last modified.  It will also return an error of -1
                   9335: # if an error occurs
                   9336: 
                   9337: sub GetFileTimestamp {
1.955     raeburn  9338:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9339:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9340:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9341:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9342:                                     undef,$getuserdir);
                   9343:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9344:         return -1;
                   9345:     }
                   9346:     if (ref($fileref) eq 'ARRAY') {
                   9347:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9348:         # @stats contains first the filename, then the stat output
                   9349:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9350:     } else {
                   9351:         return -1;
1.253     stredwic 9352:     }
1.26      www      9353: }
                   9354: 
1.712     albertel 9355: sub stat_file {
                   9356:     my ($uri) = @_;
1.787     albertel 9357:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9358: 
1.955     raeburn  9359:     my ($udom,$uname,$file);
1.712     albertel 9360:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9361: 	($udom,$uname,$file) =
1.811     albertel 9362: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9363: 	$file = 'userfiles/'.$file;
                   9364:     }
                   9365:     if ($uri =~ m-^/res/-) {
                   9366: 	($udom,$uname) = 
1.807     albertel 9367: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9368: 	$file = $uri;
                   9369:     }
                   9370: 
                   9371:     if (!$udom || !$uname || !$file) {
                   9372: 	# unable to handle the uri
                   9373: 	return ();
                   9374:     }
1.956     raeburn  9375:     my $getpropath;
                   9376:     if ($file =~ /^userfiles\//) {
                   9377:         $getpropath = 1;
                   9378:     }
1.1136    raeburn  9379:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9380:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9381:         return ();
                   9382:     } else {
                   9383:         if (ref($listref) eq 'ARRAY') {
                   9384:             my @stats = split('&',$listref->[0]);
                   9385: 	    shift(@stats); #filename is first
                   9386: 	    return @stats;
                   9387:         }
1.712     albertel 9388:     }
                   9389:     return ();
                   9390: }
                   9391: 
1.26      www      9392: # -------------------------------------------------------- Value of a Condition
                   9393: 
1.713     albertel 9394: # gets the value of a specific preevaluated condition
                   9395: #    stored in the string  $env{user.state.<cid>}
                   9396: # or looks up a condition reference in the bighash and if if hasn't
                   9397: # already been evaluated recurses into docondval to get the value of
                   9398: # the condition, then memoizing it to 
                   9399: #   $env{user.state.<cid>.<condition>}
1.40      www      9400: sub directcondval {
                   9401:     my $number=shift;
1.620     albertel 9402:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9403: 	&Apache::lonuserstate::evalstate();
                   9404:     }
1.713     albertel 9405:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9406: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9407:     } elsif ($number =~ /^_/) {
                   9408: 	my $sub_condition;
                   9409: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9410: 		&GDBM_READER(),0640)) {
                   9411: 	    $sub_condition=$bighash{'conditions'.$number};
                   9412: 	    untie(%bighash);
                   9413: 	}
                   9414: 	my $value = &docondval($sub_condition);
1.949     raeburn  9415: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9416: 	return $value;
                   9417:     }
1.620     albertel 9418:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9419:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9420:     } else {
                   9421:        return 2;
                   9422:     }
                   9423: }
                   9424: 
1.713     albertel 9425: # get the collection of conditions for this resource
1.26      www      9426: sub condval {
                   9427:     my $condidx=shift;
1.54      www      9428:     my $allpathcond='';
1.713     albertel 9429:     foreach my $cond (split(/\|/,$condidx)) {
                   9430: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9431: 	    $allpathcond.=
                   9432: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9433: 	}
1.191     harris41 9434:     }
1.54      www      9435:     $allpathcond=~s/\|$//;
1.713     albertel 9436:     return &docondval($allpathcond);
                   9437: }
                   9438: 
                   9439: #evaluates an expression of conditions
                   9440: sub docondval {
                   9441:     my ($allpathcond) = @_;
                   9442:     my $result=0;
                   9443:     if ($env{'request.course.id'}
                   9444: 	&& defined($allpathcond)) {
                   9445: 	my $operand='|';
                   9446: 	my @stack;
                   9447: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9448: 	    if ($chunk eq '(') {
                   9449: 		push @stack,($operand,$result);
                   9450: 	    } elsif ($chunk eq ')') {
                   9451: 		my $before=pop @stack;
                   9452: 		if (pop @stack eq '&') {
                   9453: 		    $result=$result>$before?$before:$result;
                   9454: 		} else {
                   9455: 		    $result=$result>$before?$result:$before;
                   9456: 		}
                   9457: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9458: 		$operand=$chunk;
                   9459: 	    } else {
                   9460: 		my $new=directcondval($chunk);
                   9461: 		if ($operand eq '&') {
                   9462: 		    $result=$result>$new?$new:$result;
                   9463: 		} else {
                   9464: 		    $result=$result>$new?$result:$new;
                   9465: 		}
                   9466: 	    }
                   9467: 	}
1.26      www      9468:     }
                   9469:     return $result;
1.421     albertel 9470: }
                   9471: 
                   9472: # ---------------------------------------------------- Devalidate courseresdata
                   9473: 
                   9474: sub devalidatecourseresdata {
                   9475:     my ($coursenum,$coursedomain)=@_;
                   9476:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9477:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9478: }
                   9479: 
1.763     www      9480: 
1.200     www      9481: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9482: #
                   9483: #  Parameters:
                   9484: #      $coursenum    - Number of the course.
                   9485: #      $coursedomain - Domain at which the course was created.
                   9486: #  Returns:
                   9487: #     A hash of the course parameters along (I think) with timestamps
                   9488: #     and version info.
1.877     foxr     9489: 
1.624     albertel 9490: sub get_courseresdata {
                   9491:     my ($coursenum,$coursedomain)=@_;
1.200     www      9492:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9493:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9494:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9495:     my %dumpreply;
1.417     albertel 9496:     unless (defined($cached)) {
1.624     albertel 9497: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9498: 	$result=\%dumpreply;
1.251     albertel 9499: 	my ($tmp) = keys(%dumpreply);
                   9500: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9501: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9502: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9503: 	    return $tmp;
1.416     albertel 9504: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9505: 	    $result=undef;
1.599     albertel 9506: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9507: 	}
                   9508:     }
1.624     albertel 9509:     return $result;
                   9510: }
                   9511: 
1.633     albertel 9512: sub devalidateuserresdata {
                   9513:     my ($uname,$udom)=@_;
                   9514:     my $hashid="$udom:$uname";
                   9515:     &devalidate_cache_new('userres',$hashid);
                   9516: }
                   9517: 
1.624     albertel 9518: sub get_userresdata {
                   9519:     my ($uname,$udom)=@_;
                   9520:     #most student don\'t have any data set, check if there is some data
                   9521:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9522: 
                   9523:     my $hashid="$udom:$uname";
                   9524:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9525:     if (!defined($cached)) {
                   9526: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9527: 	$result=\%resourcedata;
                   9528: 	&do_cache_new('userres',$hashid,$result,600);
                   9529:     }
                   9530:     my ($tmp)=keys(%$result);
                   9531:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9532: 	return $result;
                   9533:     }
                   9534:     #error 2 occurs when the .db doesn't exist
                   9535:     if ($tmp!~/error: 2 /) {
1.672     albertel 9536: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9537: 		 " Trying to get resource data for ".
                   9538: 		 $uname." at ".$udom.": ".
                   9539: 		 $tmp."</font>");
                   9540:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9541: 	#&EXT_cache_set($udom,$uname);
                   9542: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9543: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9544:     }
                   9545:     return $tmp;
                   9546: }
1.879     foxr     9547: #----------------------------------------------- resdata - return resource data
                   9548: #  Purpose:
                   9549: #    Return resource data for either users or for a course.
                   9550: #  Parameters:
                   9551: #     $name      - Course/user name.
                   9552: #     $domain    - Name of the domain the user/course is registered on.
                   9553: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9554: #     @which     - Array of names of resources desired.
                   9555: #  Returns:
                   9556: #     The value of the first reasource in @which that is found in the
                   9557: #     resource hash.
                   9558: #  Exceptional Conditions:
                   9559: #     If the $type passed in is not valid (not the string 'course' or 
                   9560: #     'user', an undefined  reference is returned.
                   9561: #     If none of the resources are found, an undef is returned
1.624     albertel 9562: sub resdata {
                   9563:     my ($name,$domain,$type,@which)=@_;
                   9564:     my $result;
                   9565:     if ($type eq 'course') {
                   9566: 	$result=&get_courseresdata($name,$domain);
                   9567:     } elsif ($type eq 'user') {
                   9568: 	$result=&get_userresdata($name,$domain);
                   9569:     }
                   9570:     if (!ref($result)) { return $result; }    
1.251     albertel 9571:     foreach my $item (@which) {
1.927     albertel 9572: 	if (defined($result->{$item->[0]})) {
                   9573: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9574: 	}
1.250     albertel 9575:     }
1.291     albertel 9576:     return undef;
1.200     www      9577: }
                   9578: 
1.379     matthew  9579: #
                   9580: # EXT resource caching routines
                   9581: #
                   9582: 
                   9583: sub clear_EXT_cache_status {
1.383     albertel 9584:     &delenv('cache.EXT.');
1.379     matthew  9585: }
                   9586: 
                   9587: sub EXT_cache_status {
                   9588:     my ($target_domain,$target_user) = @_;
1.383     albertel 9589:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9590:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9591:         # We know already the user has no data
                   9592:         return 1;
                   9593:     } else {
                   9594:         return 0;
                   9595:     }
                   9596: }
                   9597: 
                   9598: sub EXT_cache_set {
                   9599:     my ($target_domain,$target_user) = @_;
1.383     albertel 9600:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9601:     #&appenv({$cachename => time});
1.379     matthew  9602: }
                   9603: 
1.28      www      9604: # --------------------------------------------------------- Value of a Variable
1.58      www      9605: sub EXT {
1.715     albertel 9606: 
1.1172.2.28! raeburn  9607:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9608:     unless ($varname) { return ''; }
1.218     albertel 9609:     #get real user name/domain, courseid and symb
                   9610:     my $courseid;
1.359     albertel 9611:     my $publicuser;
1.427     www      9612:     if ($symbparm) {
                   9613: 	$symbparm=&get_symb_from_alias($symbparm);
                   9614:     }
1.218     albertel 9615:     if (!($uname && $udom)) {
1.790     albertel 9616:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9617:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9618:     } else {
1.620     albertel 9619: 	$courseid=$env{'request.course.id'};
1.218     albertel 9620:     }
1.48      www      9621:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9622:     my $rest;
1.320     albertel 9623:     if (defined($therest[0])) {
1.48      www      9624:        $rest=join('.',@therest);
                   9625:     } else {
                   9626:        $rest='';
                   9627:     }
1.320     albertel 9628: 
1.57      www      9629:     my $qualifierrest=$qualifier;
                   9630:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9631:     my $spacequalifierrest=$space;
                   9632:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9633:     if ($realm eq 'user') {
1.48      www      9634: # --------------------------------------------------------------- user.resource
                   9635: 	if ($space eq 'resource') {
1.651     albertel 9636: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9637: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9638: 		 &&
1.744     albertel 9639: 		 ($symbparm eq &symbread()) ) {	
                   9640: 		# if we are in the middle of processing the resource the
                   9641: 		# get the value we are planning on committing
                   9642:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9643:                     return $Apache::lonhomework::results{$qualifierrest};
                   9644:                 } else {
                   9645:                     return $Apache::lonhomework::history{$qualifierrest};
                   9646:                 }
1.335     albertel 9647: 	    } else {
1.359     albertel 9648: 		my %restored;
1.620     albertel 9649: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9650: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9651: 		} else {
                   9652: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9653: 		}
1.335     albertel 9654: 		return $restored{$qualifierrest};
                   9655: 	    }
1.48      www      9656: # ----------------------------------------------------------------- user.access
                   9657:         } elsif ($space eq 'access') {
1.218     albertel 9658: 	    # FIXME - not supporting calls for a specific user
1.48      www      9659:             return &allowed($qualifier,$rest);
                   9660: # ------------------------------------------ user.preferences, user.environment
                   9661:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9662: 	    if (($uname eq $env{'user.name'}) &&
                   9663: 		($udom eq $env{'user.domain'})) {
                   9664: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9665: 	    } else {
1.359     albertel 9666: 		my %returnhash;
                   9667: 		if (!$publicuser) {
                   9668: 		    %returnhash=&userenvironment($udom,$uname,
                   9669: 						 $qualifierrest);
                   9670: 		}
1.218     albertel 9671: 		return $returnhash{$qualifierrest};
                   9672: 	    }
1.48      www      9673: # ----------------------------------------------------------------- user.course
                   9674:         } elsif ($space eq 'course') {
1.218     albertel 9675: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9676:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9677: # ------------------------------------------------------------------- user.role
                   9678:         } elsif ($space eq 'role') {
1.218     albertel 9679: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9680:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9681:             if ($qualifier eq 'value') {
                   9682: 		return $role;
                   9683:             } elsif ($qualifier eq 'extent') {
                   9684:                 return $where;
                   9685:             }
                   9686: # ----------------------------------------------------------------- user.domain
                   9687:         } elsif ($space eq 'domain') {
1.218     albertel 9688:             return $udom;
1.48      www      9689: # ------------------------------------------------------------------- user.name
                   9690:         } elsif ($space eq 'name') {
1.218     albertel 9691:             return $uname;
1.48      www      9692: # ---------------------------------------------------- Any other user namespace
1.29      www      9693:         } else {
1.359     albertel 9694: 	    my %reply;
                   9695: 	    if (!$publicuser) {
                   9696: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9697: 	    }
                   9698: 	    return $reply{$qualifierrest};
1.48      www      9699:         }
1.236     www      9700:     } elsif ($realm eq 'query') {
                   9701: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9702:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9703: 						[$spacequalifierrest]);
1.620     albertel 9704: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9705:    } elsif ($realm eq 'request') {
1.48      www      9706: # ------------------------------------------------------------- request.browser
                   9707:         if ($space eq 'browser') {
1.1145    bisitz   9708:             return $env{'browser.'.$qualifier};
1.57      www      9709: # ------------------------------------------------------------ request.filename
                   9710:         } else {
1.620     albertel 9711:             return $env{'request.'.$spacequalifierrest};
1.29      www      9712:         }
1.28      www      9713:     } elsif ($realm eq 'course') {
1.48      www      9714: # ---------------------------------------------------------- course.description
1.620     albertel 9715:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9716:     } elsif ($realm eq 'resource') {
1.165     www      9717: 
1.620     albertel 9718: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9719: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9720: 	}
1.693     albertel 9721: 
                   9722: 	if ($space eq 'title') {
                   9723: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9724: 	    return &gettitle($symbparm);
                   9725: 	}
                   9726: 	
                   9727: 	if ($space eq 'map') {
                   9728: 	    my ($map) = &decode_symb($symbparm);
                   9729: 	    return &symbread($map);
                   9730: 	}
1.905     albertel 9731: 	if ($space eq 'filename') {
                   9732: 	    if ($symbparm) {
                   9733: 		return &clutter((&decode_symb($symbparm))[2]);
                   9734: 	    }
                   9735: 	    return &hreflocation('',$env{'request.filename'});
                   9736: 	}
1.693     albertel 9737: 
                   9738: 	my ($section, $group, @groups);
1.593     albertel 9739: 	my ($courselevelm,$courselevel);
1.1172.2.28! raeburn  9740:         if (($courseid eq '') && ($cid)) {
        !          9741:             $courseid = $cid;
        !          9742:         }
        !          9743: 	if (($symbparm && $courseid) && 
        !          9744: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      9745: 
1.218     albertel 9746: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9747: 
1.60      www      9748: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9749: 	    my $symbp=$symbparm;
1.735     albertel 9750: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9751: 
                   9752: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9753: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9754: 
1.620     albertel 9755: 	    if (($env{'user.name'} eq $uname) &&
                   9756: 		($env{'user.domain'} eq $udom)) {
                   9757: 		$section=$env{'request.course.sec'};
1.733     raeburn  9758:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9759:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9760: 	    } else {
1.539     albertel 9761: 		if (! defined($usection)) {
1.551     albertel 9762: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9763: 		} else {
                   9764: 		    $section = $usection;
                   9765: 		}
1.733     raeburn  9766:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9767: 	    }
                   9768: 
                   9769: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9770: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9771: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9772: 
1.593     albertel 9773: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9774: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9775: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9776: 
1.60      www      9777: # ----------------------------------------------------------- first, check user
1.624     albertel 9778: 
                   9779: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9780: 				       ([$courselevelr,'resource'],
                   9781: 					[$courselevelm,'map'     ],
                   9782: 					[$courselevel, 'course'  ]));
1.931     albertel 9783: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9784: 
1.594     albertel 9785: # ------------------------------------------------ second, check some of course
1.684     raeburn  9786:             my $coursereply;
1.691     raeburn  9787:             if (@groups > 0) {
                   9788:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9789:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9790:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9791:             }
1.96      www      9792: 
1.684     raeburn  9793: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9794: 				  $env{'course.'.$courseid.'.domain'},
                   9795: 				  'course',
                   9796: 				  ([$seclevelr,   'resource'],
                   9797: 				   [$seclevelm,   'map'     ],
                   9798: 				   [$seclevel,    'course'  ],
                   9799: 				   [$courselevelr,'resource']));
                   9800: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9801: 
1.60      www      9802: # ------------------------------------------------------ third, check map parms
1.218     albertel 9803: 	    my %parmhash=();
                   9804: 	    my $thisparm='';
                   9805: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9806: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9807: 		    &GDBM_READER(),0640)) {
1.218     albertel 9808: 		$thisparm=$parmhash{$symbparm};
                   9809: 		untie(%parmhash);
                   9810: 	    }
1.927     albertel 9811: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9812: 	}
1.594     albertel 9813: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9814: 
1.218     albertel 9815: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9816: 	my $filename;
                   9817: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9818: 	if ($symbparm) {
1.409     www      9819: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9820: 	} else {
1.620     albertel 9821: 	    $filename=$env{'request.filename'};
1.282     albertel 9822: 	}
                   9823: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9824: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9825: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9826: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9827: 
1.927     albertel 9828: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9829: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9830: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9831: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9832: 				     $env{'course.'.$courseid.'.domain'},
                   9833: 				     'course',
1.927     albertel 9834: 				     ([$courselevelm,'map'   ],
                   9835: 				      [$courselevel, 'course']));
                   9836: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9837: 	}
1.145     www      9838: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9839: 	unless ($space eq '0') {
1.336     albertel 9840: 	    my @parts=split(/_/,$space);
                   9841: 	    my $id=pop(@parts);
                   9842: 	    my $part=join('_',@parts);
                   9843: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9844: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9845: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9846: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9847: 	}
1.395     albertel 9848: 	if ($recurse) { return undef; }
                   9849: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9850: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9851: # ---------------------------------------------------- Any other user namespace
                   9852:     } elsif ($realm eq 'environment') {
                   9853: # ----------------------------------------------------------------- environment
1.620     albertel 9854: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9855: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9856: 	} else {
1.770     albertel 9857: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9858: 		return '';
                   9859: 	    }
1.219     albertel 9860: 	    my %returnhash=&userenvironment($udom,$uname,
                   9861: 					    $spacequalifierrest);
                   9862: 	    return $returnhash{$spacequalifierrest};
                   9863: 	}
1.28      www      9864:     } elsif ($realm eq 'system') {
1.48      www      9865: # ----------------------------------------------------------------- system.time
                   9866: 	if ($space eq 'time') {
                   9867: 	    return time;
                   9868:         }
1.696     albertel 9869:     } elsif ($realm eq 'server') {
                   9870: # ----------------------------------------------------------------- system.time
                   9871: 	if ($space eq 'name') {
                   9872: 	    return $ENV{'SERVER_NAME'};
                   9873:         }
1.28      www      9874:     }
1.48      www      9875:     return '';
1.61      www      9876: }
                   9877: 
1.927     albertel 9878: sub get_reply {
                   9879:     my ($reply_value) = @_;
1.940     raeburn  9880:     if (ref($reply_value) eq 'ARRAY') {
                   9881:         if (wantarray) {
                   9882: 	    return @$reply_value;
                   9883:         }
                   9884:         return $reply_value->[0];
                   9885:     } else {
                   9886:         return $reply_value;
1.927     albertel 9887:     }
                   9888: }
                   9889: 
1.691     raeburn  9890: sub check_group_parms {
                   9891:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9892:     my @groupitems = ();
                   9893:     my $resultitem;
1.927     albertel 9894:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9895:     foreach my $group (@{$groups}) {
                   9896:         foreach my $level (@levels) {
1.927     albertel 9897:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9898:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9899:         }
                   9900:     }
                   9901:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9902:                             $env{'course.'.$courseid.'.domain'},
                   9903:                                      'course',@groupitems);
                   9904:     return $coursereply;
                   9905: }
                   9906: 
                   9907: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9908:     my ($courseid,@groups) = @_;
                   9909:     @groups = sort(@groups);
1.691     raeburn  9910:     return @groups;
                   9911: }
                   9912: 
1.395     albertel 9913: sub packages_tab_default {
                   9914:     my ($uri,$varname)=@_;
                   9915:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9916: 
                   9917:     my (@extension,@specifics,$do_default);
                   9918:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9919: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9920: 	if ($pack_type eq 'default') {
                   9921: 	    $do_default=1;
                   9922: 	} elsif ($pack_type eq 'extension') {
                   9923: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9924: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9925: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9926: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9927: 	}
                   9928:     }
                   9929:     # first look for a package that matches the requested part id
                   9930:     foreach my $package (@specifics) {
                   9931: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9932: 	next if ($pack_part ne $part);
                   9933: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9934: 	    return $packagetab{"$pack_type&$name&default"};
                   9935: 	}
                   9936:     }
                   9937:     # look for any possible matching non extension_ package
                   9938:     foreach my $package (@specifics) {
                   9939: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9940: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9941: 	    return $packagetab{"$pack_type&$name&default"};
                   9942: 	}
1.585     albertel 9943: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9944: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9945: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9946: 	}
                   9947:     }
1.738     albertel 9948:     # look for any posible extension_ match
                   9949:     foreach my $package (@extension) {
                   9950: 	my ($package,$pack_type)=@{$package};
                   9951: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9952: 	    return $packagetab{"$pack_type&$name&default"};
                   9953: 	}
                   9954: 	if (defined($packagetab{$package."&$name&default"})) {
                   9955: 	    return $packagetab{$package."&$name&default"};
                   9956: 	}
                   9957:     }
                   9958:     # look for a global default setting
                   9959:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9960: 	return $packagetab{"default&$name&default"};
                   9961:     }
1.395     albertel 9962:     return undef;
                   9963: }
                   9964: 
1.334     albertel 9965: sub add_prefix_and_part {
                   9966:     my ($prefix,$part)=@_;
                   9967:     my $keyroot;
                   9968:     if (defined($prefix) && $prefix !~ /^__/) {
                   9969: 	# prefix that has a part already
                   9970: 	$keyroot=$prefix;
                   9971:     } elsif (defined($prefix)) {
                   9972: 	# prefix that is missing a part
                   9973: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9974:     } else {
                   9975: 	# no prefix at all
                   9976: 	if (defined($part)) { $keyroot='_'.$part; }
                   9977:     }
                   9978:     return $keyroot;
                   9979: }
                   9980: 
1.71      www      9981: # ---------------------------------------------------------------- Get metadata
                   9982: 
1.599     albertel 9983: my %metaentry;
1.1070    www      9984: my %importedpartids;
1.71      www      9985: sub metadata {
1.176     www      9986:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9987:     $uri=&declutter($uri);
1.288     albertel 9988:     # if it is a non metadata possible uri return quickly
1.529     albertel 9989:     if (($uri eq '') || 
                   9990: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  9991: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9992:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9993: 	return undef;
                   9994:     }
1.1140    www      9995:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9996: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9997: 	return undef;
1.288     albertel 9998:     }
1.73      www      9999:     my $filename=$uri;
                   10000:     $uri=~s/\.meta$//;
1.172     www      10001: #
                   10002: # Is the metadata already cached?
1.177     www      10003: # Look at timestamp of caching
1.172     www      10004: # Everything is cached by the main uri, libraries are never directly cached
                   10005: #
1.428     albertel 10006:     if (!defined($liburi)) {
1.599     albertel 10007: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10008: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10009:     }
                   10010:     {
1.1069    www      10011: # Imported parts would go here
1.1070    www      10012:         my %importedids=();
                   10013:         my @origfileimportpartids=();
1.1069    www      10014:         my $importedparts=0;
1.172     www      10015: #
                   10016: # Is this a recursive call for a library?
                   10017: #
1.599     albertel 10018: #	if (! exists($metacache{$uri})) {
                   10019: #	    $metacache{$uri}={};
                   10020: #	}
1.924     albertel 10021: 	my $cachetime = 60*60;
1.171     www      10022:         if ($liburi) {
                   10023: 	    $liburi=&declutter($liburi);
                   10024:             $filename=$liburi;
1.401     bowersj2 10025:         } else {
1.599     albertel 10026: 	    &devalidate_cache_new('meta',$uri);
                   10027: 	    undef(%metaentry);
1.401     bowersj2 10028: 	}
1.140     www      10029:         my %metathesekeys=();
1.73      www      10030:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10031: 	my $metastring;
1.1140    www      10032: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10033: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10034: 	    $metastring = 
1.929     albertel 10035: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10036: 					  ('grade_target' => 'meta'));
                   10037: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10038: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10039:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10040: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10041: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10042: 	    $metastring=&getfile($file);
1.489     albertel 10043: 	}
1.208     albertel 10044:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10045:         my $token;
1.140     www      10046:         undef %metathesekeys;
1.71      www      10047:         while ($token=$parser->get_token) {
1.339     albertel 10048: 	    if ($token->[0] eq 'S') {
                   10049: 		if (defined($token->[2]->{'package'})) {
1.172     www      10050: #
                   10051: # This is a package - get package info
                   10052: #
1.339     albertel 10053: 		    my $package=$token->[2]->{'package'};
                   10054: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10055: 		    if (defined($token->[2]->{'id'})) { 
                   10056: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10057: 		    }
1.599     albertel 10058: 		    if ($metaentry{':packages'}) {
                   10059: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10060: 		    } else {
1.599     albertel 10061: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10062: 		    }
1.736     albertel 10063: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10064: 			my $part=$keyroot;
                   10065: 			$part=~s/^\_//;
1.736     albertel 10066: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10067: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10068: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10069: 			    # ignore package.tab specified default values
                   10070:                             # here &package_tab_default() will fetch those
                   10071: 			    if ($subp eq 'default') { next; }
1.736     albertel 10072: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10073: 			    my $unikey;
                   10074: 			    if ($pack =~ /_0$/) {
                   10075: 				$unikey='parameter_0_'.$name;
                   10076: 				$part=0;
                   10077: 			    } else {
                   10078: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10079: 			    }
1.339     albertel 10080: 			    if ($subp eq 'display') {
                   10081: 				$value.=' [Part: '.$part.']';
                   10082: 			    }
1.599     albertel 10083: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10084: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10085: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10086: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10087: 			    }
1.599     albertel 10088: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10089: 				$metaentry{':'.$unikey}=
                   10090: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10091: 			    }
1.339     albertel 10092: 			}
                   10093: 		    }
                   10094: 		} else {
1.172     www      10095: #
                   10096: # This is not a package - some other kind of start tag
1.339     albertel 10097: #
                   10098: 		    my $entry=$token->[1];
1.1068    www      10099: 		    my $unikey='';
1.175     www      10100: 
1.339     albertel 10101: 		    if ($entry eq 'import') {
1.175     www      10102: #
                   10103: # Importing a library here
1.339     albertel 10104: #
1.1067    www      10105:                         my $location=$parser->get_text('/import');
                   10106:                         my $dir=$filename;
                   10107:                         $dir=~s|[^/]*$||;
                   10108:                         $location=&filelocation($dir,$location);
1.1069    www      10109:                        
1.1068    www      10110:                         my $importmode=$token->[2]->{'importmode'};
                   10111:                         if ($importmode eq 'problem') {
1.1069    www      10112: # Import as problem/response
1.1068    www      10113:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10114:                         } elsif ($importmode eq 'part') {
                   10115: # Import as part(s)
1.1069    www      10116:                            $importedparts=1;
                   10117: # We need to get the original file and the imported file to get the part order correct
                   10118: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10119: # Load and inspect original file
1.1070    www      10120:                            if ($#origfileimportpartids<0) {
                   10121:                               undef(%importedpartids);
                   10122:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10123:                               my $origfile=&getfile($origfilelocation);
                   10124:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10125:                            }
                   10126: 
1.1069    www      10127: # Load and inspect imported file
                   10128:                            my $impfile=&getfile($location);
                   10129:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10130:                            if ($#impfilepartids>=0) {
                   10131: # This problem had parts
1.1070    www      10132:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10133:                            } else {
                   10134: # Importing by turning a single problem into a problem part
                   10135: # It gets the import-tags ID as part-ID
                   10136:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10137:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10138:                            }
1.1068    www      10139:                         } else {
                   10140: # Normal import
                   10141:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10142:                            if (defined($token->[2]->{'id'})) {
                   10143:                               $unikey.='_'.$token->[2]->{'id'};
                   10144:                            }
1.1067    www      10145:                         }
                   10146: 
1.339     albertel 10147: 			if ($depthcount<20) {
1.736     albertel 10148: 			    my $metadata = 
                   10149: 				&metadata($uri,'keys', $location,$unikey,
                   10150: 					  $depthcount+1);
                   10151: 			    foreach my $meta (split(',',$metadata)) {
                   10152: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10153: 				$metathesekeys{$meta}=1;
1.339     albertel 10154: 			    }
1.1068    www      10155: 			
                   10156:                         }
1.1067    www      10157: 		    } else {
                   10158: #
                   10159: # Not importing, some other kind of non-package, non-library start tag
                   10160: # 
                   10161:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10162:                         if (defined($token->[2]->{'id'})) {
                   10163:                             $unikey.='_'.$token->[2]->{'id'};
                   10164:                         }
1.339     albertel 10165: 			if (defined($token->[2]->{'name'})) { 
                   10166: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10167: 			}
                   10168: 			$metathesekeys{$unikey}=1;
1.736     albertel 10169: 			foreach my $param (@{$token->[3]}) {
                   10170: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10171: 				$token->[2]->{$param};
1.339     albertel 10172: 			}
                   10173: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10174: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10175: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10176: 		 # only ws inside the tag, and not in default, so use default
                   10177: 		 # as value
1.599     albertel 10178: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10179: 			} elsif ( $internaltext =~ /\S/ ) {
                   10180: 		  # something interesting inside the tag
                   10181: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10182: 			} else {
1.908     albertel 10183: 		  # no interesting values, don't set a default
1.339     albertel 10184: 			}
1.172     www      10185: # end of not-a-package not-a-library import
1.339     albertel 10186: 		    }
1.172     www      10187: # end of not-a-package start tag
1.339     albertel 10188: 		}
1.172     www      10189: # the next is the end of "start tag"
1.339     albertel 10190: 	    }
                   10191: 	}
1.483     albertel 10192: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10193: 	$extension = lc($extension);
                   10194: 	if ($extension eq 'htm') { $extension='html'; }
                   10195: 
1.737     albertel 10196: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10197: 	    #no specific packages #how's our extension
                   10198: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10199: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10200: 					 \%metathesekeys);
                   10201: 	}
1.883     albertel 10202: 
                   10203: 	if (!exists($metaentry{':packages'})
                   10204: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10205: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10206: 		#no specific packages well let's get default then
                   10207: 		if ($key!~/^default&/) { next; }
1.488     albertel 10208: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10209: 					     \%metathesekeys);
                   10210: 	    }
                   10211: 	}
1.338     www      10212: # are there custom rights to evaluate
1.599     albertel 10213: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10214: 
1.338     www      10215:     #
                   10216:     # Importing a rights file here
1.339     albertel 10217:     #
                   10218: 	    unless ($depthcount) {
1.599     albertel 10219: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10220: 		my $dir=$filename;
                   10221: 		$dir=~s|[^/]*$||;
                   10222: 		$location=&filelocation($dir,$location);
1.736     albertel 10223: 		my $rights_metadata =
                   10224: 		    &metadata($uri,'keys',$location,'_rights',
                   10225: 			      $depthcount+1);
                   10226: 		foreach my $rights (split(',',$rights_metadata)) {
                   10227: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10228: 		    $metathesekeys{$rights}=1;
1.339     albertel 10229: 		}
                   10230: 	    }
                   10231: 	}
1.737     albertel 10232: 	# uniqifiy package listing
                   10233: 	my %seen;
                   10234: 	my @uniq_packages =
                   10235: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10236: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10237: 
1.1070    www      10238:         if ($importedparts) {
                   10239: # We had imported parts and need to rebuild partorder
                   10240:            $metaentry{':partorder'}='';
                   10241:            $metathesekeys{'partorder'}=1;
                   10242:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10243:                if ($origfileimportpartids[$index] eq 'part') {
                   10244: # original part, part of the problem
                   10245:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10246:                } else {
                   10247: # we have imported parts at this position
                   10248:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10249:                }
                   10250:            }
                   10251:            $metaentry{':partorder'}=~s/^\,//;
                   10252:         }
                   10253: 
1.737     albertel 10254: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10255: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10256: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10257: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10258: # this is the end of "was not already recently cached
1.71      www      10259:     }
1.599     albertel 10260:     return $metaentry{':'.$what};
1.261     albertel 10261: }
                   10262: 
1.488     albertel 10263: sub metadata_create_package_def {
1.483     albertel 10264:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10265:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10266:     if ($subp eq 'default') { next; }
                   10267:     
1.599     albertel 10268:     if (defined($metaentry{':packages'})) {
                   10269: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10270:     } else {
1.599     albertel 10271: 	$metaentry{':packages'}=$package;
1.483     albertel 10272:     }
                   10273:     my $value=$packagetab{$key};
                   10274:     my $unikey;
                   10275:     $unikey='parameter_0_'.$name;
1.599     albertel 10276:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10277:     $$metathesekeys{$unikey}=1;
1.599     albertel 10278:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10279: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10280:     }
1.599     albertel 10281:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10282: 	$metaentry{':'.$unikey}=
                   10283: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10284:     }
                   10285: }
                   10286: 
1.261     albertel 10287: sub metadata_generate_part0 {
                   10288:     my ($metadata,$metacache,$uri) = @_;
                   10289:     my %allnames;
1.737     albertel 10290:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10291: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10292: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10293: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10294: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10295: 	    $allnames{$name}=$part;
                   10296: 	  }
                   10297: 	}
                   10298:     }
                   10299:     foreach my $name (keys(%allnames)) {
                   10300:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10301:       my $key=":parameter_0_$name";
1.261     albertel 10302:       $$metacache{"$key.part"}='0';
                   10303:       $$metacache{"$key.name"}=$name;
1.428     albertel 10304:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10305: 					   $allnames{$name}.'_'.$name.
                   10306: 					   '.type'};
1.428     albertel 10307:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10308: 			     '.display'};
1.644     www      10309:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10310:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10311:       $$metacache{"$key.display"}=$olddis;
                   10312:     }
1.71      www      10313: }
                   10314: 
1.764     albertel 10315: # ------------------------------------------------------ Devalidate title cache
                   10316: 
                   10317: sub devalidate_title_cache {
                   10318:     my ($url)=@_;
                   10319:     if (!$env{'request.course.id'}) { return; }
                   10320:     my $symb=&symbread($url);
                   10321:     if (!$symb) { return; }
                   10322:     my $key=$env{'request.course.id'}."\0".$symb;
                   10323:     &devalidate_cache_new('title',$key);
                   10324: }
                   10325: 
1.1014    droeschl 10326: # ------------------------------------------------- Get the title of a course
                   10327: 
                   10328: sub current_course_title {
                   10329:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10330: }
1.301     www      10331: # ------------------------------------------------- Get the title of a resource
                   10332: 
                   10333: sub gettitle {
                   10334:     my $urlsymb=shift;
                   10335:     my $symb=&symbread($urlsymb);
1.534     albertel 10336:     if ($symb) {
1.620     albertel 10337: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10338: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10339: 	if (defined($cached)) { 
                   10340: 	    return $result;
                   10341: 	}
1.534     albertel 10342: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10343: 	my $title='';
1.907     albertel 10344: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10345: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10346: 	} else {
                   10347: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10348: 		    &GDBM_READER(),0640)) {
                   10349: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10350: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10351: 		untie(%bighash);
                   10352: 	    }
1.534     albertel 10353: 	}
                   10354: 	$title=~s/\&colon\;/\:/gs;
                   10355: 	if ($title) {
1.1159    www      10356: # Remember both $symb and $title for dynamic metadata
                   10357:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10358:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10359: # Cache this title and then return it
1.599     albertel 10360: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10361: 	}
                   10362: 	$urlsymb=$url;
                   10363:     }
                   10364:     my $title=&metadata($urlsymb,'title');
                   10365:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10366:     return $title;
1.301     www      10367: }
1.613     albertel 10368: 
1.614     albertel 10369: sub get_slot {
                   10370:     my ($which,$cnum,$cdom)=@_;
                   10371:     if (!$cnum || !$cdom) {
1.790     albertel 10372: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10373: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10374: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10375:     }
1.703     albertel 10376:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10377:     my %slotinfo;
                   10378:     if (exists($remembered{$key})) {
                   10379: 	$slotinfo{$which} = $remembered{$key};
                   10380:     } else {
                   10381: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10382: 	&Apache::lonhomework::showhash(%slotinfo);
                   10383: 	my ($tmp)=keys(%slotinfo);
                   10384: 	if ($tmp=~/^error:/) { return (); }
                   10385: 	$remembered{$key} = $slotinfo{$which};
                   10386:     }
1.616     albertel 10387:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10388: 	return %{$slotinfo{$which}};
                   10389:     }
                   10390:     return $slotinfo{$which};
1.614     albertel 10391: }
1.1150    raeburn  10392: 
                   10393: sub get_reservable_slots {
                   10394:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10395:     my $now = time;
                   10396:     my $reservable_info;
                   10397:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10398:     if (exists($remembered{$key})) {
                   10399:         $reservable_info = $remembered{$key};
                   10400:     } else {
                   10401:         my %resv;
                   10402:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10403:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10404:         $reservable_info = \%resv;
                   10405:         $remembered{$key} = $reservable_info;
                   10406:     }
                   10407:     return $reservable_info;
                   10408: }
                   10409: 
                   10410: sub get_course_slots {
                   10411:     my ($cnum,$cdom) = @_;
                   10412:     my $hashid=$cnum.':'.$cdom;
                   10413:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10414:     if (defined($cached)) {
                   10415:         if (ref($result) eq 'HASH') {
                   10416:             return %{$result};
                   10417:         }
                   10418:     } else {
                   10419:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10420:         my ($tmp) = keys(%slots);
                   10421:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10422:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10423:             return %slots;
                   10424:         }
                   10425:     }
                   10426:     return;
                   10427: }
                   10428: 
                   10429: sub devalidate_slots_cache {
                   10430:     my ($cnum,$cdom)=@_;
                   10431:     my $hashid=$cnum.':'.$cdom;
                   10432:     &devalidate_cache_new('allslots',$hashid);
                   10433: }
                   10434: 
1.1172.2.8  raeburn  10435: sub get_coursechange {
                   10436:     my ($cdom,$cnum) = @_;
                   10437:     if ($cdom eq '' || $cnum eq '') {
                   10438:         return unless ($env{'request.course.id'});
                   10439:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10440:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10441:     }
                   10442:     my $hashid=$cdom.'_'.$cnum;
                   10443:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10444:     if ((defined($cached)) && ($change ne '')) {
                   10445:         return $change;
                   10446:     } else {
                   10447:         my %crshash;
                   10448:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10449:         if ($crshash{'internal.contentchange'} eq '') {
                   10450:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10451:             if ($change eq '') {
                   10452:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10453:                 $change = $crshash{'internal.created'};
                   10454:             }
                   10455:         } else {
                   10456:             $change = $crshash{'internal.contentchange'};
                   10457:         }
                   10458:         my $cachetime = 600;
                   10459:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10460:     }
                   10461:     return $change;
                   10462: }
                   10463: 
                   10464: sub devalidate_coursechange_cache {
                   10465:     my ($cnum,$cdom)=@_;
                   10466:     my $hashid=$cnum.':'.$cdom;
                   10467:     &devalidate_cache_new('crschange',$hashid);
                   10468: }
                   10469: 
1.31      www      10470: # ------------------------------------------------- Update symbolic store links
                   10471: 
                   10472: sub symblist {
                   10473:     my ($mapname,%newhash)=@_;
1.438     www      10474:     $mapname=&deversion(&declutter($mapname));
1.31      www      10475:     my %hash;
1.620     albertel 10476:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10477:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10478:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10479: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10480: 		next if ($url eq 'last_known'
                   10481: 			 && $env{'form.no_update_last_known'});
                   10482: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10483: 						    $newhash{$url}->[1],
                   10484: 						    $newhash{$url}->[0]);
1.191     harris41 10485:             }
1.31      www      10486:             if (untie(%hash)) {
                   10487: 		return 'ok';
                   10488:             }
                   10489:         }
                   10490:     }
                   10491:     return 'error';
1.212     www      10492: }
                   10493: 
                   10494: # --------------------------------------------------------------- Verify a symb
                   10495: 
                   10496: sub symbverify {
1.1172.2.11  raeburn  10497:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10498:     my $thisfn=$thisurl;
1.439     www      10499:     $thisfn=&declutter($thisfn);
1.215     www      10500: # direct jump to resource in page or to a sequence - will construct own symbs
                   10501:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10502: # check URL part
1.409     www      10503:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10504: 
1.431     www      10505:     unless ($url eq $thisfn) { return 0; }
1.213     www      10506: 
1.216     www      10507:     $symb=&symbclean($symb);
1.510     www      10508:     $thisurl=&deversion($thisurl);
1.439     www      10509:     $thisfn=&deversion($thisfn);
1.213     www      10510: 
                   10511:     my %bighash;
                   10512:     my $okay=0;
1.431     www      10513: 
1.620     albertel 10514:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10515:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10516:         my $noclutter;
1.1032    raeburn  10517:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10518:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10519:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10520:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10521:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10522:                 $noclutter = 1;
                   10523:             }
                   10524:         }
                   10525:         my $ids;
                   10526:         if ($noclutter) {
                   10527:             $ids=$bighash{'ids_'.$thisurl};
                   10528:         } else {
                   10529:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10530:         }
1.1102    raeburn  10531:         unless ($ids) {
1.1172.2.13  raeburn  10532:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10533:             $ids=$bighash{$idkey};
1.216     www      10534:         }
                   10535:         if ($ids) {
                   10536: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10537:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10538:                 $symb =~ s/\?.+$//;
                   10539:             }
1.800     albertel 10540: 	    foreach my $id (split(/\,/,$ids)) {
                   10541: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10542:                if (
                   10543:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10544:    eq $symb) {
1.1172.2.11  raeburn  10545:                    if (ref($encstate)) {
                   10546:                        $$encstate = $bighash{'encrypted_'.$id};
                   10547:                    }
1.1172.2.13  raeburn  10548:                    if (($env{'request.role.adv'}) ||
                   10549:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10550:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10551:                        $okay=1;
                   10552:                        last;
                   10553:                    }
                   10554:                }
                   10555:            }
1.216     www      10556:         }
1.213     www      10557: 	untie(%bighash);
                   10558:     }
                   10559:     return $okay;
1.31      www      10560: }
                   10561: 
1.210     www      10562: # --------------------------------------------------------------- Clean-up symb
                   10563: 
                   10564: sub symbclean {
                   10565:     my $symb=shift;
1.568     albertel 10566:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10567: # remove version from map
                   10568:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10569: 
1.210     www      10570: # remove version from URL
                   10571:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10572: 
1.507     www      10573: # remove wrapper
                   10574: 
1.510     www      10575:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10576:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10577:     return $symb;
1.409     www      10578: }
                   10579: 
                   10580: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10581: 
                   10582: sub encode_symb {
                   10583:     my ($map,$resid,$url)=@_;
                   10584:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10585: }
1.409     www      10586: 
                   10587: sub decode_symb {
1.568     albertel 10588:     my $symb=shift;
                   10589:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10590:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10591:     return (&fixversion($map),$resid,&fixversion($url));
                   10592: }
                   10593: 
                   10594: sub fixversion {
                   10595:     my $fn=shift;
1.609     banghart 10596:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10597:     my %bighash;
                   10598:     my $uri=&clutter($fn);
1.620     albertel 10599:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10600: # is this cached?
1.599     albertel 10601:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10602:     if (defined($cached)) { return $result; }
                   10603: # unfortunately not cached, or expired
1.620     albertel 10604:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10605: 	    &GDBM_READER(),0640)) {
                   10606:  	if ($bighash{'version_'.$uri}) {
                   10607:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10608:  	    unless (($version eq 'mostrecent') || 
                   10609: 		    ($version==&getversion($uri))) {
1.440     www      10610:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10611:  	    }
                   10612:  	}
                   10613:  	untie %bighash;
1.413     www      10614:     }
1.599     albertel 10615:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10616: }
                   10617: 
                   10618: sub deversion {
                   10619:     my $url=shift;
                   10620:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10621:     return $url;
1.210     www      10622: }
                   10623: 
1.31      www      10624: # ------------------------------------------------------ Return symb list entry
                   10625: 
                   10626: sub symbread {
1.249     www      10627:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10628:     my $cache_str;
                   10629:     if ($thisfn ne '') {
                   10630:         $cache_str='request.symbread.cached.'.$thisfn;
                   10631:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10632:             return $env{$cache_str};
                   10633:         }
1.1172.2.13  raeburn  10634:    } else {
1.242     www      10635: # no filename provided? try from environment
1.620     albertel 10636:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10637:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10638:         }
                   10639:         $thisfn=$env{'request.filename'};
1.44      www      10640:     }
1.569     albertel 10641:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10642: # is that filename actually a symb? Verify, clean, and return
                   10643:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10644: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10645: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10646: 	}
1.242     www      10647:     }
1.44      www      10648:     $thisfn=declutter($thisfn);
1.31      www      10649:     my %hash;
1.37      www      10650:     my %bighash;
                   10651:     my $syval='';
1.620     albertel 10652:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10653:         my $targetfn = $thisfn;
1.609     banghart 10654:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10655:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10656:         }
1.687     albertel 10657: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10658: 	    $targetfn=$1;
                   10659: 	}
1.620     albertel 10660:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10661:                       &GDBM_READER(),0640)) {
1.481     raeburn  10662: 	    $syval=$hash{$targetfn};
1.37      www      10663:             untie(%hash);
                   10664:         }
                   10665: # ---------------------------------------------------------- There was an entry
                   10666:         if ($syval) {
1.601     albertel 10667: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10668: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10669: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10670: 		    #return $env{$cache_str}='';
1.601     albertel 10671: 		#}    
                   10672: 		#$syval.=$1;
                   10673: 	    #}
1.37      www      10674:         } else {
                   10675: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10676:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10677:                             &GDBM_READER(),0640)) {
1.37      www      10678: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10679:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10680:               unless ($ids) { 
                   10681:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10682:               }
                   10683:               unless ($ids) {
                   10684: # alias?
                   10685: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10686:               }
1.37      www      10687:               if ($ids) {
                   10688: # ------------------------------------------------------------------- Has ID(s)
                   10689:                  my @possibilities=split(/\,/,$ids);
1.39      www      10690:                  if ($#possibilities==0) {
                   10691: # ----------------------------------------------- There is only one possibility
1.37      www      10692: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10693: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10694: 						    $resid,$thisfn);
1.249     www      10695:                  } elsif (!$donotrecurse) {
1.39      www      10696: # ------------------------------------------ There is more than one possibility
                   10697:                      my $realpossible=0;
1.800     albertel 10698:                      foreach my $id (@possibilities) {
                   10699: 			 my $file=$bighash{'src_'.$id};
1.39      www      10700:                          if (&allowed('bre',$file)) {
1.800     albertel 10701:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10702:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10703: 				$realpossible++;
1.626     albertel 10704:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10705: 						    $resid,$thisfn);
1.39      www      10706:                             }
                   10707: 			 }
1.191     harris41 10708:                      }
1.39      www      10709: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10710:                  } else {
                   10711:                      $syval='';
1.37      www      10712:                  }
                   10713: 	      }
                   10714:               untie(%bighash)
1.481     raeburn  10715:            }
1.31      www      10716:         }
1.62      www      10717:         if ($syval) {
1.620     albertel 10718: 	    return $env{$cache_str}=$syval;
1.62      www      10719:         }
1.31      www      10720:     }
1.949     raeburn  10721:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10722:     return $env{$cache_str}='';
1.31      www      10723: }
                   10724: 
                   10725: # ---------------------------------------------------------- Return random seed
                   10726: 
1.32      www      10727: sub numval {
                   10728:     my $txt=shift;
                   10729:     $txt=~tr/A-J/0-9/;
                   10730:     $txt=~tr/a-j/0-9/;
                   10731:     $txt=~tr/K-T/0-9/;
                   10732:     $txt=~tr/k-t/0-9/;
                   10733:     $txt=~tr/U-Z/0-5/;
                   10734:     $txt=~tr/u-z/0-5/;
                   10735:     $txt=~s/\D//g;
1.564     albertel 10736:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10737:     return int($txt);
1.368     albertel 10738: }
                   10739: 
1.484     albertel 10740: sub numval2 {
                   10741:     my $txt=shift;
                   10742:     $txt=~tr/A-J/0-9/;
                   10743:     $txt=~tr/a-j/0-9/;
                   10744:     $txt=~tr/K-T/0-9/;
                   10745:     $txt=~tr/k-t/0-9/;
                   10746:     $txt=~tr/U-Z/0-5/;
                   10747:     $txt=~tr/u-z/0-5/;
                   10748:     $txt=~s/\D//g;
                   10749:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10750:     my $total;
                   10751:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10752:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10753:     return int($total);
                   10754: }
                   10755: 
1.575     albertel 10756: sub numval3 {
                   10757:     use integer;
                   10758:     my $txt=shift;
                   10759:     $txt=~tr/A-J/0-9/;
                   10760:     $txt=~tr/a-j/0-9/;
                   10761:     $txt=~tr/K-T/0-9/;
                   10762:     $txt=~tr/k-t/0-9/;
                   10763:     $txt=~tr/U-Z/0-5/;
                   10764:     $txt=~tr/u-z/0-5/;
                   10765:     $txt=~s/\D//g;
                   10766:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10767:     my $total;
                   10768:     foreach my $val (@txts) { $total+=$val; }
                   10769:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10770:     return $total;
                   10771: }
                   10772: 
1.675     albertel 10773: sub digest {
                   10774:     my ($data)=@_;
                   10775:     my $digest=&Digest::MD5::md5($data);
                   10776:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10777:     my ($e,$f);
                   10778:     {
                   10779:         use integer;
                   10780:         $e=($a+$b);
                   10781:         $f=($c+$d);
                   10782:         if ($_64bit) {
                   10783:             $e=(($e<<32)>>32);
                   10784:             $f=(($f<<32)>>32);
                   10785:         }
                   10786:     }
                   10787:     if (wantarray) {
                   10788: 	return ($e,$f);
                   10789:     } else {
                   10790: 	my $g;
                   10791: 	{
                   10792: 	    use integer;
                   10793: 	    $g=($e+$f);
                   10794: 	    if ($_64bit) {
                   10795: 		$g=(($g<<32)>>32);
                   10796: 	    }
                   10797: 	}
                   10798: 	return $g;
                   10799:     }
                   10800: }
                   10801: 
1.368     albertel 10802: sub latest_rnd_algorithm_id {
1.675     albertel 10803:     return '64bit5';
1.366     albertel 10804: }
1.32      www      10805: 
1.503     albertel 10806: sub get_rand_alg {
                   10807:     my ($courseid)=@_;
1.790     albertel 10808:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10809:     if ($courseid) {
1.620     albertel 10810: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10811:     }
                   10812:     return &latest_rnd_algorithm_id();
                   10813: }
                   10814: 
1.562     albertel 10815: sub validCODE {
                   10816:     my ($CODE)=@_;
                   10817:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10818:     return 0;
                   10819: }
                   10820: 
1.491     albertel 10821: sub getCODE {
1.620     albertel 10822:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10823:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10824: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10825: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10826: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10827:     }
                   10828:     return undef;
                   10829: }
1.1133    foxr     10830: #
                   10831: #  Determines the random seed for a specific context:
                   10832: #
                   10833: # parameters:
                   10834: #   symb      - in course context the symb for the seed.
                   10835: #   course_id - The course id of the form domain_coursenum.
                   10836: #   domain    - Domain for the user.
                   10837: #   course    - Course for the user.
                   10838: #   cenv      - environment of the course.
                   10839: #
                   10840: # NOTE:
                   10841: #   All parameters are picked out of the environment if missing
                   10842: #   or not defined.
                   10843: #   If a symb cannot be determined the current time is used instead.
                   10844: #
                   10845: #  For a given well defined symb, courside, domain, username,
                   10846: #  and course environment, the seed is reproducible.
                   10847: #
1.31      www      10848: sub rndseed {
1.1133    foxr     10849:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10850:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10851:     if (!defined($symb)) {
1.366     albertel 10852: 	unless ($symb=$wsymb) { return time; }
                   10853:     }
1.1146    foxr     10854:     if (!defined $courseid) { 
                   10855: 	$courseid=$wcourseid; 
                   10856:     }
                   10857:     if (!defined $domain) { $domain=$wdomain; }
                   10858:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10859: 
                   10860:     my $which;
                   10861:     if (defined($cenv->{'rndseed'})) {
                   10862: 	$which = $cenv->{'rndseed'};
                   10863:     } else {
                   10864: 	$which =&get_rand_alg($courseid);
                   10865:     }
1.491     albertel 10866:     if (defined(&getCODE())) {
1.675     albertel 10867: 	if ($which eq '64bit5') {
                   10868: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10869: 	} elsif ($which eq '64bit4') {
1.575     albertel 10870: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10871: 	} else {
                   10872: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10873: 	}
1.675     albertel 10874:     } elsif ($which eq '64bit5') {
                   10875: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10876:     } elsif ($which eq '64bit4') {
                   10877: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10878:     } elsif ($which eq '64bit3') {
                   10879: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10880:     } elsif ($which eq '64bit2') {
                   10881: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10882:     } elsif ($which eq '64bit') {
                   10883: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10884:     }
                   10885:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10886: }
                   10887: 
                   10888: sub rndseed_32bit {
                   10889:     my ($symb,$courseid,$domain,$username)=@_;
                   10890:     {
                   10891: 	use integer;
                   10892: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10893: 	my $symbseed=numval($symb) << 22;
                   10894: 	my $namechck=unpack("%32C*",$username) << 17;
                   10895: 	my $nameseed=numval($username) << 12;
                   10896: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10897: 	my $courseseed=unpack("%32C*",$courseid);
                   10898: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10899: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10900: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10901: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10902: 	return $num;
                   10903:     }
                   10904: }
                   10905: 
                   10906: sub rndseed_64bit {
                   10907:     my ($symb,$courseid,$domain,$username)=@_;
                   10908:     {
                   10909: 	use integer;
                   10910: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10911: 	my $symbseed=numval($symb) << 10;
                   10912: 	my $namechck=unpack("%32S*",$username);
                   10913: 	
                   10914: 	my $nameseed=numval($username) << 21;
                   10915: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10916: 	my $courseseed=unpack("%32S*",$courseid);
                   10917: 	
                   10918: 	my $num1=$symbchck+$symbseed+$namechck;
                   10919: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10920: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10921: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10922: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10923: 	return "$num1,$num2";
1.155     albertel 10924:     }
1.366     albertel 10925: }
                   10926: 
1.443     albertel 10927: sub rndseed_64bit2 {
                   10928:     my ($symb,$courseid,$domain,$username)=@_;
                   10929:     {
                   10930: 	use integer;
                   10931: 	# strings need to be an even # of cahracters long, it it is odd the
                   10932:         # last characters gets thrown away
                   10933: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10934: 	my $symbseed=numval($symb) << 10;
                   10935: 	my $namechck=unpack("%32S*",$username.' ');
                   10936: 	
                   10937: 	my $nameseed=numval($username) << 21;
1.501     albertel 10938: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10939: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10940: 	
                   10941: 	my $num1=$symbchck+$symbseed+$namechck;
                   10942: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10943: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10944: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10945: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10946: 	return "$num1,$num2";
                   10947:     }
                   10948: }
                   10949: 
                   10950: sub rndseed_64bit3 {
                   10951:     my ($symb,$courseid,$domain,$username)=@_;
                   10952:     {
                   10953: 	use integer;
                   10954: 	# strings need to be an even # of cahracters long, it it is odd the
                   10955:         # last characters gets thrown away
                   10956: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10957: 	my $symbseed=numval2($symb) << 10;
                   10958: 	my $namechck=unpack("%32S*",$username.' ');
                   10959: 	
                   10960: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10961: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10962: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10963: 	
                   10964: 	my $num1=$symbchck+$symbseed+$namechck;
                   10965: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10967: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10968: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10969: 	
1.503     albertel 10970: 	return "$num1:$num2";
1.443     albertel 10971:     }
                   10972: }
                   10973: 
1.575     albertel 10974: sub rndseed_64bit4 {
                   10975:     my ($symb,$courseid,$domain,$username)=@_;
                   10976:     {
                   10977: 	use integer;
                   10978: 	# strings need to be an even # of cahracters long, it it is odd the
                   10979:         # last characters gets thrown away
                   10980: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10981: 	my $symbseed=numval3($symb) << 10;
                   10982: 	my $namechck=unpack("%32S*",$username.' ');
                   10983: 	
                   10984: 	my $nameseed=numval3($username) << 21;
                   10985: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10986: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10987: 	
                   10988: 	my $num1=$symbchck+$symbseed+$namechck;
                   10989: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10990: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10991: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10992: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10993: 	
1.575     albertel 10994: 	return "$num1:$num2";
                   10995:     }
                   10996: }
                   10997: 
1.675     albertel 10998: sub rndseed_64bit5 {
                   10999:     my ($symb,$courseid,$domain,$username)=@_;
                   11000:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11001:     return "$num1:$num2";
                   11002: }
                   11003: 
1.366     albertel 11004: sub rndseed_CODE_64bit {
                   11005:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11006:     {
1.366     albertel 11007: 	use integer;
1.443     albertel 11008: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11009: 	my $symbseed=numval2($symb);
1.491     albertel 11010: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11011: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11012: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11013: 	my $num1=$symbseed+$CODEchck;
                   11014: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11015: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11016: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11017: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11018: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11019: 	return "$num1:$num2";
1.366     albertel 11020:     }
                   11021: }
                   11022: 
1.575     albertel 11023: sub rndseed_CODE_64bit4 {
                   11024:     my ($symb,$courseid,$domain,$username)=@_;
                   11025:     {
                   11026: 	use integer;
                   11027: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11028: 	my $symbseed=numval3($symb);
                   11029: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11030: 	my $CODEseed=numval3(&getCODE());
                   11031: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11032: 	my $num1=$symbseed+$CODEchck;
                   11033: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11034: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11035: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11036: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11037: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11038: 	return "$num1:$num2";
                   11039:     }
                   11040: }
                   11041: 
1.675     albertel 11042: sub rndseed_CODE_64bit5 {
                   11043:     my ($symb,$courseid,$domain,$username)=@_;
                   11044:     my $code = &getCODE();
                   11045:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11046:     return "$num1:$num2";
                   11047: }
                   11048: 
1.366     albertel 11049: sub setup_random_from_rndseed {
                   11050:     my ($rndseed)=@_;
1.503     albertel 11051:     if ($rndseed =~/([,:])/) {
                   11052: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11053: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11054:     } else {
                   11055: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11056:     }
1.36      albertel 11057: }
                   11058: 
1.474     albertel 11059: sub latest_receipt_algorithm_id {
1.835     albertel 11060:     return 'receipt3';
1.474     albertel 11061: }
                   11062: 
1.480     www      11063: sub recunique {
                   11064:     my $fucourseid=shift;
                   11065:     my $unique;
1.835     albertel 11066:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11067: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11068: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11069:     } else {
                   11070: 	$unique=$perlvar{'lonReceipt'};
                   11071:     }
                   11072:     return unpack("%32C*",$unique);
                   11073: }
                   11074: 
                   11075: sub recprefix {
                   11076:     my $fucourseid=shift;
                   11077:     my $prefix;
1.835     albertel 11078:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11079: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11080: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11081:     } else {
                   11082: 	$prefix=$perlvar{'lonHostID'};
                   11083:     }
                   11084:     return unpack("%32C*",$prefix);
                   11085: }
                   11086: 
1.76      www      11087: sub ireceipt {
1.474     albertel 11088:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11089: 
                   11090:     my $return =&recprefix($fucourseid).'-';
                   11091: 
                   11092:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11093: 	$env{'request.state'} eq 'construct') {
                   11094: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11095: 	return $return;
                   11096:     }
                   11097: 
1.76      www      11098:     my $cuname=unpack("%32C*",$funame);
                   11099:     my $cudom=unpack("%32C*",$fudom);
                   11100:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11101:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11102:     my $cunique=&recunique($fucourseid);
1.474     albertel 11103:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11104:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11105: 
1.790     albertel 11106: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11107: 			       
                   11108: 	$return.= ($cunique%$cuname+
                   11109: 		   $cunique%$cudom+
                   11110: 		   $cusymb%$cuname+
                   11111: 		   $cusymb%$cudom+
                   11112: 		   $cucourseid%$cuname+
                   11113: 		   $cucourseid%$cudom+
                   11114: 		   $cpart%$cuname+
                   11115: 		   $cpart%$cudom);
                   11116:     } else {
                   11117: 	$return.= ($cunique%$cuname+
                   11118: 		   $cunique%$cudom+
                   11119: 		   $cusymb%$cuname+
                   11120: 		   $cusymb%$cudom+
                   11121: 		   $cucourseid%$cuname+
                   11122: 		   $cucourseid%$cudom);
                   11123:     }
                   11124:     return $return;
1.76      www      11125: }
                   11126: 
                   11127: sub receipt {
1.474     albertel 11128:     my ($part)=@_;
1.790     albertel 11129:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11130:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11131: }
1.260     ng       11132: 
1.790     albertel 11133: sub whichuser {
                   11134:     my ($passedsymb)=@_;
                   11135:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11136:     if (defined($env{'form.grade_symb'})) {
                   11137: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11138: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11139: 	if (!$allowed &&
                   11140: 	    exists($env{'request.course.sec'}) &&
                   11141: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11142: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11143: 			      '/'.$env{'request.course.sec'});
                   11144: 	}
                   11145: 	if ($allowed) {
                   11146: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11147: 	    $courseid=$tmp_courseid;
                   11148: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11149: 	    ($name)=&get_env_multiple('form.grade_username');
                   11150: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11151: 	}
                   11152:     }
                   11153:     if (!$passedsymb) {
                   11154: 	$symb=&symbread();
                   11155:     } else {
                   11156: 	$symb=$passedsymb;
                   11157:     }
                   11158:     $courseid=$env{'request.course.id'};
                   11159:     $domain=$env{'user.domain'};
                   11160:     $name=$env{'user.name'};
                   11161:     if ($name eq 'public' && $domain eq 'public') {
                   11162: 	if (!defined($env{'form.username'})) {
                   11163: 	    $env{'form.username'}.=time.rand(10000000);
                   11164: 	}
                   11165: 	$name.=$env{'form.username'};
                   11166:     }
                   11167:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11168: 
                   11169: }
                   11170: 
1.36      albertel 11171: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11172: # returns either the contents of the file or 
                   11173: # -1 if the file doesn't exist
1.481     raeburn  11174: #
                   11175: # if the target is a file that was uploaded via DOCS, 
                   11176: # a check will be made to see if a current copy exists on the local server,
                   11177: # if it does this will be served, otherwise a copy will be retrieved from
                   11178: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11179: # the local server.   
1.472     albertel 11180: 
1.36      albertel 11181: sub getfile {
1.538     albertel 11182:     my ($file) = @_;
1.609     banghart 11183:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11184:     &repcopy($file);
                   11185:     return &readfile($file);
                   11186: }
                   11187: 
                   11188: sub repcopy_userfile {
                   11189:     my ($file)=@_;
1.1142    raeburn  11190:     my $londocroot = $perlvar{'lonDocRoot'};
                   11191:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11192:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11193:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11194: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11195:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11196:     if (-e "$file") {
1.828     www      11197: # we already have a local copy, check it out
1.538     albertel 11198: 	my @fileinfo = stat($file);
1.828     www      11199: 	my $rtncode;
                   11200: 	my $info;
1.538     albertel 11201: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11202: 	if ($lwpresp ne 'ok') {
1.828     www      11203: # there is no such file anymore, even though we had a local copy
1.482     albertel 11204: 	    if ($rtncode eq '404') {
1.538     albertel 11205: 		unlink($file);
1.482     albertel 11206: 	    }
                   11207: 	    return -1;
                   11208: 	}
                   11209: 	if ($info < $fileinfo[9]) {
1.828     www      11210: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11211: 	    return 'ok';
1.828     www      11212: 	} else {
                   11213: # the file is outdated, get rid of it
                   11214: 	    unlink($file);
1.482     albertel 11215: 	}
1.828     www      11216:     }
                   11217: # one way or the other, at this point, we don't have the file
                   11218: # construct the correct path for the file
                   11219:     my @parts = ($cdom,$cnum); 
                   11220:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11221: 	push @parts, split(/\//,$1);
                   11222:     }
                   11223:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11224:     foreach my $part (@parts) {
                   11225: 	$path .= '/'.$part;
                   11226: 	if (!-e $path) {
                   11227: 	    mkdir($path,0770);
1.482     albertel 11228: 	}
                   11229:     }
1.828     www      11230: # now the path exists for sure
                   11231: # get a user agent
                   11232:     my $ua=new LWP::UserAgent;
                   11233:     my $transferfile=$file.'.in.transfer';
                   11234: # FIXME: this should flock
                   11235:     if (-e $transferfile) { return 'ok'; }
                   11236:     my $request;
                   11237:     $uri=~s/^\///;
1.980     raeburn  11238:     my $homeserver = &homeserver($cnum,$cdom);
                   11239:     my $protocol = $protocol{$homeserver};
                   11240:     $protocol = 'http' if ($protocol ne 'https');
                   11241:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11242:     my $response=$ua->request($request,$transferfile);
                   11243: # did it work?
                   11244:     if ($response->is_error()) {
                   11245: 	unlink($transferfile);
                   11246: 	&logthis("Userfile repcopy failed for $uri");
                   11247: 	return -1;
                   11248:     }
                   11249: # worked, rename the transfer file
                   11250:     rename($transferfile,$file);
1.607     raeburn  11251:     return 'ok';
1.481     raeburn  11252: }
                   11253: 
1.517     albertel 11254: sub tokenwrapper {
                   11255:     my $uri=shift;
1.980     raeburn  11256:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11257:     $uri=~s|^/||;
1.620     albertel 11258:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11259:     my $token=$1;
1.552     albertel 11260:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11261:     if ($udom && $uname && $file) {
                   11262: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11263:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11264:         my $homeserver = &homeserver($uname,$udom);
                   11265:         my $protocol = $protocol{$homeserver};
                   11266:         $protocol = 'http' if ($protocol ne 'https');
                   11267:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11268:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11269:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11270:     } else {
                   11271:         return '/adm/notfound.html';
                   11272:     }
                   11273: }
                   11274: 
1.828     www      11275: # call with reqtype HEAD: get last modification time
                   11276: # call with reqtype GET: get the file contents
                   11277: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11278: #
1.481     raeburn  11279: sub getuploaded {
                   11280:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11281:     $uri=~s/^\///;
1.980     raeburn  11282:     my $homeserver = &homeserver($cnum,$cdom);
                   11283:     my $protocol = $protocol{$homeserver};
                   11284:     $protocol = 'http' if ($protocol ne 'https');
                   11285:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11286:     my $ua=new LWP::UserAgent;
                   11287:     my $request=new HTTP::Request($reqtype,$uri);
                   11288:     my $response=$ua->request($request);
                   11289:     $$rtncode = $response->code;
1.482     albertel 11290:     if (! $response->is_success()) {
                   11291: 	return 'failed';
                   11292:     }      
                   11293:     if ($reqtype eq 'HEAD') {
1.486     www      11294: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11295:     } elsif ($reqtype eq 'GET') {
                   11296: 	$$info = $response->content;
1.472     albertel 11297:     }
1.482     albertel 11298:     return 'ok';
1.36      albertel 11299: }
                   11300: 
1.481     raeburn  11301: sub readfile {
                   11302:     my $file = shift;
                   11303:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11304:     my $fh;
                   11305:     open($fh,"<$file");
                   11306:     my $a='';
1.800     albertel 11307:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11308:     return $a;
                   11309: }
                   11310: 
1.36      albertel 11311: sub filelocation {
1.590     banghart 11312:     my ($dir,$file) = @_;
                   11313:     my $location;
                   11314:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11315: 
                   11316:     if ($file =~ m-^/adm/-) {
                   11317: 	$file=~s-^/adm/wrapper/-/-;
                   11318: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11319:     }
1.882     albertel 11320: 
1.1139    www      11321:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11322:         $location = $file;
1.609     banghart 11323:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11324:         my ($udom,$uname,$filename)=
1.811     albertel 11325:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11326:         my $home=&homeserver($uname,$udom);
                   11327:         my $is_me=0;
                   11328:         my @ids=&current_machine_ids();
                   11329:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11330:         if ($is_me) {
1.1117    foxr     11331:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11332:         } else {
                   11333:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11334:   	      $udom.'/'.$uname.'/'.$filename;
                   11335:         }
1.882     albertel 11336:     } elsif ($file =~ m-^/adm/-) {
                   11337: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11338:     } else {
                   11339:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11340:         $file=~s:^/(res|priv)/:/:;
                   11341:         my $space=$1;
1.590     banghart 11342:         if ( !( $file =~ m:^/:) ) {
                   11343:             $location = $dir. '/'.$file;
                   11344:         } else {
1.1142    raeburn  11345:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11346:         }
1.59      albertel 11347:     }
1.590     banghart 11348:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11349:     while ($location=~m{/\.\./}) {
                   11350: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11351: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11352: 	} else {
                   11353: 	    $location=~ s{/\.\./}{/}g;
                   11354: 	}
                   11355:     } #remove dir/..
1.590     banghart 11356:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11357:     return $location;
1.46      www      11358: }
1.36      albertel 11359: 
1.46      www      11360: sub hreflocation {
                   11361:     my ($dir,$file)=@_;
1.980     raeburn  11362:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11363: 	$file=filelocation($dir,$file);
1.700     albertel 11364:     } elsif ($file=~m-^/adm/-) {
                   11365: 	$file=~s-^/adm/wrapper/-/-;
                   11366: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11367:     }
                   11368:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11369: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11370:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11371: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11372: 	        {/uploaded/$1/$2/}x;
1.46      www      11373:     }
1.913     albertel 11374:     if ($file=~ m{^/userfiles/}) {
                   11375: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11376:     }
1.462     albertel 11377:     return $file;
1.465     albertel 11378: }
                   11379: 
1.1139    www      11380: 
                   11381: 
                   11382: 
                   11383: 
1.465     albertel 11384: sub current_machine_domains {
1.853     albertel 11385:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11386: }
                   11387: 
                   11388: sub machine_domains {
                   11389:     my ($hostname) = @_;
1.465     albertel 11390:     my @domains;
1.838     albertel 11391:     my %hostname = &all_hostnames();
1.465     albertel 11392:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11393: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11394: 	if ($hostname eq $name) {
1.844     albertel 11395: 	    push(@domains,&host_domain($id));
1.465     albertel 11396: 	}
                   11397:     }
                   11398:     return @domains;
                   11399: }
                   11400: 
                   11401: sub current_machine_ids {
1.853     albertel 11402:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11403: }
                   11404: 
                   11405: sub machine_ids {
                   11406:     my ($hostname) = @_;
                   11407:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11408:     my @ids;
1.888     albertel 11409:     my %name_to_host = &all_names();
1.889     albertel 11410:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11411: 	return @{ $name_to_host{$hostname} };
                   11412:     }
                   11413:     return;
1.31      www      11414: }
                   11415: 
1.824     raeburn  11416: sub additional_machine_domains {
                   11417:     my @domains;
                   11418:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11419:     while( my $line = <$fh>) {
                   11420:         $line =~ s/\s//g;
                   11421:         push(@domains,$line);
                   11422:     }
                   11423:     return @domains;
                   11424: }
                   11425: 
                   11426: sub default_login_domain {
                   11427:     my $domain = $perlvar{'lonDefDomain'};
                   11428:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11429:     foreach my $posdom (&current_machine_domains(),
                   11430:                         &additional_machine_domains()) {
                   11431:         if (lc($posdom) eq lc($testdomain)) {
                   11432:             $domain=$posdom;
                   11433:             last;
                   11434:         }
                   11435:     }
                   11436:     return $domain;
                   11437: }
                   11438: 
1.31      www      11439: # ------------------------------------------------------------- Declutters URLs
                   11440: 
                   11441: sub declutter {
                   11442:     my $thisfn=shift;
1.569     albertel 11443:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11444:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11445:     $thisfn=~s/^\///;
1.697     albertel 11446:     $thisfn=~s|^adm/wrapper/||;
                   11447:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11448:     $thisfn=~s/^res\///;
1.1172    bisitz   11449:     $thisfn=~s/^priv\///;
1.1032    raeburn  11450:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11451:         $thisfn=~s/\?.+$//;
                   11452:     }
1.268     www      11453:     return $thisfn;
                   11454: }
                   11455: 
                   11456: # ------------------------------------------------------------- Clutter up URLs
                   11457: 
                   11458: sub clutter {
                   11459:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11460:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11461: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11462:        $thisfn='/res'.$thisfn; 
                   11463:     }
1.1031    raeburn  11464:     if ($thisfn !~m|^/adm|) {
                   11465: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11466: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11467: 	} else {
                   11468: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11469: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11470: 	    if ($embstyle eq 'ssi'
                   11471: 		|| ($embstyle eq 'hdn')
                   11472: 		|| ($embstyle eq 'rat')
                   11473: 		|| ($embstyle eq 'prv')
                   11474: 		|| ($embstyle eq 'ign')) {
                   11475: 		#do nothing with these
                   11476: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11477: 		|| ($embstyle eq 'emb')
                   11478: 		|| ($embstyle eq 'wrp')) {
                   11479: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11480: 	    } elsif ($embstyle eq 'unk'
                   11481: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11482: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11483: 	    } else {
1.718     www      11484: #		&logthis("Got a blank emb style");
1.695     albertel 11485: 	    }
1.694     albertel 11486: 	}
                   11487:     }
1.31      www      11488:     return $thisfn;
1.12      www      11489: }
                   11490: 
1.787     albertel 11491: sub clutter_with_no_wrapper {
                   11492:     my $uri = &clutter(shift);
                   11493:     if ($uri =~ m-^/adm/-) {
                   11494: 	$uri =~ s-^/adm/wrapper/-/-;
                   11495: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11496:     }
                   11497:     return $uri;
                   11498: }
                   11499: 
1.557     albertel 11500: sub freeze_escape {
                   11501:     my ($value)=@_;
                   11502:     if (ref($value)) {
                   11503: 	$value=&nfreeze($value);
                   11504: 	return '__FROZEN__'.&escape($value);
                   11505:     }
                   11506:     return &escape($value);
                   11507: }
                   11508: 
1.11      www      11509: 
1.557     albertel 11510: sub thaw_unescape {
                   11511:     my ($value)=@_;
                   11512:     if ($value =~ /^__FROZEN__/) {
                   11513: 	substr($value,0,10,undef);
                   11514: 	$value=&unescape($value);
                   11515: 	return &thaw($value);
                   11516:     }
                   11517:     return &unescape($value);
                   11518: }
                   11519: 
1.436     albertel 11520: sub correct_line_ends {
                   11521:     my ($result)=@_;
                   11522:     $$result =~s/\r\n/\n/mg;
                   11523:     $$result =~s/\r/\n/mg;
1.415     albertel 11524: }
1.1       albertel 11525: # ================================================================ Main Program
                   11526: 
1.184     www      11527: sub goodbye {
1.204     albertel 11528:    &logthis("Starting Shut down");
1.443     albertel 11529: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11530:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11531: #converted
1.599     albertel 11532: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11533:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11534: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11535: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11536: #1.1 only
1.870     albertel 11537: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11538: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11539: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11540: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11541:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11542:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11543:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11544:    &flushcourselogs();
                   11545:    &logthis("Shutting down");
                   11546: }
                   11547: 
1.852     albertel 11548: sub get_dns {
1.1172.2.17  raeburn  11549:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11550:     if (!$ignore_cache) {
                   11551: 	my ($content,$cached)=
                   11552: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11553: 	if ($cached) {
1.1172.2.17  raeburn  11554: 	    &$func($content,$hashref);
1.869     albertel 11555: 	    return;
                   11556: 	}
                   11557:     }
                   11558: 
                   11559:     my %alldns;
1.852     albertel 11560:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11561:     foreach my $dns (<$config>) {
                   11562: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11563:         my $line = $1;
                   11564:         my ($host,$protocol) = split(/:/,$line);
                   11565:         if ($protocol ne 'https') {
                   11566:             $protocol = 'http';
                   11567:         }
                   11568: 	$alldns{$host} = $protocol;
1.869     albertel 11569:     }
                   11570:     while (%alldns) {
                   11571: 	my ($dns) = keys(%alldns);
1.852     albertel 11572: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11573:         $ua->timeout(30);
1.979     raeburn  11574: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11575: 	my $response=$ua->request($request);
1.979     raeburn  11576:         delete($alldns{$dns});
1.852     albertel 11577: 	next if ($response->is_error());
                   11578: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11579:         unless ($nocache) {
1.1172.2.23  raeburn  11580: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11581:         }
                   11582: 	&$func(\@content,$hashref);
1.869     albertel 11583: 	return;
1.852     albertel 11584:     }
                   11585:     close($config);
1.871     albertel 11586:     my $which = (split('/',$url))[3];
                   11587:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11588:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11589:     my @content = <$config>;
1.1172.2.17  raeburn  11590:     &$func(\@content,$hashref);
                   11591:     return;
                   11592: }
                   11593: 
                   11594: # ------------------------------------------------------Get DNS checksums file
                   11595: sub parse_dns_checksums_tab {
                   11596:     my ($lines,$hashref) = @_;
                   11597:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11598:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11599:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11600:     my (%chksum,%revnum);
                   11601:     if (ref($lines) eq 'ARRAY') {
                   11602:         chomp(@{$lines});
                   11603:         my $versions = shift(@{$lines});
                   11604:         my %supported;
                   11605:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11606:             my $releaseslist = $1;
                   11607:             if ($releaseslist =~ /,/) {
                   11608:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11609:             } elsif ($releaseslist) {
                   11610:                 $supported{$releaseslist} = 1;
                   11611:             }
                   11612:         }
                   11613:         if ($supported{$release}) {
                   11614:             my $matchthis = 0;
                   11615:             foreach my $line (@{$lines}) {
                   11616:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11617:                     if ($matchthis) {
                   11618:                         last;
                   11619:                     } elsif ($1 eq $release) {
                   11620:                         $matchthis = 1;
                   11621:                     }
                   11622:                 } elsif ($matchthis) {
                   11623:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11624:                     $chksum{$file} = $shasum;
                   11625:                     $revnum{$file} = $version;
                   11626:                 }
                   11627:             }
                   11628:             if (ref($hashref) eq 'HASH') {
                   11629:                 %{$hashref} = (
                   11630:                                 sums     => \%chksum,
                   11631:                                 versions => \%revnum,
                   11632:                               );
                   11633:             }
                   11634:         }
                   11635:     }
1.869     albertel 11636:     return;
1.852     albertel 11637: }
1.1172.2.17  raeburn  11638: 
                   11639: sub fetch_dns_checksums {
                   11640:     my %checksums;
                   11641:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11642:              \%checksums);
                   11643:     return \%checksums;
                   11644: }
                   11645: 
1.327     albertel 11646: # ------------------------------------------------------------ Read domain file
                   11647: {
1.852     albertel 11648:     my $loaded;
1.846     albertel 11649:     my %domain;
                   11650: 
1.852     albertel 11651:     sub parse_domain_tab {
                   11652: 	my ($lines) = @_;
                   11653: 	foreach my $line (@$lines) {
                   11654: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11655: 
1.846     albertel 11656: 	    chomp($line);
1.852     albertel 11657: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11658: 	    my %this_domain;
                   11659: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11660: 			       'lang_def', 'city', 'longi', 'lati',
                   11661: 			       'primary') {
                   11662: 		$this_domain{$field} = shift(@elements);
                   11663: 	    }
                   11664: 	    $domain{$name} = \%this_domain;
1.852     albertel 11665: 	}
                   11666:     }
1.864     albertel 11667: 
                   11668:     sub reset_domain_info {
                   11669: 	undef($loaded);
                   11670: 	undef(%domain);
                   11671:     }
                   11672: 
1.852     albertel 11673:     sub load_domain_tab {
1.869     albertel 11674: 	my ($ignore_cache) = @_;
                   11675: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11676: 	my $fh;
                   11677: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11678: 	    my @lines = <$fh>;
                   11679: 	    &parse_domain_tab(\@lines);
1.448     albertel 11680: 	}
1.852     albertel 11681: 	close($fh);
                   11682: 	$loaded = 1;
1.327     albertel 11683:     }
1.846     albertel 11684: 
                   11685:     sub domain {
1.852     albertel 11686: 	&load_domain_tab() if (!$loaded);
                   11687: 
1.846     albertel 11688: 	my ($name,$what) = @_;
                   11689: 	return if ( !exists($domain{$name}) );
                   11690: 
                   11691: 	if (!$what) {
                   11692: 	    return $domain{$name}{'description'};
                   11693: 	}
                   11694: 	return $domain{$name}{$what};
                   11695:     }
1.974     raeburn  11696: 
                   11697:     sub domain_info {
                   11698:         &load_domain_tab() if (!$loaded);
                   11699:         return %domain;
                   11700:     }
                   11701: 
1.327     albertel 11702: }
                   11703: 
                   11704: 
1.1       albertel 11705: # ------------------------------------------------------------- Read hosts file
                   11706: {
1.838     albertel 11707:     my %hostname;
1.844     albertel 11708:     my %hostdom;
1.845     albertel 11709:     my %libserv;
1.852     albertel 11710:     my $loaded;
1.888     albertel 11711:     my %name_to_host;
1.1074    raeburn  11712:     my %internetdom;
1.1107    raeburn  11713:     my %LC_dns_serv;
1.852     albertel 11714: 
                   11715:     sub parse_hosts_tab {
                   11716: 	my ($file) = @_;
                   11717: 	foreach my $configline (@$file) {
                   11718: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11719:             chomp($configline);
                   11720: 	    if ($configline =~ /^\^/) {
                   11721:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11722:                     $LC_dns_serv{$1} = 1;
                   11723:                 }
                   11724:                 next;
                   11725:             }
1.1074    raeburn  11726: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11727: 	    $name=~s/\s//g;
                   11728: 	    if ($id && $domain && $role && $name) {
                   11729: 		$hostname{$id}=$name;
1.888     albertel 11730: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11731: 		$hostdom{$id}=$domain;
                   11732: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11733:                 if (defined($protocol)) {
                   11734:                     if ($protocol eq 'https') {
                   11735:                         $protocol{$id} = $protocol;
                   11736:                     } else {
                   11737:                         $protocol{$id} = 'http'; 
                   11738:                     }
1.968     raeburn  11739:                 } else {
1.969     raeburn  11740:                     $protocol{$id} = 'http';
1.968     raeburn  11741:                 }
1.1074    raeburn  11742:                 if (defined($intdom)) {
                   11743:                     $internetdom{$id} = $intdom;
                   11744:                 }
1.852     albertel 11745: 	    }
                   11746: 	}
                   11747:     }
1.864     albertel 11748:     
                   11749:     sub reset_hosts_info {
1.897     albertel 11750: 	&purge_remembered();
1.864     albertel 11751: 	&reset_domain_info();
                   11752: 	&reset_hosts_ip_info();
1.892     albertel 11753: 	undef(%name_to_host);
1.864     albertel 11754: 	undef(%hostname);
                   11755: 	undef(%hostdom);
                   11756: 	undef(%libserv);
                   11757: 	undef($loaded);
                   11758:     }
1.1       albertel 11759: 
1.852     albertel 11760:     sub load_hosts_tab {
1.869     albertel 11761: 	my ($ignore_cache) = @_;
                   11762: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11763: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11764: 	my @config = <$config>;
                   11765: 	&parse_hosts_tab(\@config);
                   11766: 	close($config);
                   11767: 	$loaded=1;
1.1       albertel 11768:     }
1.852     albertel 11769: 
1.838     albertel 11770:     sub hostname {
1.852     albertel 11771: 	&load_hosts_tab() if (!$loaded);
                   11772: 
1.838     albertel 11773: 	my ($lonid) = @_;
                   11774: 	return $hostname{$lonid};
                   11775:     }
1.845     albertel 11776: 
1.838     albertel 11777:     sub all_hostnames {
1.852     albertel 11778: 	&load_hosts_tab() if (!$loaded);
                   11779: 
1.838     albertel 11780: 	return %hostname;
                   11781:     }
1.845     albertel 11782: 
1.888     albertel 11783:     sub all_names {
                   11784: 	&load_hosts_tab() if (!$loaded);
                   11785: 
                   11786: 	return %name_to_host;
                   11787:     }
                   11788: 
1.974     raeburn  11789:     sub all_host_domain {
                   11790:         &load_hosts_tab() if (!$loaded);
                   11791:         return %hostdom;
                   11792:     }
                   11793: 
1.845     albertel 11794:     sub is_library {
1.852     albertel 11795: 	&load_hosts_tab() if (!$loaded);
                   11796: 
1.845     albertel 11797: 	return exists($libserv{$_[0]});
                   11798:     }
                   11799: 
                   11800:     sub all_library {
1.852     albertel 11801: 	&load_hosts_tab() if (!$loaded);
                   11802: 
1.845     albertel 11803: 	return %libserv;
                   11804:     }
                   11805: 
1.1062    droeschl 11806:     sub unique_library {
                   11807: 	#2x reverse removes all hostnames that appear more than once
                   11808:         my %unique = reverse &all_library();
                   11809:         return reverse %unique;
                   11810:     }
                   11811: 
1.841     albertel 11812:     sub get_servers {
1.852     albertel 11813: 	&load_hosts_tab() if (!$loaded);
                   11814: 
1.841     albertel 11815: 	my ($domain,$type) = @_;
                   11816: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11817: 	                                          : %hostname;
                   11818: 	my %result;
1.842     albertel 11819: 	if (ref($domain) eq 'ARRAY') {
                   11820: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11821: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11822: 		    $result{$host} = $hostname;
                   11823: 		}
                   11824: 	    }
                   11825: 	} else {
                   11826: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11827: 		if ($hostdom{$host} eq $domain) {
                   11828: 		    $result{$host} = $hostname;
                   11829: 		}
1.841     albertel 11830: 	    }
                   11831: 	}
                   11832: 	return %result;
                   11833:     }
1.845     albertel 11834: 
1.1062    droeschl 11835:     sub get_unique_servers {
                   11836:         my %unique = reverse &get_servers(@_);
                   11837: 	return reverse %unique;
                   11838:     }
                   11839: 
1.844     albertel 11840:     sub host_domain {
1.852     albertel 11841: 	&load_hosts_tab() if (!$loaded);
                   11842: 
1.844     albertel 11843: 	my ($lonid) = @_;
                   11844: 	return $hostdom{$lonid};
                   11845:     }
                   11846: 
1.841     albertel 11847:     sub all_domains {
1.852     albertel 11848: 	&load_hosts_tab() if (!$loaded);
                   11849: 
1.841     albertel 11850: 	my %seen;
                   11851: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11852: 	return @uniq;
                   11853:     }
1.1074    raeburn  11854: 
                   11855:     sub internet_dom {
                   11856:         &load_hosts_tab() if (!$loaded);
                   11857: 
                   11858:         my ($lonid) = @_;
                   11859:         return $internetdom{$lonid};
                   11860:     }
1.1107    raeburn  11861: 
                   11862:     sub is_LC_dns {
                   11863:         &load_hosts_tab() if (!$loaded);
                   11864: 
                   11865:         my ($hostname) = @_;
                   11866:         return exists($LC_dns_serv{$hostname});
                   11867:     }
                   11868: 
1.1       albertel 11869: }
                   11870: 
1.847     albertel 11871: { 
                   11872:     my %iphost;
1.856     albertel 11873:     my %name_to_ip;
                   11874:     my %lonid_to_ip;
1.869     albertel 11875: 
1.847     albertel 11876:     sub get_hosts_from_ip {
                   11877: 	my ($ip) = @_;
                   11878: 	my %iphosts = &get_iphost();
                   11879: 	if (ref($iphosts{$ip})) {
                   11880: 	    return @{$iphosts{$ip}};
                   11881: 	}
                   11882: 	return;
1.839     albertel 11883:     }
1.864     albertel 11884:     
                   11885:     sub reset_hosts_ip_info {
                   11886: 	undef(%iphost);
                   11887: 	undef(%name_to_ip);
                   11888: 	undef(%lonid_to_ip);
                   11889:     }
1.856     albertel 11890: 
                   11891:     sub get_host_ip {
                   11892: 	my ($lonid) = @_;
                   11893: 	if (exists($lonid_to_ip{$lonid})) {
                   11894: 	    return $lonid_to_ip{$lonid};
                   11895: 	}
                   11896: 	my $name=&hostname($lonid);
                   11897:    	my $ip = gethostbyname($name);
                   11898: 	return if (!$ip || length($ip) ne 4);
                   11899: 	$ip=inet_ntoa($ip);
                   11900: 	$name_to_ip{$name}   = $ip;
                   11901: 	$lonid_to_ip{$lonid} = $ip;
                   11902: 	return $ip;
                   11903:     }
1.847     albertel 11904:     
                   11905:     sub get_iphost {
1.869     albertel 11906: 	my ($ignore_cache) = @_;
1.894     albertel 11907: 
1.869     albertel 11908: 	if (!$ignore_cache) {
                   11909: 	    if (%iphost) {
                   11910: 		return %iphost;
                   11911: 	    }
                   11912: 	    my ($ip_info,$cached)=
                   11913: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11914: 	    if ($cached) {
                   11915: 		%iphost      = %{$ip_info->[0]};
                   11916: 		%name_to_ip  = %{$ip_info->[1]};
                   11917: 		%lonid_to_ip = %{$ip_info->[2]};
                   11918: 		return %iphost;
                   11919: 	    }
                   11920: 	}
1.894     albertel 11921: 
                   11922: 	# get yesterday's info for fallback
                   11923: 	my %old_name_to_ip;
                   11924: 	my ($ip_info,$cached)=
                   11925: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11926: 	if ($cached) {
                   11927: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11928: 	}
                   11929: 
1.888     albertel 11930: 	my %name_to_host = &all_names();
                   11931: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11932: 	    my $ip;
                   11933: 	    if (!exists($name_to_ip{$name})) {
                   11934: 		$ip = gethostbyname($name);
                   11935: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11936: 		    if (defined($old_name_to_ip{$name})) {
                   11937: 			$ip = $old_name_to_ip{$name};
                   11938: 			&logthis("Can't find $name defaulting to old $ip");
                   11939: 		    } else {
                   11940: 			&logthis("Name $name no IP found");
                   11941: 			next;
                   11942: 		    }
                   11943: 		} else {
                   11944: 		    $ip=inet_ntoa($ip);
1.847     albertel 11945: 		}
                   11946: 		$name_to_ip{$name} = $ip;
                   11947: 	    } else {
                   11948: 		$ip = $name_to_ip{$name};
1.653     albertel 11949: 	    }
1.888     albertel 11950: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11951: 		$lonid_to_ip{$id} = $ip;
                   11952: 	    }
                   11953: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11954: 	}
1.1172.2.23  raeburn  11955: 	&do_cache_new('iphost','iphost',
                   11956: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   11957: 		      48*60*60);
1.869     albertel 11958: 
1.847     albertel 11959: 	return %iphost;
1.598     albertel 11960:     }
                   11961: 
1.992     raeburn  11962:     #
                   11963:     #  Given a DNS returns the loncapa host name for that DNS 
                   11964:     # 
                   11965:     sub host_from_dns {
                   11966:         my ($dns) = @_;
                   11967:         my @hosts;
                   11968:         my $ip;
                   11969: 
1.993     raeburn  11970:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11971:             $ip = $name_to_ip{$dns};
                   11972:         }
                   11973:         if (!$ip) {
                   11974:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11975:             if (length($ip) == 4) { 
                   11976: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11977:             }
                   11978:         }
                   11979:         if ($ip) {
                   11980: 	    @hosts = get_hosts_from_ip($ip);
                   11981: 	    return $hosts[0];
                   11982:         }
                   11983:         return undef;
1.986     foxr     11984:     }
1.992     raeburn  11985: 
1.1074    raeburn  11986:     sub get_internet_names {
                   11987:         my ($lonid) = @_;
                   11988:         return if ($lonid eq '');
                   11989:         my ($idnref,$cached)=
                   11990:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11991:         if ($cached) {
                   11992:             return $idnref;
                   11993:         }
                   11994:         my $ip = &get_host_ip($lonid);
                   11995:         my @hosts = &get_hosts_from_ip($ip);
                   11996:         my %iphost = &get_iphost();
                   11997:         my (@idns,%seen);
                   11998:         foreach my $id (@hosts) {
                   11999:             my $dom = &host_domain($id);
                   12000:             my $prim_id = &domain($dom,'primary');
                   12001:             my $prim_ip = &get_host_ip($prim_id);
                   12002:             next if ($seen{$prim_ip});
                   12003:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12004:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12005:                     my $intdom = &internet_dom($id);
                   12006:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12007:                         push(@idns,$intdom);
                   12008:                     }
                   12009:                 }
                   12010:             }
                   12011:             $seen{$prim_ip} = 1;
                   12012:         }
1.1172.2.23  raeburn  12013:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12014:     }
                   12015: 
1.986     foxr     12016: }
                   12017: 
1.1079    raeburn  12018: sub all_loncaparevs {
                   12019:     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);
                   12020: }
                   12021: 
1.1172.2.27  raeburn  12022: # ------------------------------------------------------- Read loncaparev table
                   12023: {
                   12024:     sub load_loncaparevs {
                   12025:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12026:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12027:                 while (my $configline=<$config>) {
                   12028:                     chomp($configline);
                   12029:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12030:                     $loncaparevs{$hostid}=$loncaparev;
                   12031:                 }
                   12032:                 close($config);
                   12033:             }
                   12034:         }
                   12035:     }
                   12036: }
                   12037: 
                   12038: # ----------------------------------------------------- Read serverhostID table
                   12039: {
                   12040:     sub load_serverhomeIDs {
                   12041:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12042:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12043:                 while (my $configline=<$config>) {
                   12044:                     chomp($configline);
                   12045:                     my ($name,$id)=split(/:/,$configline);
                   12046:                     $serverhomeIDs{$name}=$id;
                   12047:                 }
                   12048:                 close($config);
                   12049:             }
                   12050:         }
                   12051:     }
                   12052: }
                   12053: 
                   12054: 
1.862     albertel 12055: BEGIN {
                   12056: 
                   12057: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12058:     unless ($readit) {
                   12059: {
                   12060:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12061:     %perlvar = (%perlvar,%{$configvars});
                   12062: }
                   12063: 
                   12064: 
1.1       albertel 12065: # ------------------------------------------------------ Read spare server file
                   12066: {
1.448     albertel 12067:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12068: 
                   12069:     while (my $configline=<$config>) {
                   12070:        chomp($configline);
1.284     matthew  12071:        if ($configline) {
1.784     albertel 12072: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12073: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12074: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12075:        }
                   12076:     }
1.448     albertel 12077:     close($config);
1.1       albertel 12078: }
1.11      www      12079: # ------------------------------------------------------------ Read permissions
                   12080: {
1.448     albertel 12081:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12082: 
                   12083:     while (my $configline=<$config>) {
1.448     albertel 12084: 	chomp($configline);
                   12085: 	if ($configline) {
                   12086: 	    my ($role,$perm)=split(/ /,$configline);
                   12087: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12088: 	}
1.11      www      12089:     }
1.448     albertel 12090:     close($config);
1.11      www      12091: }
                   12092: 
                   12093: # -------------------------------------------- Read plain texts for permissions
                   12094: {
1.448     albertel 12095:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12096: 
                   12097:     while (my $configline=<$config>) {
1.448     albertel 12098: 	chomp($configline);
                   12099: 	if ($configline) {
1.742     raeburn  12100: 	    my ($short,@plain)=split(/:/,$configline);
                   12101:             %{$prp{$short}} = ();
                   12102: 	    if (@plain > 0) {
                   12103:                 $prp{$short}{'std'} = $plain[0];
                   12104:                 for (my $i=1; $i<@plain; $i++) {
                   12105:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12106:                 }
                   12107:             }
1.448     albertel 12108: 	}
1.135     www      12109:     }
1.448     albertel 12110:     close($config);
1.135     www      12111: }
                   12112: 
                   12113: # ---------------------------------------------------------- Read package table
                   12114: {
1.448     albertel 12115:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12116: 
                   12117:     while (my $configline=<$config>) {
1.483     albertel 12118: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12119: 	chomp($configline);
                   12120: 	my ($short,$plain)=split(/:/,$configline);
                   12121: 	my ($pack,$name)=split(/\&/,$short);
                   12122: 	if ($plain ne '') {
                   12123: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12124: 	    $packagetab{$short}=$plain; 
                   12125: 	}
1.11      www      12126:     }
1.448     albertel 12127:     close($config);
1.329     matthew  12128: }
                   12129: 
1.1172.2.27  raeburn  12130: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12131: 
1.1172.2.27  raeburn  12132: &load_loncaparevs();
                   12133: 
                   12134: # ------------------------------------------------------- Read serverhostID table
                   12135: 
                   12136: &load_serverhomeIDs();
1.1074    raeburn  12137: 
1.1172.2.27  raeburn  12138: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12139: {
                   12140:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12141:     if (-e $file) {
                   12142:         my $parser = HTML::LCParser->new($file);
                   12143:         while (my $token = $parser->get_token()) {
                   12144:             if ($token->[0] eq 'S') {
                   12145:                 my $item = $token->[1];
                   12146:                 my $name = $token->[2]{'name'};
                   12147:                 my $value = $token->[2]{'value'};
                   12148:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12149:                     my $release = $parser->get_text();
                   12150:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12151:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12152:                 }
                   12153:             }
                   12154:         }
                   12155:     }
1.1073    raeburn  12156: }
                   12157: 
1.1138    raeburn  12158: # ---------------------------------------------------------- Read managers table
                   12159: {
                   12160:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12161:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12162:             while (my $configline=<$config>) {
                   12163:                 chomp($configline);
                   12164:                 next if ($configline =~ /^\#/);
                   12165:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12166:                     $managerstab{$configline} = 1;
                   12167:                 }
                   12168:             }
                   12169:             close($config);
                   12170:         }
                   12171:     }
                   12172: }
                   12173: 
1.329     matthew  12174: # ------------- set up temporary directory
                   12175: {
1.1117    foxr     12176:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12177: 
1.11      www      12178: }
                   12179: 
1.794     albertel 12180: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12181: 				'compress_threshold'=> 20_000,
                   12182:  			        });
1.185     www      12183: 
1.281     www      12184: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12185: $dumpcount=0;
1.958     www      12186: $locknum=0;
1.22      www      12187: 
1.163     harris41 12188: &logtouch();
1.672     albertel 12189: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12190: $readit=1;
1.564     albertel 12191:     {
                   12192: 	use integer;
                   12193: 	my $test=(2**32)+1;
1.568     albertel 12194: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12195: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12196:     }
1.1172.2.18  raeburn  12197: 
                   12198:     {
                   12199:         eval {
                   12200:             ($apache) =
                   12201:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12202:         };
                   12203:         if ($@) {
                   12204:            $apache = 1.3;
                   12205:         }
                   12206:     }
                   12207: 
1.195     www      12208: }
1.1       albertel 12209: }
1.179     www      12210: 
1.1       albertel 12211: 1;
1.191     harris41 12212: __END__
                   12213: 
1.243     albertel 12214: =pod
                   12215: 
1.191     harris41 12216: =head1 NAME
                   12217: 
1.243     albertel 12218: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12219: 
                   12220: =head1 SYNOPSIS
                   12221: 
1.243     albertel 12222: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12223: 
                   12224:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12225: 
1.243     albertel 12226: Common parameters:
                   12227: 
                   12228: =over 4
                   12229: 
                   12230: =item *
                   12231: 
                   12232: $uname : an internal username (if $cname expecting a course Id specifically)
                   12233: 
                   12234: =item *
                   12235: 
                   12236: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12237: 
                   12238: =item *
                   12239: 
                   12240: $symb : a resource instance identifier
                   12241: 
                   12242: =item *
                   12243: 
                   12244: $namespace : the name of a .db file that contains the data needed or
                   12245: being set.
                   12246: 
                   12247: =back
                   12248: 
1.394     bowersj2 12249: =head1 OVERVIEW
1.191     harris41 12250: 
1.394     bowersj2 12251: lonnet provides subroutines which interact with the
                   12252: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12253: about classes, users, and resources.
1.243     albertel 12254: 
                   12255: For many of these objects you can also use this to store data about
                   12256: them or modify them in various ways.
1.191     harris41 12257: 
1.394     bowersj2 12258: =head2 Symbs
1.191     harris41 12259: 
1.394     bowersj2 12260: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12261: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12262: map, the resource number of the resource in the map, and the URL of
                   12263: the resource itself. The latter is somewhat redundant, but might help
                   12264: if maps change.
                   12265: 
                   12266: An example is
                   12267: 
                   12268:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12269: 
                   12270: The respective map entry is
                   12271: 
                   12272:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12273:   title="Problem 2">
                   12274:  </resource>
                   12275: 
                   12276: Symbs are used by the random number generator, as well as to store and
                   12277: restore data specific to a certain instance of for example a problem.
                   12278: 
                   12279: =head2 Storing And Retrieving Data
                   12280: 
                   12281: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12282: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12283: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12284: is is the non-critical message twin of cstore. These functions are for
                   12285: handlers to store a perl hash to a user's permanent data space in an
                   12286: easy manner, and to retrieve it again on another call. It is expected
                   12287: that a handler would use this once at the beginning to retrieve data,
                   12288: and then again once at the end to send only the new data back.
                   12289: 
                   12290: The data is stored in the user's data directory on the user's
                   12291: homeserver under the ID of the course.
                   12292: 
                   12293: The hash that is returned by restore will have all of the previous
                   12294: value for all of the elements of the hash.
                   12295: 
                   12296: Example:
                   12297: 
                   12298:  #creating a hash
                   12299:  my %hash;
                   12300:  $hash{'foo'}='bar';
                   12301: 
                   12302:  #storing it
                   12303:  &Apache::lonnet::cstore(\%hash);
                   12304: 
                   12305:  #changing a value
                   12306:  $hash{'foo'}='notbar';
                   12307: 
                   12308:  #adding a new value
                   12309:  $hash{'bar'}='foo';
                   12310:  &Apache::lonnet::cstore(\%hash);
                   12311: 
                   12312:  #retrieving the hash
                   12313:  my %history=&Apache::lonnet::restore();
                   12314: 
                   12315:  #print the hash
                   12316:  foreach my $key (sort(keys(%history))) {
                   12317:    print("\%history{$key} = $history{$key}");
                   12318:  }
                   12319: 
                   12320: Will print out:
1.191     harris41 12321: 
1.394     bowersj2 12322:  %history{1:foo} = bar
                   12323:  %history{1:keys} = foo:timestamp
                   12324:  %history{1:timestamp} = 990455579
                   12325:  %history{2:bar} = foo
                   12326:  %history{2:foo} = notbar
                   12327:  %history{2:keys} = foo:bar:timestamp
                   12328:  %history{2:timestamp} = 990455580
                   12329:  %history{bar} = foo
                   12330:  %history{foo} = notbar
                   12331:  %history{timestamp} = 990455580
                   12332:  %history{version} = 2
                   12333: 
                   12334: Note that the special hash entries C<keys>, C<version> and
                   12335: C<timestamp> were added to the hash. C<version> will be equal to the
                   12336: total number of versions of the data that have been stored. The
                   12337: C<timestamp> attribute will be the UNIX time the hash was
                   12338: stored. C<keys> is available in every historical section to list which
                   12339: keys were added or changed at a specific historical revision of a
                   12340: hash.
                   12341: 
                   12342: B<Warning>: do not store the hash that restore returns directly. This
                   12343: will cause a mess since it will restore the historical keys as if the
                   12344: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12345: 
1.394     bowersj2 12346: Calling convention:
1.191     harris41 12347: 
1.1172.2.27  raeburn  12348:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12349:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12350: 
1.394     bowersj2 12351: For more detailed information, see lonnet specific documentation.
1.191     harris41 12352: 
1.394     bowersj2 12353: =head1 RETURN MESSAGES
1.191     harris41 12354: 
1.394     bowersj2 12355: =over 4
1.191     harris41 12356: 
1.394     bowersj2 12357: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12358: 
1.394     bowersj2 12359: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12360: when the connection is brought back up
1.191     harris41 12361: 
1.394     bowersj2 12362: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12363: for later delivery
1.191     harris41 12364: 
1.967     bisitz   12365: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12366: 
1.394     bowersj2 12367: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12368: that was requested
1.191     harris41 12369: 
1.243     albertel 12370: =back
1.191     harris41 12371: 
1.243     albertel 12372: =head1 PUBLIC SUBROUTINES
1.191     harris41 12373: 
1.243     albertel 12374: =head2 Session Environment Functions
1.191     harris41 12375: 
1.243     albertel 12376: =over 4
1.191     harris41 12377: 
1.394     bowersj2 12378: =item * 
                   12379: X<appenv()>
1.949     raeburn  12380: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12381: the user envirnoment file, and will be restored for each access this
1.620     albertel 12382: user makes during this session, also modifies the %env for the current
1.949     raeburn  12383: process. Optional rolesarrayref - if defined contains a reference to an array
                   12384: of roles which are exempt from the restriction on modifying user.role entries 
                   12385: in the user's environment.db and in %env.    
1.191     harris41 12386: 
                   12387: =item *
1.394     bowersj2 12388: X<delenv()>
1.987     raeburn  12389: B<delenv($delthis,$regexp)>: removes all items from the session
                   12390: environment file that begin with $delthis. If the 
                   12391: optional second arg - $regexp - is true, $delthis is treated as a 
                   12392: regular expression, otherwise \Q$delthis\E is used. 
                   12393: The values are also deleted from the current processes %env.
1.191     harris41 12394: 
1.795     albertel 12395: =item * get_env_multiple($name) 
                   12396: 
                   12397: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12398: values may be defined and end up as an array ref.
                   12399: 
                   12400: returns an array of values
                   12401: 
1.243     albertel 12402: =back
                   12403: 
                   12404: =head2 User Information
1.191     harris41 12405: 
1.243     albertel 12406: =over 4
1.191     harris41 12407: 
                   12408: =item *
1.394     bowersj2 12409: X<queryauthenticate()>
                   12410: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12411: authentication scheme
                   12412: 
                   12413: =item *
1.394     bowersj2 12414: X<authenticate()>
1.1073    raeburn  12415: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12416: authenticate user from domain's lib servers (first use the current
                   12417: one). C<$upass> should be the users password.
1.1073    raeburn  12418: $checkdefauth is optional (value is 1 if a check should be made to
                   12419:    authenticate user using default authentication method, and allow
                   12420:    account creation if username does not have account in the domain).
                   12421: $clientcancheckhost is optional (value is 1 if checking whether the
                   12422:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12423: 
                   12424: =item *
1.394     bowersj2 12425: X<homeserver()>
                   12426: B<homeserver($uname,$udom)>: find the server which has
                   12427: the user's directory and files (there must be only one), this caches
                   12428: the answer, and also caches if there is a borken connection.
1.191     harris41 12429: 
                   12430: =item *
1.394     bowersj2 12431: X<idget()>
                   12432: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12433: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12434: username, and only 1 username per ID in a specific domain) (returns
                   12435: hash: id=>name,id=>name)
1.191     harris41 12436: 
                   12437: =item *
1.394     bowersj2 12438: X<idrget()>
                   12439: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12440: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12441: 
                   12442: =item *
1.394     bowersj2 12443: X<idput()>
                   12444: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12445: 
                   12446: =item *
1.394     bowersj2 12447: X<rolesinit()>
1.1169    droeschl 12448: B<rolesinit($udom,$username)>: get user privileges.
                   12449: returns user role, first access and timer interval hashes
1.243     albertel 12450: 
                   12451: =item *
1.1171    droeschl 12452: X<privileged()>
                   12453: B<privileged($username,$domain)>: returns a true if user has a
                   12454: privileged and active role (i.e. su or dc), false otherwise.
                   12455: 
                   12456: =item *
1.551     albertel 12457: X<getsection()>
                   12458: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12459: course $cname, return section name/number or '' for "not in course"
                   12460: and '-1' for "no section"
                   12461: 
                   12462: =item *
1.394     bowersj2 12463: X<userenvironment()>
                   12464: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12465: passed in @what from the requested user's environment, returns a hash
                   12466: 
1.858     raeburn  12467: =item * 
                   12468: X<userlog_query()>
1.859     albertel 12469: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12470: activity.log file. %filters defines filters applied when parsing the
                   12471: log file. These can be start or end timestamps, or the type of action
                   12472: - log to look for Login or Logout events, check for Checkin or
                   12473: Checkout, role for role selection. The response is in the form
                   12474: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12475: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12476: 
1.243     albertel 12477: =back
                   12478: 
                   12479: =head2 User Roles
                   12480: 
                   12481: =over 4
                   12482: 
                   12483: =item *
                   12484: 
1.810     raeburn  12485: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12486:  F: full access
                   12487:  U,I,K: authentication modes (cxx only)
                   12488:  '': forbidden
                   12489:  1: user needs to choose course
                   12490:  2: browse allowed
1.766     albertel 12491:  A: passphrase authentication needed
1.243     albertel 12492: 
                   12493: =item *
                   12494: 
1.1172.2.13  raeburn  12495: constructaccess($url,$setpriv) : check for access to construction space URL
                   12496: 
                   12497: See if the owner domain and name in the URL match those in the
                   12498: expected environment.  If so, return three element list
                   12499: ($ownername,$ownerdomain,$ownerhome).
                   12500: 
                   12501: Otherwise return the null string.
                   12502: 
                   12503: If second argument 'setpriv' is true, it assigns the privileges,
                   12504: and returns the same three element list, unless the owner has
                   12505: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12506: in which case the null string is returned.
                   12507: 
                   12508: =item *
                   12509: 
1.243     albertel 12510: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12511: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12512: and course level
                   12513: 
                   12514: =item *
                   12515: 
1.988     raeburn  12516: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12517: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12518: $type is Course (default) or Community.
1.988     raeburn  12519: If $forcedefault evaluates to true, text returned will be default 
                   12520: text for $type. Otherwise, if this is a course, the text returned 
                   12521: will be a custom name for the role (if defined in the course's 
                   12522: environment).  If no custom name is defined the default is returned.
                   12523:    
1.832     raeburn  12524: =item *
                   12525: 
1.1172.2.23  raeburn  12526: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12527: All arguments are optional. Returns a hash of a roles, either for
                   12528: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12529: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12530: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12531: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12532: For each key, value is set to colon-separated start and end times for
                   12533: the role.  If no username and domain are specified, will default to
1.934     raeburn  12534: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12535: of role statuses (active, future or previous), roles 
                   12536: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12537: to restrict the list of roles reported. If no array ref is 
                   12538: provided for types, will default to return only active roles.
1.834     albertel 12539: 
1.1172.2.13  raeburn  12540: =item *
                   12541: 
                   12542: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12543: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12544: 
                   12545: Additional optional arguments are: $type (if role checking is to be restricted
                   12546: to certain user status types -- previous (expired roles), active (currently
                   12547: available roles) or future (roles available in the future), and
                   12548: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12549: have active Domain Coordinator role in course's domain or in additional
                   12550: domains (specified in 'Domains to check for privileged users' in course
                   12551: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12552: 
                   12553: =item *
                   12554: 
                   12555: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12556: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12557: $possdomains and $possroles are optional array refs -- to domains to check and
                   12558: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12559: users' roles.db to check for a dc or su role in any domain. This can be
                   12560: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12561: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12562: this then allows &privileged_by_domain() to be used, which caches the identity
                   12563: of privileged users, eliminating the need for repeated calls to &dump().
                   12564: 
                   12565: =item *
                   12566: 
                   12567: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12568: where the outer hash keys are domains specified in the $possdomains array ref,
                   12569: next inner hash keys are privileged roles specified in the $roles array ref,
                   12570: and the innermost hash contains key = value pairs for username:domain = end:start
                   12571: for active or future "privileged" users with that role in that domain. To avoid
                   12572: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12573: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12574: 
1.243     albertel 12575: =back
                   12576: 
                   12577: =head2 User Modification
                   12578: 
                   12579: =over 4
                   12580: 
                   12581: =item *
                   12582: 
1.957     raeburn  12583: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12584: user for the level given by URL.  Optional start and end dates (leave empty
                   12585: string or zero for "no date")
1.191     harris41 12586: 
                   12587: =item *
                   12588: 
1.243     albertel 12589: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12590: change a users, password, possible return values are: ok,
                   12591: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12592: refused
1.191     harris41 12593: 
                   12594: =item *
                   12595: 
1.243     albertel 12596: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12597: 
                   12598: =item *
                   12599: 
1.1058    raeburn  12600: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12601:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12602: 
                   12603: will update user information (firstname,middlename,lastname,generation,
                   12604: permanentemail), and if forceid is true, student/employee ID also.
                   12605: A user's institutional affiliation(s) can also be updated.
                   12606: User information fields will not be overwritten with empty entries 
                   12607: unless the field is included in the $candelete array reference.
                   12608: This array is included when a single user is modified via "Manage Users",
                   12609: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12610: 
                   12611: =item *
                   12612: 
1.286     matthew  12613: modifystudent
                   12614: 
1.957     raeburn  12615: modify a student's enrollment and identification information.
1.286     matthew  12616: The course id is resolved based on the current users environment.  
                   12617: This means the envoking user must be a course coordinator or otherwise
                   12618: associated with a course.
                   12619: 
1.297     matthew  12620: This call is essentially a wrapper for lonnet::modifyuser and
                   12621: lonnet::modify_student_enrollment
1.286     matthew  12622: 
                   12623: Inputs: 
                   12624: 
                   12625: =over 4
                   12626: 
1.957     raeburn  12627: =item B<$udom> Student's loncapa domain
1.286     matthew  12628: 
1.957     raeburn  12629: =item B<$uname> Student's loncapa login name
1.286     matthew  12630: 
1.964     bisitz   12631: =item B<$uid> Student/Employee ID
1.286     matthew  12632: 
1.957     raeburn  12633: =item B<$umode> Student's authentication mode
1.286     matthew  12634: 
1.957     raeburn  12635: =item B<$upass> Student's password
1.286     matthew  12636: 
1.957     raeburn  12637: =item B<$first> Student's first name
1.286     matthew  12638: 
1.957     raeburn  12639: =item B<$middle> Student's middle name
1.286     matthew  12640: 
1.957     raeburn  12641: =item B<$last> Student's last name
1.286     matthew  12642: 
1.957     raeburn  12643: =item B<$gene> Student's generation
1.286     matthew  12644: 
1.957     raeburn  12645: =item B<$usec> Student's section in course
1.286     matthew  12646: 
                   12647: =item B<$end> Unix time of the roles expiration
                   12648: 
                   12649: =item B<$start> Unix time of the roles start date
                   12650: 
                   12651: =item B<$forceid> If defined, allow $uid to be changed
                   12652: 
                   12653: =item B<$desiredhome> server to use as home server for student
                   12654: 
1.957     raeburn  12655: =item B<$email> Student's permanent e-mail address
                   12656: 
                   12657: =item B<$type> Type of enrollment (auto or manual)
                   12658: 
1.963     raeburn  12659: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12660: 
                   12661: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12662: 
1.963     raeburn  12663: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12664: 
1.963     raeburn  12665: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12666: 
1.1172.2.19  raeburn  12667: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12668: 
                   12669: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  12670: 
1.286     matthew  12671: =back
1.297     matthew  12672: 
                   12673: =item *
                   12674: 
                   12675: modify_student_enrollment
                   12676: 
                   12677: Change a students enrollment status in a class.  The environment variable
                   12678: 'role.request.course' must be defined for this function to proceed.
                   12679: 
                   12680: Inputs:
                   12681: 
                   12682: =over 4
                   12683: 
                   12684: =item $udom, students domain
                   12685: 
                   12686: =item $uname, students name
                   12687: 
                   12688: =item $uid, students user id
                   12689: 
                   12690: =item $first, students first name
                   12691: 
                   12692: =item $middle
                   12693: 
                   12694: =item $last
                   12695: 
                   12696: =item $gene
                   12697: 
                   12698: =item $usec
                   12699: 
                   12700: =item $end
                   12701: 
                   12702: =item $start
                   12703: 
1.957     raeburn  12704: =item $type
                   12705: 
                   12706: =item $locktype
                   12707: 
                   12708: =item $cid
                   12709: 
                   12710: =item $selfenroll
                   12711: 
                   12712: =item $context
                   12713: 
1.1172.2.19  raeburn  12714: =item $credits, number of credits student will earn from this class
                   12715: 
1.297     matthew  12716: =back
                   12717: 
1.191     harris41 12718: 
                   12719: =item *
                   12720: 
1.243     albertel 12721: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12722: custom role; give a custom role to a user for the level given by URL.  Specify
                   12723: name and domain of role author, and role name
1.191     harris41 12724: 
                   12725: =item *
                   12726: 
1.243     albertel 12727: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12728: 
                   12729: =item *
                   12730: 
1.243     albertel 12731: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12732: 
                   12733: =back
                   12734: 
                   12735: =head2 Course Infomation
                   12736: 
                   12737: =over 4
1.191     harris41 12738: 
                   12739: =item *
                   12740: 
1.1118    foxr     12741: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12742: specified course id, including all environment settings for the
                   12743: course, the description of the course will be in the hash under the
                   12744: key 'description'
1.191     harris41 12745: 
1.1118    foxr     12746: $options is an optional parameter that if supplied is a hash reference that controls
                   12747: what how this function works.  It has the following key/values:
                   12748: 
                   12749: =over 4
                   12750: 
                   12751: =item freshen_cache
                   12752: 
                   12753: If defined, and the environment cache for the course is valid, it is 
                   12754: returned in the returned hash.
                   12755: 
                   12756: =item one_time
                   12757: 
                   12758: If defined, the last cache time is set to _now_
                   12759: 
                   12760: =item user
                   12761: 
                   12762: If defined, the supplied username is used instead of the current user.
                   12763: 
                   12764: 
                   12765: =back
                   12766: 
1.191     harris41 12767: =item *
                   12768: 
1.624     albertel 12769: resdata($name,$domain,$type,@which) : request for current parameter
                   12770: setting for a specific $type, where $type is either 'course' or 'user',
                   12771: @what should be a list of parameters to ask about. This routine caches
                   12772: answers for 5 minutes.
1.243     albertel 12773: 
1.877     foxr     12774: =item *
                   12775: 
                   12776: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12777: data base, returning a hash that is keyed by the resource name and has
                   12778: values that are the resource value.  I believe that the timestamps and
                   12779: versions are also returned.
                   12780: 
1.243     albertel 12781: =back
                   12782: 
                   12783: =head2 Course Modification
                   12784: 
                   12785: =over 4
1.191     harris41 12786: 
                   12787: =item *
                   12788: 
1.243     albertel 12789: writecoursepref($courseid,%prefs) : write preferences (environment
                   12790: database) for a course
1.191     harris41 12791: 
                   12792: =item *
                   12793: 
1.1011    raeburn  12794: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12795: 
                   12796: =item *
                   12797: 
1.1038    raeburn  12798: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12799: 
1.1167    droeschl 12800: =item *
                   12801: 
                   12802: is_course($courseid), is_course($cdom, $cnum)
                   12803: 
                   12804: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12805: two component version $cdom, $cnum. It checks if the specified course exists.
                   12806: 
                   12807: Returns:
                   12808:     undef if the course doesn't exist, otherwise
                   12809:     in scalar context the combined courseid.
                   12810:     in list context the two components of the course identifier, domain and 
                   12811:     courseid.    
                   12812: 
1.243     albertel 12813: =back
                   12814: 
                   12815: =head2 Resource Subroutines
                   12816: 
                   12817: =over 4
1.191     harris41 12818: 
                   12819: =item *
                   12820: 
1.243     albertel 12821: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12822: 
                   12823: =item *
                   12824: 
1.243     albertel 12825: repcopy($filename) : subscribes to the requested file, and attempts to
                   12826: replicate from the owning library server, Might return
1.607     raeburn  12827: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12828: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12829: resource. Expects the local filesystem pathname
                   12830: (/home/httpd/html/res/....)
                   12831: 
                   12832: =back
                   12833: 
                   12834: =head2 Resource Information
                   12835: 
                   12836: =over 4
1.191     harris41 12837: 
                   12838: =item *
                   12839: 
1.1172.2.28! raeburn  12840: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
        !          12841: and returns the value of a variety of different possible values,
        !          12842: $varname should be a request string, and the other parameters can be
        !          12843: used to specify who and what one is asking about. Ordinarily, $cid 
        !          12844: does not need to be specified, as it is retrived from 
        !          12845: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
        !          12846: within lonuserstate::loadmap() when initializing a course, before
        !          12847: $env{'request.course.id'} has been set, so it needs to be provided
        !          12848: in that one case.
1.243     albertel 12849: 
                   12850: Possible values for $varname are environment.lastname (or other item
                   12851: from the envirnment hash), user.name (or someother aspect about the
                   12852: user), resource.0.maxtries (or some other part and parameter of a
                   12853: resource)
1.204     albertel 12854: 
                   12855: =item *
                   12856: 
1.243     albertel 12857: directcondval($number) : get current value of a condition; reads from a state
                   12858: string
1.204     albertel 12859: 
                   12860: =item *
                   12861: 
1.243     albertel 12862: condval($condidx) : value of condition index based on state
1.204     albertel 12863: 
                   12864: =item *
                   12865: 
1.243     albertel 12866: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12867: resource's metadata, $what should be either a specific key, or either
                   12868: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12869: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12870: 
                   12871: this function automatically caches all requests
1.191     harris41 12872: 
                   12873: =item *
                   12874: 
1.243     albertel 12875: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12876: network of library servers; returns file handle of where SQL and regex results
                   12877: will be stored for query
1.191     harris41 12878: 
                   12879: =item *
                   12880: 
1.243     albertel 12881: symbread($filename) : return symbolic list entry (filename argument optional);
                   12882: returns the data handle
1.191     harris41 12883: 
                   12884: =item *
                   12885: 
1.1172.2.17  raeburn  12886: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12887: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12888: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12889: on failure, user must be in a course, as it assumes the existence of
                   12890: the course initial hash, and uses $env('request.course.id'}.  The third
                   12891: arg is an optional reference to a scalar.  If this arg is passed in the
                   12892: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12893: encrypted; otherwise it will be null.
1.243     albertel 12894: 
1.191     harris41 12895: =item *
                   12896: 
1.243     albertel 12897: symbclean($symb) : removes versions numbers from a symb, returns the
                   12898: cleaned symb
1.191     harris41 12899: 
                   12900: =item *
                   12901: 
1.243     albertel 12902: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12903: course map, user must be in a course for it to work.
1.191     harris41 12904: 
                   12905: =item *
                   12906: 
1.243     albertel 12907: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12908: 
                   12909: =item *
                   12910: 
1.243     albertel 12911: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12912: a random seed, all arguments are optional, if they aren't sent it uses the
                   12913: environment to derive them. Note: if symb isn't sent and it can't get one
                   12914: from &symbread it will use the current time as its return value
1.191     harris41 12915: 
                   12916: =item *
                   12917: 
1.243     albertel 12918: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12919: unfakeable, receipt
1.191     harris41 12920: 
                   12921: =item *
                   12922: 
1.620     albertel 12923: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12924: 
                   12925: =item *
                   12926: 
1.243     albertel 12927: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12928: 
                   12929: =item *
                   12930: 
1.243     albertel 12931: 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 12932: 
                   12933: =item *
                   12934: 
1.243     albertel 12935: 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 12936: 
                   12937: =item *
                   12938: 
1.243     albertel 12939: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12940: 
                   12941: =item *
                   12942: 
1.243     albertel 12943: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12944: forcing spreadsheet to reevaluate the resource scores next time.
                   12945: 
1.1172.2.13  raeburn  12946: =item *
                   12947: 
                   12948: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12949: when viewing in course context.
                   12950: 
                   12951:  input: six args -- filename (decluttered), course number, course domain,
                   12952:                     url, symb (if registered) and group (if this is a
                   12953:                     group item -- e.g., bulletin board, group page etc.).
                   12954: 
                   12955:  output: array of five scalars --
                   12956:          $cfile -- url for file editing if editable on current server
                   12957:          $home -- homeserver of resource (i.e., for author if published,
                   12958:                                           or course if uploaded.).
                   12959:          $switchserver --  1 if server switch will be needed.
                   12960:          $forceedit -- 1 if icon/link should be to go to edit mode
                   12961:          $forceview -- 1 if icon/link should be to go to view mode
                   12962: 
                   12963: =item *
                   12964: 
                   12965: is_course_upload($file,$cnum,$cdom)
                   12966: 
                   12967: Used in course context to determine if current file was uploaded to
                   12968: the course (i.e., would be found in /userfiles/docs on the course's
                   12969: homeserver.
                   12970: 
                   12971:   input: 3 args -- filename (decluttered), course number and course domain.
                   12972:   output: boolean -- 1 if file was uploaded.
                   12973: 
1.243     albertel 12974: =back
                   12975: 
                   12976: =head2 Storing/Retreiving Data
                   12977: 
                   12978: =over 4
1.191     harris41 12979: 
                   12980: =item *
                   12981: 
1.243     albertel 12982: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12983: for this url; hashref needs to be given and should be a \%hashname; the
                   12984: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12985: be derived from the env
1.191     harris41 12986: 
                   12987: =item *
                   12988: 
1.243     albertel 12989: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12990: uses critical subroutine
1.191     harris41 12991: 
                   12992: =item *
                   12993: 
1.243     albertel 12994: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12995: all args are optional
1.191     harris41 12996: 
                   12997: =item *
                   12998: 
1.717     albertel 12999: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13000: dumps the complete (or key matching regexp) namespace into a hash
                   13001: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13002: normally &store()ed into
                   13003: 
                   13004: $range should be either an integer '100' (give me the first 100
                   13005:                                            matching records)
                   13006:               or be  two integers sperated by a - with no spaces
                   13007:                  '30-50' (give me the 30th through the 50th matching
                   13008:                           records)
                   13009: 
                   13010: 
                   13011: =item *
                   13012: 
                   13013: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13014: replaces a &store() version of data with a replacement set of data
                   13015: for a particular resource in a namespace passed in the $storehash hash 
                   13016: reference
                   13017: 
                   13018: =item *
                   13019: 
1.243     albertel 13020: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13021: works very similar to store/cstore, but all data is stored in a
                   13022: temporary location and can be reset using tmpreset, $storehash should
                   13023: be a hash reference, returns nothing on success
1.191     harris41 13024: 
                   13025: =item *
                   13026: 
1.243     albertel 13027: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13028: similar to restore, but all data is stored in a temporary location and
                   13029: can be reset using tmpreset. Returns a hash of values on success,
                   13030: error string otherwise.
1.191     harris41 13031: 
                   13032: =item *
                   13033: 
1.243     albertel 13034: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13035: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13036: 
                   13037: =item *
                   13038: 
1.243     albertel 13039: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13040: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13041: 
                   13042: =item *
                   13043: 
1.243     albertel 13044: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13045: namesp ($udom and $uname are optional)
1.191     harris41 13046: 
                   13047: =item *
                   13048: 
1.702     albertel 13049: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13050: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13051: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13052: 
1.702     albertel 13053: $range should be either an integer '100' (give me the first 100
                   13054:                                            matching records)
                   13055:               or be  two integers sperated by a - with no spaces
                   13056:                  '30-50' (give me the 30th through the 50th matching
                   13057:                           records)
1.449     matthew  13058: =item *
                   13059: 
                   13060: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13061: $store can be a scalar, an array reference, or if the amount to be 
                   13062: incremented is > 1, a hash reference.
                   13063: 
                   13064: ($udom and $uname are optional)
1.191     harris41 13065: 
                   13066: =item *
                   13067: 
1.243     albertel 13068: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13069: ($udom and $uname are optional)
1.191     harris41 13070: 
                   13071: =item *
                   13072: 
1.243     albertel 13073: cput($namespace,$storehash,$udom,$uname) : critical put
                   13074: ($udom and $uname are optional)
1.191     harris41 13075: 
                   13076: =item *
                   13077: 
1.748     albertel 13078: newput($namespace,$storehash,$udom,$uname) :
                   13079: 
                   13080: Attempts to store the items in the $storehash, but only if they don't
                   13081: currently exist, if this succeeds you can be certain that you have 
                   13082: successfully created a new key value pair in the $namespace db.
                   13083: 
                   13084: 
                   13085: Args:
                   13086:  $namespace: name of database to store values to
                   13087:  $storehash: hashref to store to the db
                   13088:  $udom: (optional) domain of user containing the db
                   13089:  $uname: (optional) name of user caontaining the db
                   13090: 
                   13091: Returns:
                   13092:  'ok' -> succeeded in storing all keys of $storehash
                   13093:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13094:                         least <key> already existed in the db (other
                   13095:                         requested keys may also already exist)
1.967     bisitz   13096:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13097:  'con_lost' -> unable to contact request server
                   13098:  'refused' -> action was not allowed by remote machine
                   13099: 
                   13100: 
                   13101: =item *
                   13102: 
1.243     albertel 13103: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13104: reference filled in from namesp (encrypts the return communication)
                   13105: ($udom and $uname are optional)
1.191     harris41 13106: 
                   13107: =item *
                   13108: 
1.243     albertel 13109: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13110: critical subroutine
                   13111: 
1.806     raeburn  13112: =item *
                   13113: 
1.860     raeburn  13114: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13115: array reference filled in from namespace found in domain level on either
                   13116: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13117: 
                   13118: =item *
                   13119: 
1.860     raeburn  13120: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13121: domain level either on specified domain server ($uhome) or primary domain 
                   13122: server ($udom and $uhome are optional)
1.806     raeburn  13123: 
1.943     raeburn  13124: =item * 
                   13125: 
                   13126: get_domain_defaults($target_domain) : returns hash with defaults for
                   13127: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13128: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13129: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13130: Values are retrieved from cache (if current), or from domain's configuration.db
                   13131: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13132: or lonTabs/domain.tab. 
                   13133: 
                   13134: %domdefaults = &get_auth_defaults($target_domain);
                   13135: 
1.243     albertel 13136: =back
                   13137: 
                   13138: =head2 Network Status Functions
                   13139: 
                   13140: =over 4
1.191     harris41 13141: 
                   13142: =item *
                   13143: 
1.1137    raeburn  13144: dirlist() : return directory list based on URI (first arg).
                   13145: 
                   13146: Inputs: 1 required, 5 optional.
                   13147: 
                   13148: =over
                   13149: 
                   13150: =item 
                   13151: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13152: 
                   13153: =item
                   13154: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13155: 
                   13156: =item
                   13157: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13158: 
                   13159: =item
                   13160: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13161: 
                   13162: =item
                   13163: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13164: 
                   13165: =item 
                   13166: $alternateRoot - path to prepend in place of path from $uri.
                   13167: 
                   13168: =back
                   13169: 
                   13170: Returns: Array of up to two items.
                   13171: 
                   13172: =over
                   13173: 
                   13174: a reference to an array of files/subdirectories
                   13175: 
                   13176: =over
                   13177: 
                   13178: Each element in the array of files/subdirectories is a & separated list of
                   13179: item name and the result of running stat on the item.  If dirlist was requested
                   13180: for a file instead of a directory, the item name will be ''. For a directory 
                   13181: listing, if the item is a metadata file, the element will end &N&M 
                   13182: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13183: default copyright set (1).  
                   13184: 
                   13185: =back
                   13186: 
                   13187: a scalar containing error condition (if encountered).
                   13188: 
                   13189: =over
                   13190: 
                   13191: =item 
                   13192: no_host (no homeserver identified for $username:$domain).
                   13193: 
                   13194: =item 
                   13195: no_such_host (server contacted for listing not identified as valid host).
                   13196: 
                   13197: =item 
                   13198: con_lost (connection to remote server failed).
                   13199: 
                   13200: =item 
                   13201: refused (invalid $username:$domain received on lond side).
                   13202: 
                   13203: =item 
                   13204: no_such_dir (directory at specified path on lond side does not exist). 
                   13205: 
                   13206: =item 
                   13207: empty (directory at specified path on lond side is empty).
                   13208: 
                   13209: =over
                   13210: 
                   13211: This is currently not encountered because the &ls3, &ls2, 
                   13212: &ls (_handler) routines on the lond side do not filter out
                   13213: . and .. from a directory listing. 
                   13214: 
                   13215: =back
                   13216: 
                   13217: =back
                   13218: 
                   13219: =back
1.191     harris41 13220: 
                   13221: =item *
                   13222: 
1.243     albertel 13223: spareserver() : find server with least workload from spare.tab
                   13224: 
1.986     foxr     13225: 
                   13226: =item *
                   13227: 
                   13228: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13229: if there is no corresponding loncapa host.
                   13230: 
1.243     albertel 13231: =back
                   13232: 
1.986     foxr     13233: 
1.243     albertel 13234: =head2 Apache Request
                   13235: 
                   13236: =over 4
1.191     harris41 13237: 
                   13238: =item *
                   13239: 
1.243     albertel 13240: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13241: localhost, posts hash
                   13242: 
                   13243: =back
                   13244: 
                   13245: =head2 Data to String to Data
                   13246: 
                   13247: =over 4
1.191     harris41 13248: 
                   13249: =item *
                   13250: 
1.243     albertel 13251: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13252: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13253: 
                   13254: =item *
                   13255: 
1.243     albertel 13256: hashref2str($hashref) : convert a hashref into a string complete with
                   13257: escaping and '=' and '&' separators, supports elements that are
                   13258: arrayrefs and hashrefs
1.191     harris41 13259: 
                   13260: =item *
                   13261: 
1.243     albertel 13262: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13263: with escaping and '&' separators, supports elements that are arrayrefs
                   13264: and hashrefs
1.191     harris41 13265: 
                   13266: =item *
                   13267: 
1.243     albertel 13268: str2hash($string) : convert string to hash using unescaping and
                   13269: splitting on '=' and '&', supports elements that are arrayrefs and
                   13270: hashrefs
1.191     harris41 13271: 
                   13272: =item *
                   13273: 
1.243     albertel 13274: str2array($string) : convert string to hash using unescaping and
                   13275: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13276: 
                   13277: =back
                   13278: 
                   13279: =head2 Logging Routines
                   13280: 
                   13281: 
                   13282: These routines allow one to make log messages in the lonnet.log and
                   13283: lonnet.perm logfiles.
1.191     harris41 13284: 
1.1119    foxr     13285: =over 4
                   13286: 
1.191     harris41 13287: =item *
                   13288: 
1.243     albertel 13289: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13290: 
                   13291: =item *
                   13292: 
1.243     albertel 13293: logthis() : append message to the normal lonnet.log file, it gets
                   13294: preiodically rolled over and deleted.
1.191     harris41 13295: 
                   13296: =item *
                   13297: 
1.243     albertel 13298: logperm() : append a permanent message to lonnet.perm.log, this log
                   13299: file never gets deleted by any automated portion of the system, only
                   13300: messages of critical importance should go in here.
                   13301: 
1.1119    foxr     13302: 
1.243     albertel 13303: =back
                   13304: 
                   13305: =head2 General File Helper Routines
                   13306: 
                   13307: =over 4
1.191     harris41 13308: 
                   13309: =item *
                   13310: 
1.481     raeburn  13311: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13312: (a) files in /uploaded
                   13313:   (i) If a local copy of the file exists - 
                   13314:       compares modification date of local copy with last-modified date for 
                   13315:       definitive version stored on home server for course. If local copy is 
                   13316:       stale, requests a new version from the home server and stores it. 
                   13317:       If the original has been removed from the home server, then local copy 
                   13318:       is unlinked.
                   13319:   (ii) If local copy does not exist -
                   13320:       requests the file from the home server and stores it. 
                   13321:   
                   13322:   If $caller is 'uploadrep':  
                   13323:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13324:     for request for files originally uploaded via DOCS. 
                   13325:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13326:   
                   13327:   Otherwise:
                   13328:      This indicates a call from the content generation phase of the request.
                   13329:      -  returns the entire contents of the file or -1.
                   13330:      
                   13331: (b) files in /res
                   13332:    - returns the entire contents of a file or -1; 
                   13333:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13334: 
1.712     albertel 13335: 
                   13336: =item *
                   13337: 
                   13338: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13339:                   reference
                   13340: 
                   13341: returns either a stat() list of data about the file or an empty list
                   13342: if the file doesn't exist or couldn't find out about it (connection
                   13343: problems or user unknown)
                   13344: 
1.191     harris41 13345: =item *
                   13346: 
1.243     albertel 13347: filelocation($dir,$file) : returns file system location of a file
                   13348: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13349: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13350: and a file of ../bob will become /a/bob)
1.191     harris41 13351: 
                   13352: =item *
                   13353: 
                   13354: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13355: filelocation except for hrefs
                   13356: 
                   13357: =item *
                   13358: 
                   13359: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13360: 
1.243     albertel 13361: =back
                   13362: 
1.608     albertel 13363: =head2 Usererfile file routines (/uploaded*)
                   13364: 
                   13365: =over 4
                   13366: 
                   13367: =item *
                   13368: 
                   13369: userfileupload(): main rotine for putting a file in a user or course's
                   13370:                   filespace, arguments are,
                   13371: 
1.620     albertel 13372:  formname - required - this is the name of the element in $env where the
1.608     albertel 13373:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13374:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13375:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13376:  context - if coursedoc, store the file in the course of the active role
                   13377:              of the current user; 
                   13378:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13379:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13380:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13381:          if undefined, it will be placed in "unknown"
                   13382: 
                   13383:  (This routine calls clean_filename() to remove any dangerous
                   13384:  characters from the filename, and then calls finuserfileupload() to
                   13385:  complete the transaction)
                   13386: 
                   13387:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13388:  and /adm/notfound.html if unsuccessful
                   13389: 
                   13390: =item *
                   13391: 
                   13392: clean_filename(): routine for cleaing a filename up for storage in
                   13393:                  userfile space, argument is:
                   13394: 
                   13395:  filename - proposed filename
                   13396: 
                   13397: returns: the new clean filename
                   13398: 
                   13399: =item *
                   13400: 
1.1090    raeburn  13401: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13402: userspace, probably shouldn't be called directly
                   13403: 
                   13404:   docuname: username or courseid of destination for the file
                   13405:   docudom: domain of user/course of destination for the file
                   13406:   formname: same as for userfileupload()
1.1090    raeburn  13407:   fname: filename (including subdirectories) for the file
                   13408:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13409:   allfiles: reference to hash used to store objects found by parser
                   13410:   codebase: reference to hash used for codebases of java objects found by parser
                   13411:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13412:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13413:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13414:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13415:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13416:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13417:   mimetype: reference to scalar to accommodate mime type determined
                   13418:             from File::MMagic if $parser = parse.
1.608     albertel 13419: 
                   13420:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13421:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13422:  was 'overwrite').
                   13423:  
1.608     albertel 13424: 
                   13425: =item *
                   13426: 
                   13427: renameuserfile(): renames an existing userfile to a new name
                   13428: 
                   13429:   Args:
                   13430:    docuname: username or courseid of destination for the file
                   13431:    docudom: domain of user/course of destination for the file
                   13432:    old: current file name (including any subdirs under userfiles)
                   13433:    new: desired file name (including any subdirs under userfiles)
                   13434: 
                   13435: =item *
                   13436: 
                   13437: mkdiruserfile(): creates a directory is a userfiles dir
                   13438: 
                   13439:   Args:
                   13440:    docuname: username or courseid of destination for the file
                   13441:    docudom: domain of user/course of destination for the file
                   13442:    dir: dir to create (including any subdirs under userfiles)
                   13443: 
                   13444: =item *
                   13445: 
                   13446: removeuserfile(): removes a file that exists in userfiles
                   13447: 
                   13448:   Args:
                   13449:    docuname: username or courseid of destination for the file
                   13450:    docudom: domain of user/course of destination for the file
                   13451:    fname: filname to delete (including any subdirs under userfiles)
                   13452: 
                   13453: =item *
                   13454: 
                   13455: removeuploadedurl(): convience function for removeuserfile()
                   13456: 
                   13457:   Args:
                   13458:    url:  a full /uploaded/... url to delete
                   13459: 
1.747     albertel 13460: =item * 
                   13461: 
                   13462: get_portfile_permissions():
                   13463:   Args:
                   13464:     domain: domain of user or course contain the portfolio files
                   13465:     user: name of user or num of course contain the portfolio files
                   13466:   Returns:
                   13467:     hashref of a dump of the proper file_permissions.db
                   13468:    
                   13469: 
                   13470: =item * 
                   13471: 
                   13472: get_access_controls():
                   13473: 
                   13474: Args:
                   13475:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13476:   group: (optional) the group you want the files associated with
                   13477:   file: (optional) the file you want access info on
                   13478: 
                   13479: Returns:
1.749     raeburn  13480:     a hash (keys are file names) of hashes containing
                   13481:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13482:         values are XML containing access control settings (see below) 
1.747     albertel 13483: 
                   13484: Internal notes:
                   13485: 
1.749     raeburn  13486:  access controls are stored in file_permissions.db as key=value pairs.
                   13487:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13488:         where scope -> public,guest,course,group,domains or users.
                   13489:               end -> UNIX time for end of access (0 -> no end date)
                   13490:               start -> UNIX time for start of access
                   13491: 
                   13492:     value -> XML description of access control
                   13493:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13494:             <start></start>
                   13495:             <end></end>
                   13496: 
                   13497:             <password></password>  for scope type = guest
                   13498: 
                   13499:             <domain></domain>     for scope type = course or group
                   13500:             <number></number>
                   13501:             <roles id="">
                   13502:              <role></role>
                   13503:              <access></access>
                   13504:              <section></section>
                   13505:              <group></group>
                   13506:             </roles>
                   13507: 
                   13508:             <dom></dom>         for scope type = domains
                   13509: 
                   13510:             <users>             for scope type = users
                   13511:              <user>
                   13512:               <uname></uname>
                   13513:               <udom></udom>
                   13514:              </user>
                   13515:             </users>
                   13516:            </scope> 
                   13517:               
                   13518:  Access data is also aggregated for each file in an additional key=value pair:
                   13519:  key -> path to file/file_name\0accesscontrol 
                   13520:  value -> reference to hash
                   13521:           hash contains key = value pairs
                   13522:           where key = uniqueID:scope_end_start
                   13523:                 value = UNIX time record was last updated
                   13524: 
                   13525:           Used to improve speed of look-ups of access controls for each file.  
                   13526:  
                   13527:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13528: 
1.1172.2.13  raeburn  13529: =item *
                   13530: 
1.749     raeburn  13531: modify_access_controls():
                   13532: 
                   13533: Modifies access controls for a portfolio file
                   13534: Args
                   13535: 1. file name
                   13536: 2. reference to hash of required changes,
                   13537: 3. domain
                   13538: 4. username
                   13539:   where domain,username are the domain of the portfolio owner 
                   13540:   (either a user or a course) 
                   13541: 
                   13542: Returns:
                   13543: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13544: 2. result of deletions ('ok' or 'error', with error message).
                   13545: 3. reference to hash of any new or updated access controls.
                   13546: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13547:    key = integer (inbound ID)
1.1172.2.13  raeburn  13548:    value = uniqueID
                   13549: 
                   13550: =item *
                   13551: 
                   13552: get_timebased_id():
                   13553: 
                   13554: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13555: course via the Course Editor (e.g., folders, composite pages,
                   13556: group bulletin boards).
                   13557: 
                   13558: Args: (first three required; six others optional)
                   13559: 
                   13560: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13561:    docssequence, or name of group
                   13562: 
                   13563: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13564:    e.g., num, boardids
                   13565: 
                   13566: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13567:    file will be named nohist_namespace.db
                   13568: 
                   13569: 4. cdom: domain of course; default is current course domain from %env
                   13570: 
                   13571: 5. cnum: course number; default is current course number from %env
                   13572: 
                   13573: 6. idtype: set to concat if an additional digit is to be appended to the
                   13574:    unix timestamp to form the suffix, if the plain timestamp is already
                   13575:    in use.  Default is to not do this, but simply increment the unix
                   13576:    timestamp by 1 until a unique key is obtained.
                   13577: 
                   13578: 7. who: holder of locking key; defaults to user:domain for user.
                   13579: 
                   13580: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13581:    retrying); default is 3.
                   13582: 
                   13583: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13584: 
                   13585: Returns:
                   13586: 
                   13587: 1. suffix obtained (numeric)
                   13588: 
                   13589: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13590: 
                   13591: 3. error: contains (localized) error message if an error occurred.
                   13592: 
1.747     albertel 13593: 
1.608     albertel 13594: =back
                   13595: 
1.243     albertel 13596: =head2 HTTP Helper Routines
                   13597: 
                   13598: =over 4
                   13599: 
1.191     harris41 13600: =item *
                   13601: 
                   13602: escape() : unpack non-word characters into CGI-compatible hex codes
                   13603: 
                   13604: =item *
                   13605: 
                   13606: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13607: 
1.243     albertel 13608: =back
                   13609: 
                   13610: =head1 PRIVATE SUBROUTINES
                   13611: 
                   13612: =head2 Underlying communication routines (Shouldn't call)
                   13613: 
                   13614: =over 4
                   13615: 
                   13616: =item *
                   13617: 
                   13618: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13619: 
                   13620: =item *
                   13621: 
                   13622: reply() : uses subreply to send a message to remote machine, logs all failures
                   13623: 
                   13624: =item *
                   13625: 
                   13626: critical() : passes a critical message to another server; if cannot
                   13627: get through then place message in connection buffer directory and
                   13628: returns con_delayed, if incapable of saving message, returns
                   13629: con_failed
                   13630: 
                   13631: =item *
                   13632: 
                   13633: reconlonc() : tries to reconnect lonc client processes.
                   13634: 
                   13635: =back
                   13636: 
                   13637: =head2 Resource Access Logging
                   13638: 
                   13639: =over 4
                   13640: 
                   13641: =item *
                   13642: 
                   13643: flushcourselogs() : flush (save) buffer logs and access logs
                   13644: 
                   13645: =item *
                   13646: 
                   13647: courselog($what) : save message for course in hash
                   13648: 
                   13649: =item *
                   13650: 
                   13651: courseacclog($what) : save message for course using &courselog().  Perform
                   13652: special processing for specific resource types (problems, exams, quizzes, etc).
                   13653: 
1.191     harris41 13654: =item *
                   13655: 
                   13656: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13657: as a PerlChildExitHandler
1.243     albertel 13658: 
                   13659: =back
                   13660: 
                   13661: =head2 Other
                   13662: 
                   13663: =over 4
                   13664: 
                   13665: =item *
                   13666: 
                   13667: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13668: 
                   13669: =back
                   13670: 
                   13671: =cut
1.877     foxr     13672: 

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