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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.30! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.29 2013/07/05 15:53:28 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.1172.2.30! raeburn  1579: # ---------------------------------------- Delete unwanted IDs from ids.db file
        !          1580: 
        !          1581: sub iddel {
        !          1582:     my ($udom,$idshashref,$uhome)=@_;
        !          1583:     my %result=();
        !          1584:     unless (ref($idshashref) eq 'HASH') {
        !          1585:         return %result;
        !          1586:     }
        !          1587:     my %servers=();
        !          1588:     while (my ($id,$uname) = each(%{$idshashref})) {
        !          1589:         my $uhom;
        !          1590:         if ($uhome) {
        !          1591:             $uhom = $uhome;
        !          1592:         } else {
        !          1593:             $uhom=&homeserver($uname,$udom);
        !          1594:         }
        !          1595:         if ($uhom ne 'no_host') {
        !          1596:             if ($servers{$uhom}) {
        !          1597:                 $servers{$uhom}.='&'.&escape($id);
        !          1598:             } else {
        !          1599:                 $servers{$uhom}=&escape($id);
        !          1600:             }
        !          1601:         }
        !          1602:     }
        !          1603:     foreach my $server (keys(%servers)) {
        !          1604:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
        !          1605:     }
        !          1606:     return %result;
        !          1607: }
        !          1608: 
1.1023    raeburn  1609: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1610: sub dump_dom {
1.1165    droeschl 1611:     my ($namespace, $udom, $regexp) = @_;
                   1612: 
                   1613:     $udom ||= $env{'user.domain'};
                   1614: 
                   1615:     return () unless $udom;
                   1616: 
                   1617:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1618: }
                   1619: 
1.1023    raeburn  1620: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1621: 
                   1622: sub get_dom {
1.860     raeburn  1623:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1624:     my $items='';
                   1625:     foreach my $item (@$storearr) {
                   1626:         $items.=&escape($item).'&';
                   1627:     }
                   1628:     $items=~s/\&$//;
1.860     raeburn  1629:     if (!$udom) {
                   1630:         $udom=$env{'user.domain'};
                   1631:         if (defined(&domain($udom,'primary'))) {
                   1632:             $uhome=&domain($udom,'primary');
                   1633:         } else {
1.874     albertel 1634:             undef($uhome);
1.860     raeburn  1635:         }
                   1636:     } else {
                   1637:         if (!$uhome) {
                   1638:             if (defined(&domain($udom,'primary'))) {
                   1639:                 $uhome=&domain($udom,'primary');
                   1640:             }
                   1641:         }
                   1642:     }
                   1643:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1644:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1645:         my %returnhash;
1.875     albertel 1646:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1647:             return %returnhash;
                   1648:         }
1.806     raeburn  1649:         my @pairs=split(/\&/,$rep);
                   1650:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1651:             return @pairs;
                   1652:         }
                   1653:         my $i=0;
                   1654:         foreach my $item (@$storearr) {
                   1655:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1656:             $i++;
                   1657:         }
                   1658:         return %returnhash;
                   1659:     } else {
1.880     banghart 1660:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1661:     }
                   1662: }
                   1663: 
                   1664: # -------------------------------------------- put items in domain db files 
                   1665: 
                   1666: sub put_dom {
1.860     raeburn  1667:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1668:     if (!$udom) {
                   1669:         $udom=$env{'user.domain'};
                   1670:         if (defined(&domain($udom,'primary'))) {
                   1671:             $uhome=&domain($udom,'primary');
                   1672:         } else {
1.874     albertel 1673:             undef($uhome);
1.860     raeburn  1674:         }
                   1675:     } else {
                   1676:         if (!$uhome) {
                   1677:             if (defined(&domain($udom,'primary'))) {
                   1678:                 $uhome=&domain($udom,'primary');
                   1679:             }
                   1680:         }
                   1681:     } 
                   1682:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1683:         my $items='';
                   1684:         foreach my $item (keys(%$storehash)) {
                   1685:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1686:         }
                   1687:         $items=~s/\&$//;
                   1688:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1689:     } else {
1.860     raeburn  1690:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1691:     }
                   1692: }
                   1693: 
1.1023    raeburn  1694: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1695: sub newput_dom {
1.1023    raeburn  1696:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1697:     my $result;
                   1698:     if (!$udom) {
                   1699:         $udom=$env{'user.domain'};
                   1700:     }
1.1023    raeburn  1701:     if ($udom) {
                   1702:         my $uname = &get_domainconfiguser($udom);
                   1703:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1704:     }
                   1705:     return $result;
                   1706: }
                   1707: 
1.1023    raeburn  1708: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1709: sub del_dom {
1.1023    raeburn  1710:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1711:     if (ref($storearr) eq 'ARRAY') {
                   1712:         if (!$udom) {
                   1713:             $udom=$env{'user.domain'};
                   1714:         }
1.1023    raeburn  1715:         if ($udom) {
                   1716:             my $uname = &get_domainconfiguser($udom); 
                   1717:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1718:         }
                   1719:     }
                   1720: }
                   1721: 
1.1023    raeburn  1722: # ----------------------------------construct domainconfig user for a domain 
                   1723: sub get_domainconfiguser {
                   1724:     my ($udom) = @_;
                   1725:     return $udom.'-domainconfig';
                   1726: }
                   1727: 
1.837     raeburn  1728: sub retrieve_inst_usertypes {
                   1729:     my ($udom) = @_;
                   1730:     my (%returnhash,@order);
1.989     raeburn  1731:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1732:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1733:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1734:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1735:         @order = @{$domdefs{'inststatusorder'}};
                   1736:     } else {
                   1737:         if (defined(&domain($udom,'primary'))) {
                   1738:             my $uhome=&domain($udom,'primary');
                   1739:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1740:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1741:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1742:                 return (\%returnhash,\@order);
                   1743:             }
                   1744:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1745:             my @pairs=split(/\&/,$hashitems);
                   1746:             foreach my $item (@pairs) {
                   1747:                 my ($key,$value)=split(/=/,$item,2);
                   1748:                 $key = &unescape($key);
                   1749:                 next if ($key =~ /^error: 2 /);
                   1750:                 $returnhash{$key}=&thaw_unescape($value);
                   1751:             }
                   1752:             my @esc_order = split(/\&/,$orderitems);
                   1753:             foreach my $item (@esc_order) {
                   1754:                 push(@order,&unescape($item));
                   1755:             }
                   1756:         } else {
                   1757:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1758:         }
                   1759:     }
                   1760:     return (\%returnhash,\@order);
                   1761: }
                   1762: 
1.868     raeburn  1763: sub is_domainimage {
                   1764:     my ($url) = @_;
                   1765:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1766:         if (&domain($1) ne '') {
                   1767:             return '1';
                   1768:         }
                   1769:     }
                   1770:     return;
                   1771: }
                   1772: 
1.899     raeburn  1773: sub inst_directory_query {
                   1774:     my ($srch) = @_;
                   1775:     my $udom = $srch->{'srchdomain'};
                   1776:     my %results;
                   1777:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1778:     my $outcome;
1.899     raeburn  1779:     if ($homeserver ne '') {
1.904     albertel 1780: 	my $queryid=&reply("querysend:instdirsearch:".
                   1781: 			   &escape($srch->{'srchby'}).':'.
                   1782: 			   &escape($srch->{'srchterm'}).':'.
                   1783: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1784: 	my $host=&hostname($homeserver);
                   1785: 	if ($queryid !~/^\Q$host\E\_/) {
                   1786: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1787: 	    return;
                   1788: 	}
                   1789: 	my $response = &get_query_reply($queryid);
                   1790: 	my $maxtries = 5;
                   1791: 	my $tries = 1;
                   1792: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1793: 	    $response = &get_query_reply($queryid);
                   1794: 	    $tries ++;
                   1795: 	}
                   1796: 
                   1797:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1798:             if ($response eq 'unavailable') {
                   1799:                 $outcome = $response;
                   1800:             } else {
                   1801:                 $outcome = 'ok';
                   1802:                 my @matches = split(/\n/,$response);
                   1803:                 foreach my $match (@matches) {
                   1804:                     my ($key,$value) = split(/=/,$match);
                   1805:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1806:                 }
1.899     raeburn  1807:             }
                   1808:         }
                   1809:     }
1.909     raeburn  1810:     return ($outcome,%results);
1.899     raeburn  1811: }
                   1812: 
                   1813: sub usersearch {
                   1814:     my ($srch) = @_;
                   1815:     my $dom = $srch->{'srchdomain'};
                   1816:     my %results;
                   1817:     my %libserv = &all_library();
                   1818:     my $query = 'usersearch';
                   1819:     foreach my $tryserver (keys(%libserv)) {
                   1820:         if (&host_domain($tryserver) eq $dom) {
                   1821:             my $host=&hostname($tryserver);
                   1822:             my $queryid=
1.911     raeburn  1823:                 &reply("querysend:".&escape($query).':'.
                   1824:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1825:                        &escape($srch->{'srchtype'}).':'.
                   1826:                        &escape($srch->{'srchterm'}),$tryserver);
                   1827:             if ($queryid !~/^\Q$host\E\_/) {
                   1828:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1829:                 next;
1.899     raeburn  1830:             }
                   1831:             my $reply = &get_query_reply($queryid);
                   1832:             my $maxtries = 1;
                   1833:             my $tries = 1;
                   1834:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1835:                 $reply = &get_query_reply($queryid);
                   1836:                 $tries ++;
                   1837:             }
                   1838:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1839:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1840:             } else {
1.911     raeburn  1841:                 my @matches;
                   1842:                 if ($reply =~ /\n/) {
                   1843:                     @matches = split(/\n/,$reply);
                   1844:                 } else {
                   1845:                     @matches = split(/\&/,$reply);
                   1846:                 }
1.899     raeburn  1847:                 foreach my $match (@matches) {
                   1848:                     my ($uname,$udom,%userhash);
1.911     raeburn  1849:                     foreach my $entry (split(/:/,$match)) {
                   1850:                         my ($key,$value) =
                   1851:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1852:                         $userhash{$key} = $value;
                   1853:                         if ($key eq 'username') {
                   1854:                             $uname = $value;
                   1855:                         } elsif ($key eq 'domain') {
                   1856:                             $udom = $value;
1.911     raeburn  1857:                         }
1.899     raeburn  1858:                     }
                   1859:                     $results{$uname.':'.$udom} = \%userhash;
                   1860:                 }
                   1861:             }
                   1862:         }
                   1863:     }
                   1864:     return %results;
                   1865: }
                   1866: 
1.912     raeburn  1867: sub get_instuser {
                   1868:     my ($udom,$uname,$id) = @_;
                   1869:     my $homeserver = &domain($udom,'primary');
                   1870:     my ($outcome,%results);
                   1871:     if ($homeserver ne '') {
                   1872:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1873:                            &escape($id).':'.&escape($udom),$homeserver);
                   1874:         my $host=&hostname($homeserver);
                   1875:         if ($queryid !~/^\Q$host\E\_/) {
                   1876:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1877:             return;
                   1878:         }
                   1879:         my $response = &get_query_reply($queryid);
                   1880:         my $maxtries = 5;
                   1881:         my $tries = 1;
                   1882:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1883:             $response = &get_query_reply($queryid);
                   1884:             $tries ++;
                   1885:         }
                   1886:         if (!&error($response) && $response ne 'refused') {
                   1887:             if ($response eq 'unavailable') {
                   1888:                 $outcome = $response;
                   1889:             } else {
                   1890:                 $outcome = 'ok';
                   1891:                 my @matches = split(/\n/,$response);
                   1892:                 foreach my $match (@matches) {
                   1893:                     my ($key,$value) = split(/=/,$match);
                   1894:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1895:                 }
                   1896:             }
                   1897:         }
                   1898:     }
                   1899:     my %userinfo;
                   1900:     if (ref($results{$uname}) eq 'HASH') {
                   1901:         %userinfo = %{$results{$uname}};
                   1902:     } 
                   1903:     return ($outcome,%userinfo);
                   1904: }
                   1905: 
                   1906: sub inst_rulecheck {
1.923     raeburn  1907:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1908:     my %returnhash;
                   1909:     if ($udom ne '') {
                   1910:         if (ref($rules) eq 'ARRAY') {
                   1911:             @{$rules} = map {&escape($_);} (@{$rules});
                   1912:             my $rulestr = join(':',@{$rules});
                   1913:             my $homeserver=&domain($udom,'primary');
                   1914:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1915:                 my $response;
                   1916:                 if ($item eq 'username') {                
                   1917:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1918:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1919:                                               $homeserver));
1.923     raeburn  1920:                 } elsif ($item eq 'id') {
                   1921:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1922:                                               ':'.&escape($id).':'.$rulestr,
                   1923:                                               $homeserver));
1.945     raeburn  1924:                 } elsif ($item eq 'selfcreate') {
                   1925:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1926:                                                &escape($udom).':'.&escape($uname).
                   1927:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1928:                 }
1.912     raeburn  1929:                 if ($response ne 'refused') {
                   1930:                     my @pairs=split(/\&/,$response);
                   1931:                     foreach my $item (@pairs) {
                   1932:                         my ($key,$value)=split(/=/,$item,2);
                   1933:                         $key = &unescape($key);
                   1934:                         next if ($key =~ /^error: 2 /);
                   1935:                         $returnhash{$key}=&thaw_unescape($value);
                   1936:                     }
                   1937:                 }
                   1938:             }
                   1939:         }
                   1940:     }
                   1941:     return %returnhash;
                   1942: }
                   1943: 
                   1944: sub inst_userrules {
1.923     raeburn  1945:     my ($udom,$check) = @_;
1.912     raeburn  1946:     my (%ruleshash,@ruleorder);
                   1947:     if ($udom ne '') {
                   1948:         my $homeserver=&domain($udom,'primary');
                   1949:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1950:             my $response;
                   1951:             if ($check eq 'id') {
                   1952:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1953:                                  $homeserver);
1.943     raeburn  1954:             } elsif ($check eq 'email') {
                   1955:                 $response=&reply('instemailrules:'.&escape($udom),
                   1956:                                  $homeserver);
1.923     raeburn  1957:             } else {
                   1958:                 $response=&reply('instuserrules:'.&escape($udom),
                   1959:                                  $homeserver);
                   1960:             }
1.912     raeburn  1961:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1962:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1963:                 ($response ne 'no_such_host')) {
                   1964:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1965:                 my @pairs=split(/\&/,$hashitems);
                   1966:                 foreach my $item (@pairs) {
                   1967:                     my ($key,$value)=split(/=/,$item,2);
                   1968:                     $key = &unescape($key);
                   1969:                     next if ($key =~ /^error: 2 /);
                   1970:                     $ruleshash{$key}=&thaw_unescape($value);
                   1971:                 }
                   1972:                 my @esc_order = split(/\&/,$orderitems);
                   1973:                 foreach my $item (@esc_order) {
                   1974:                     push(@ruleorder,&unescape($item));
                   1975:                 }
                   1976:             }
                   1977:         }
                   1978:     }
                   1979:     return (\%ruleshash,\@ruleorder);
                   1980: }
                   1981: 
1.976     raeburn  1982: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1983: 
                   1984: sub get_domain_defaults {
                   1985:     my ($domain) = @_;
                   1986:     my $cachetime = 60*60*24;
                   1987:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1988:     if (defined($cached)) {
                   1989:         if (ref($result) eq 'HASH') {
                   1990:             return %{$result};
                   1991:         }
                   1992:     }
                   1993:     my %domdefaults;
                   1994:     my %domconfig =
1.989     raeburn  1995:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1996:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1997:                                   'coursedefaults','usersessions',
                   1998:                                   'requestauthor'],$domain);
1.943     raeburn  1999:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2000:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2001:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2002:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2003:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2004:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2005:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2006:     } else {
                   2007:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2008:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2009:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2010:     }
1.976     raeburn  2011:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2012:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2013:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2014:         } else {
                   2015:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2016:         }
1.1172.2.6  raeburn  2017:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2018:         foreach my $item (@usertools) {
                   2019:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2020:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2021:             }
                   2022:         }
1.1172.2.29  raeburn  2023:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2024:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2025:         }
1.976     raeburn  2026:     }
1.985     raeburn  2027:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  2028:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  2029:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2030:         }
                   2031:     }
1.1172.2.9  raeburn  2032:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2033:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2034:     }
1.989     raeburn  2035:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2036:         foreach my $item ('inststatustypes','inststatusorder') {
                   2037:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2038:         }
                   2039:     }
1.1047    raeburn  2040:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2041:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2042:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2043:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2044:         }
1.1172.2.30! raeburn  2045:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
        !          2046:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
        !          2047:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
        !          2048:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
        !          2049:         }
1.1047    raeburn  2050:     }
1.1073    raeburn  2051:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2052:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2053:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2054:         }
                   2055:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2056:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2057:         }
                   2058:     }
1.1172.2.23  raeburn  2059:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2060:     return %domdefaults;
                   2061: }
                   2062: 
1.344     www      2063: # --------------------------------------------------- Assign a key to a student
                   2064: 
                   2065: sub assign_access_key {
1.364     www      2066: #
                   2067: # a valid key looks like uname:udom#comments
                   2068: # comments are being appended
                   2069: #
1.498     www      2070:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2071:     $kdom=
1.620     albertel 2072:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2073:     $knum=
1.620     albertel 2074:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2075:     $cdom=
1.620     albertel 2076:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2077:     $cnum=
1.620     albertel 2078:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2079:     $udom=$env{'user.name'} unless (defined($udom));
                   2080:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2081:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2082:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2083:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2084:                                                   # assigned to this person
                   2085:                                                   # - this should not happen,
1.345     www      2086:                                                   # unless something went wrong
                   2087:                                                   # the first time around
                   2088: # ready to assign
1.364     www      2089:         $logentry=$1.'; '.$logentry;
1.496     www      2090:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2091:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2092: # key now belongs to user
1.346     www      2093: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2094:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2095:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2096:                 return 'ok';
                   2097:             } else {
                   2098:                 return 
                   2099:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2100: 	    }
                   2101:         } else {
                   2102:             return 'error: Could not assign key, try again later.';
                   2103:         }
1.364     www      2104:     } elsif (!$existing{$ckey}) {
1.345     www      2105: # the key does not exist
                   2106: 	return 'error: The key does not exist';
                   2107:     } else {
                   2108: # the key is somebody else's
                   2109: 	return 'error: The key is already in use';
                   2110:     }
1.344     www      2111: }
                   2112: 
1.364     www      2113: # ------------------------------------------ put an additional comment on a key
                   2114: 
                   2115: sub comment_access_key {
                   2116: #
                   2117: # a valid key looks like uname:udom#comments
                   2118: # comments are being appended
                   2119: #
                   2120:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2121:     $cdom=
1.620     albertel 2122:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2123:     $cnum=
1.620     albertel 2124:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2125:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2126:     if ($existing{$ckey}) {
                   2127:         $existing{$ckey}.='; '.$logentry;
                   2128: # ready to assign
1.367     www      2129:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2130:                                                  $cdom,$cnum) eq 'ok') {
                   2131: 	    return 'ok';
                   2132:         } else {
                   2133: 	    return 'error: Count not store comment.';
                   2134:         }
                   2135:     } else {
                   2136: # the key does not exist
                   2137: 	return 'error: The key does not exist';
                   2138:     }
                   2139: }
                   2140: 
1.344     www      2141: # ------------------------------------------------------ Generate a set of keys
                   2142: 
                   2143: sub generate_access_keys {
1.364     www      2144:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      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));
1.361     www      2149:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2150:     unless (($cdom) && ($cnum)) { return 0; }
                   2151:     if ($number>10000) { return 0; }
                   2152:     sleep(2); # make sure don't get same seed twice
                   2153:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2154:     my $total=0;
                   2155:     for (my $i=1;$i<=$number;$i++) {
                   2156:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2157:                   sprintf("%lx",int(100000*rand)).'-'.
                   2158:                   sprintf("%lx",int(100000*rand));
                   2159:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2160:        $newkey=~s/0/h/g; # and also 0 and O
                   2161:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2162:        if ($existing{$newkey}) {
                   2163:            $i--;
                   2164:        } else {
1.364     www      2165: 	  if (&put('accesskeys',
                   2166:               { $newkey => '# generated '.localtime().
1.620     albertel 2167:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2168:                            '; '.$logentry },
                   2169: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2170:               $total++;
                   2171: 	  }
                   2172:        }
                   2173:     }
1.620     albertel 2174:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2175:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2176:     return $total;
                   2177: }
                   2178: 
                   2179: # ------------------------------------------------------- Validate an accesskey
                   2180: 
                   2181: sub validate_access_key {
                   2182:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2183:     $cdom=
1.620     albertel 2184:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2185:     $cnum=
1.620     albertel 2186:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2187:     $udom=$env{'user.domain'} unless (defined($udom));
                   2188:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2189:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2190:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2191: }
                   2192: 
                   2193: # ------------------------------------- Find the section of student in a course
1.652     albertel 2194: sub devalidate_getsection_cache {
                   2195:     my ($udom,$unam,$courseid)=@_;
                   2196:     my $hashid="$udom:$unam:$courseid";
                   2197:     &devalidate_cache_new('getsection',$hashid);
                   2198: }
1.298     matthew  2199: 
1.815     albertel 2200: sub courseid_to_courseurl {
                   2201:     my ($courseid) = @_;
                   2202:     #already url style courseid
                   2203:     return $courseid if ($courseid =~ m{^/});
                   2204: 
                   2205:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2206: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2207: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2208: 	return "/$cdom/$cnum";
                   2209:     }
                   2210: 
                   2211:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2212:     if (exists($courseinfo{'num'})) {
                   2213: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2214:     }
                   2215: 
                   2216:     return undef;
                   2217: }
                   2218: 
1.298     matthew  2219: sub getsection {
                   2220:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2221:     my $cachetime=1800;
1.551     albertel 2222: 
                   2223:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2224:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2225:     if (defined($cached)) { return $result; }
                   2226: 
1.298     matthew  2227:     my %Pending; 
                   2228:     my %Expired;
                   2229:     #
                   2230:     # Each role can either have not started yet (pending), be active, 
                   2231:     #    or have expired.
                   2232:     #
                   2233:     # If there is an active role, we are done.
                   2234:     #
                   2235:     # If there is more than one role which has not started yet, 
                   2236:     #     choose the one which will start sooner
                   2237:     # If there is one role which has not started yet, return it.
                   2238:     #
                   2239:     # If there is more than one expired role, choose the one which ended last.
                   2240:     # If there is a role which has expired, return it.
                   2241:     #
1.815     albertel 2242:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2243:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2244:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2245:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2246:         my $section=$1;
                   2247:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2248:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2249:         my $now=time;
1.548     albertel 2250:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2251:             $Expired{$end}=$section;
                   2252:             next;
                   2253:         }
1.548     albertel 2254:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2255:             $Pending{$start}=$section;
                   2256:             next;
                   2257:         }
1.599     albertel 2258:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2259:     }
                   2260:     #
                   2261:     # Presumedly there will be few matching roles from the above
                   2262:     # loop and the sorting time will be negligible.
                   2263:     if (scalar(keys(%Pending))) {
                   2264:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2265:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2266:     } 
                   2267:     if (scalar(keys(%Expired))) {
                   2268:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2269:         my $time = pop(@sorted);
1.599     albertel 2270:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2271:     }
1.599     albertel 2272:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2273: }
1.70      www      2274: 
1.599     albertel 2275: sub save_cache {
                   2276:     &purge_remembered();
1.722     albertel 2277:     #&Apache::loncommon::validate_page();
1.620     albertel 2278:     undef(%env);
1.780     albertel 2279:     undef($env_loaded);
1.599     albertel 2280: }
1.452     albertel 2281: 
1.599     albertel 2282: my $to_remember=-1;
                   2283: my %remembered;
                   2284: my %accessed;
                   2285: my $kicks=0;
                   2286: my $hits=0;
1.849     albertel 2287: sub make_key {
                   2288:     my ($name,$id) = @_;
1.872     albertel 2289:     if (length($id) > 65 
                   2290: 	&& length(&escape($id)) > 200) {
                   2291: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2292:     }
1.849     albertel 2293:     return &escape($name.':'.$id);
                   2294: }
                   2295: 
1.599     albertel 2296: sub devalidate_cache_new {
                   2297:     my ($name,$id,$debug) = @_;
                   2298:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2299:     $id=&make_key($name,$id);
1.599     albertel 2300:     $memcache->delete($id);
                   2301:     delete($remembered{$id});
                   2302:     delete($accessed{$id});
                   2303: }
                   2304: 
                   2305: sub is_cached_new {
                   2306:     my ($name,$id,$debug) = @_;
1.849     albertel 2307:     $id=&make_key($name,$id);
1.599     albertel 2308:     if (exists($remembered{$id})) {
1.1133    foxr     2309: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2310: 	$accessed{$id}=[&gettimeofday()];
                   2311: 	$hits++;
                   2312: 	return ($remembered{$id},1);
                   2313:     }
                   2314:     my $value = $memcache->get($id);
                   2315:     if (!(defined($value))) {
                   2316: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2317: 	return (undef,undef);
1.416     albertel 2318:     }
1.599     albertel 2319:     if ($value eq '__undef__') {
                   2320: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2321: 	$value=undef;
                   2322:     }
                   2323:     &make_room($id,$value,$debug);
                   2324:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2325:     return ($value,1);
                   2326: }
                   2327: 
                   2328: sub do_cache_new {
                   2329:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2330:     $id=&make_key($name,$id);
1.599     albertel 2331:     my $setvalue=$value;
                   2332:     if (!defined($setvalue)) {
                   2333: 	$setvalue='__undef__';
                   2334:     }
1.623     albertel 2335:     if (!defined($time) ) {
                   2336: 	$time=600;
                   2337:     }
1.599     albertel 2338:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2339:     my $result = $memcache->set($id,$setvalue,$time);
                   2340:     if (! $result) {
1.872     albertel 2341: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2342: 	$memcache->disconnect_all();
1.872     albertel 2343:     }
1.600     albertel 2344:     # need to make a copy of $value
1.919     albertel 2345:     &make_room($id,$value,$debug);
1.599     albertel 2346:     return $value;
                   2347: }
                   2348: 
                   2349: sub make_room {
                   2350:     my ($id,$value,$debug)=@_;
1.919     albertel 2351: 
                   2352:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2353:                                     : $value;
1.599     albertel 2354:     if ($to_remember<0) { return; }
                   2355:     $accessed{$id}=[&gettimeofday()];
                   2356:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2357:     my $to_kick;
                   2358:     my $max_time=0;
                   2359:     foreach my $other (keys(%accessed)) {
                   2360: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2361: 	    $to_kick=$other;
                   2362: 	    $max_time=&tv_interval($accessed{$other});
                   2363: 	}
                   2364:     }
                   2365:     delete($remembered{$to_kick});
                   2366:     delete($accessed{$to_kick});
                   2367:     $kicks++;
                   2368:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2369:     return;
                   2370: }
                   2371: 
1.599     albertel 2372: sub purge_remembered {
1.604     albertel 2373:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2374:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2375:     undef(%remembered);
                   2376:     undef(%accessed);
1.428     albertel 2377: }
1.70      www      2378: # ------------------------------------- Read an entry from a user's environment
                   2379: 
                   2380: sub userenvironment {
                   2381:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2382:     my $items;
                   2383:     foreach my $item (@what) {
                   2384:         $items.=&escape($item).'&';
                   2385:     }
                   2386:     $items=~s/\&$//;
1.70      www      2387:     my %returnhash=();
1.1009    raeburn  2388:     my $uhome = &homeserver($unam,$udom);
                   2389:     unless ($uhome eq 'no_host') {
                   2390:         my @answer=split(/\&/, 
                   2391:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2392:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2393:             return %returnhash;
                   2394:         }
1.1009    raeburn  2395:         my $i;
                   2396:         for ($i=0;$i<=$#what;$i++) {
                   2397: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2398:         }
1.70      www      2399:     }
                   2400:     return %returnhash;
1.1       albertel 2401: }
                   2402: 
1.617     albertel 2403: # ---------------------------------------------------------- Get a studentphoto
                   2404: sub studentphoto {
                   2405:     my ($udom,$unam,$ext) = @_;
                   2406:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2407:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2408:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2409:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2410:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2411:             } else {
                   2412:                 my ($result,$perm_reqd)=
1.707     albertel 2413: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2414:                 if ($result eq 'ok') {
                   2415:                     if (!($perm_reqd eq 'yes')) {
                   2416:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2417:                     }
                   2418:                 }
                   2419:             }
                   2420:         }
                   2421:     } else {
                   2422:         my ($result,$perm_reqd) = 
1.707     albertel 2423: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2424:         if ($result eq 'ok') {
                   2425:             if (!($perm_reqd eq 'yes')) {
                   2426:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2427:             }
                   2428:         }
                   2429:     }
                   2430:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2431: }
                   2432: 
                   2433: sub retrievestudentphoto {
                   2434:     my ($udom,$unam,$ext,$type) = @_;
                   2435:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2436:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2437:     if ($ret eq 'ok') {
                   2438:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2439:         if ($type eq 'thumbnail') {
                   2440:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2441:         }
                   2442:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2443:         return $tokenurl;
                   2444:     } else {
                   2445:         if ($type eq 'thumbnail') {
                   2446:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2447:         } else { 
                   2448:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2449:         }
1.617     albertel 2450:     }
                   2451: }
                   2452: 
1.263     www      2453: # -------------------------------------------------------------------- New chat
                   2454: 
                   2455: sub chatsend {
1.724     raeburn  2456:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2457:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2459:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2460:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2461: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2462: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2463: }
                   2464: 
                   2465: # ------------------------------------------ Find current version of a resource
                   2466: 
                   2467: sub getversion {
                   2468:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2469:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2470:     return &currentversion(&filelocation('',$fname));
                   2471: }
                   2472: 
                   2473: sub currentversion {
                   2474:     my $fname=shift;
                   2475:     my $author=$fname;
                   2476:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2477:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2478:     my $home=&homeserver($uname,$udom);
1.292     www      2479:     if ($home eq 'no_host') { 
                   2480:         return -1; 
                   2481:     }
1.1112    www      2482:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2483:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2484: 	return -1;
                   2485:     }
1.1112    www      2486:     return $answer;
1.263     www      2487: }
                   2488: 
1.1111    www      2489: #
                   2490: # Return special version number of resource if set by override, empty otherwise
                   2491: #
                   2492: sub usedversion {
                   2493:     my $fname=shift;
                   2494:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2495:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2496:     if ($urlversion) { return $urlversion; }
                   2497:     return '';
                   2498: }
                   2499: 
1.1       albertel 2500: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2501: 
1.1       albertel 2502: sub subscribe {
                   2503:     my $fname=shift;
1.761     raeburn  2504:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2505:     $fname=~s/[\n\r]//g;
1.1       albertel 2506:     my $author=$fname;
                   2507:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2508:     my ($udom,$uname)=split(/\//,$author);
                   2509:     my $home=homeserver($uname,$udom);
1.335     albertel 2510:     if ($home eq 'no_host') {
                   2511:         return 'not_found';
1.1       albertel 2512:     }
                   2513:     my $answer=reply("sub:$fname",$home);
1.64      www      2514:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2515: 	$answer.=' by '.$home;
                   2516:     }
1.1       albertel 2517:     return $answer;
                   2518: }
                   2519:     
1.8       www      2520: # -------------------------------------------------------------- Replicate file
                   2521: 
                   2522: sub repcopy {
                   2523:     my $filename=shift;
1.23      www      2524:     $filename=~s/\/+/\//g;
1.1142    raeburn  2525:     my $londocroot = $perlvar{'lonDocRoot'};
                   2526:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2527:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2528:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2529: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2530: 	return &repcopy_userfile($filename);
                   2531:     }
1.532     albertel 2532:     $filename=~s/[\n\r]//g;
1.8       www      2533:     my $transname="$filename.in.transfer";
1.828     www      2534: # FIXME: this should flock
1.607     raeburn  2535:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2536:     my $remoteurl=subscribe($filename);
1.64      www      2537:     if ($remoteurl =~ /^con_lost by/) {
                   2538: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2539:            return 'unavailable';
1.8       www      2540:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2541: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2542: 	   return 'not_found';
1.64      www      2543:     } elsif ($remoteurl =~ /^rejected by/) {
                   2544: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2545:            return 'forbidden';
1.20      www      2546:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2547:            return 'ok';
1.8       www      2548:     } else {
1.290     www      2549:         my $author=$filename;
                   2550:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2551:         my ($udom,$uname)=split(/\//,$author);
                   2552:         my $home=homeserver($uname,$udom);
                   2553:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2554:            my @parts=split(/\//,$filename);
                   2555:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2556:            if ($path ne "$londocroot/res") {
1.8       www      2557:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2558: 	       return 'bad_request';
1.8       www      2559:            }
                   2560:            my $count;
                   2561:            for ($count=5;$count<$#parts;$count++) {
                   2562:                $path.="/$parts[$count]";
                   2563:                if ((-e $path)!=1) {
                   2564: 		   mkdir($path,0777);
                   2565:                }
                   2566:            }
                   2567:            my $ua=new LWP::UserAgent;
                   2568:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2569:            my $response=$ua->request($request,$transname);
                   2570:            if ($response->is_error()) {
                   2571: 	       unlink($transname);
                   2572:                my $message=$response->status_line;
1.672     albertel 2573:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2574:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2575:                return 'unavailable';
1.8       www      2576:            } else {
1.16      www      2577: 	       if ($remoteurl!~/\.meta$/) {
                   2578:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2579:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2580:                   if ($mresponse->is_error()) {
                   2581: 		      unlink($filename.'.meta');
                   2582:                       &logthis(
1.672     albertel 2583:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2584:                   }
                   2585: 	       }
1.8       www      2586:                rename($transname,$filename);
1.607     raeburn  2587:                return 'ok';
1.8       www      2588:            }
1.290     www      2589:        }
1.8       www      2590:     }
1.330     www      2591: }
                   2592: 
                   2593: # ------------------------------------------------ Get server side include body
                   2594: sub ssi_body {
1.381     albertel 2595:     my ($filelink,%form)=@_;
1.606     matthew  2596:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2597:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2598:     }
1.953     www      2599:     my $output='';
                   2600:     my $response;
1.980     raeburn  2601:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2602:        ($output,$response)=&externalssi($filelink);
1.953     www      2603:     } else {
1.1004    droeschl 2604:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2605:        $filelink .= 'inhibitmenu=yes';
1.953     www      2606:        ($output,$response)=&ssi($filelink,%form);
                   2607:     }
1.778     albertel 2608:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2609:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2610:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2611:     if (wantarray) {
                   2612:         return ($output, $response);
                   2613:     } else {
                   2614:         return $output;
                   2615:     }
1.8       www      2616: }
                   2617: 
1.15      www      2618: # --------------------------------------------------------- Server Side Include
                   2619: 
1.782     albertel 2620: sub absolute_url {
                   2621:     my ($host_name) = @_;
                   2622:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2623:     if ($host_name eq '') {
                   2624: 	$host_name = $ENV{'SERVER_NAME'};
                   2625:     }
                   2626:     return $protocol.$host_name;
                   2627: }
                   2628: 
1.942     foxr     2629: #
                   2630: #   Server side include.
                   2631: # Parameters:
                   2632: #  fn     Possibly encrypted resource name/id.
                   2633: #  form   Hash that describes how the rendering should be done
                   2634: #         and other things.
1.944     foxr     2635: # Returns:
1.950     raeburn  2636: #   Scalar context: The content of the response.
                   2637: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2638: #     
1.15      www      2639: sub ssi {
                   2640: 
1.944     foxr     2641:     my ($fn,%form)=@_;
1.15      www      2642:     my $ua=new LWP::UserAgent;
1.23      www      2643:     my $request;
1.711     albertel 2644: 
                   2645:     $form{'no_update_last_known'}=1;
1.895     albertel 2646:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2647:     if (%form) {
1.782     albertel 2648:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2649:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2650:     } else {
1.782     albertel 2651:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2652:     }
                   2653: 
1.15      www      2654:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2655:     my $response= $ua->request($request);
1.944     foxr     2656:     if (wantarray) {
1.1172.2.3  raeburn  2657: 	return ($response->content, $response);
1.944     foxr     2658:     } else {
1.1172.2.3  raeburn  2659: 	return $response->content;
1.942     foxr     2660:     }
1.324     www      2661: }
                   2662: 
                   2663: sub externalssi {
                   2664:     my ($url)=@_;
                   2665:     my $ua=new LWP::UserAgent;
                   2666:     my $request=new HTTP::Request('GET',$url);
                   2667:     my $response=$ua->request($request);
1.954     raeburn  2668:     if (wantarray) {
                   2669:         return ($response->content, $response);
                   2670:     } else {
                   2671:         return $response->content;
                   2672:     }
1.15      www      2673: }
1.254     www      2674: 
1.492     albertel 2675: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2676: 
                   2677: sub allowuploaded {
                   2678:     my ($srcurl,$url)=@_;
                   2679:     $url=&clutter(&declutter($url));
                   2680:     my $dir=$url;
                   2681:     $dir=~s/\/[^\/]+$//;
                   2682:     my %httpref=();
                   2683:     my $httpurl=&hreflocation('',$url);
                   2684:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2685:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2686: }
1.477     raeburn  2687: 
1.1172.2.13  raeburn  2688: #
                   2689: # Determine if the current user should be able to edit a particular resource,
                   2690: # when viewing in course context.
                   2691: # (a) When viewing resource used to determine if "Edit" item is included in
                   2692: #     Functions.
                   2693: # (b) When displaying folder contents in course editor, used to determine if
                   2694: #     "Edit" link will be displayed alongside resource.
                   2695: #
                   2696: #  input: six args -- filename (decluttered), course number, course domain,
                   2697: #                   url, symb (if registered) and group (if this is a group
                   2698: #                   item -- e.g., bulletin board, group page etc.).
                   2699: #  output: array of five scalars --
                   2700: #          $cfile -- url for file editing if editable on current server
                   2701: #          $home -- homeserver of resource (i.e., for author if published,
                   2702: #                                           or course if uploaded.).
                   2703: #          $switchserver --  1 if server switch will be needed.
                   2704: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2705: #          $forceview -- 1 if icon/link should be to go to view mode
                   2706: #
                   2707: 
                   2708: sub can_edit_resource {
                   2709:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2710:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2711: #
                   2712: # For aboutme pages user can only edit his/her own.
                   2713: #
                   2714:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2715:         my ($sdom,$sname) = ($1,$2);
                   2716:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2717:             $home = $env{'user.home'};
                   2718:             $cfile = $resurl;
                   2719:             if ($env{'form.forceedit'}) {
                   2720:                 $forceview = 1;
                   2721:             } else {
                   2722:                 $forceedit = 1;
                   2723:             }
                   2724:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2725:         } else {
                   2726:             return;
                   2727:         }
                   2728:     }
                   2729: 
                   2730:     if ($env{'request.course.id'}) {
                   2731:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2732:         if ($group ne '') {
                   2733: # if this is a group homepage or group bulletin board, check group privs
                   2734:             my $allowed = 0;
                   2735:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2736:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2737:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2738:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2739:                     $allowed = 1;
                   2740:                 }
                   2741:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2742:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2743:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2744:                     $allowed = 1;
                   2745:                 }
                   2746:             }
                   2747:             if ($allowed) {
                   2748:                 $home=&homeserver($cnum,$cdom);
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } else {
                   2756:                 return;
                   2757:             }
                   2758:         } else {
1.1172.2.15  raeburn  2759:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2760:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2761:                     return;
                   2762:                 }
                   2763:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2764: #
                   2765: # No edit allowed where CC has switched to student role.
                   2766: #
                   2767:                 return;
                   2768:             }
                   2769:         }
                   2770:     }
                   2771: 
                   2772:     if ($file ne '') {
                   2773:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2774:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2775:                 $uploaded = 1;
                   2776:                 $incourse = 1;
                   2777:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2778:                     $cfile = &hreflocation('',$file);
                   2779:                     if ($env{'form.forceedit'}) {
                   2780:                         $forceview = 1;
                   2781:                     } else {
                   2782:                         $forceedit = 1;
                   2783:                     }
                   2784:                 }
                   2785:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2786:                 $incourse = 1;
                   2787:                 if ($env{'form.forceedit'}) {
                   2788:                     $forceview = 1;
                   2789:                 } else {
                   2790:                     $forceedit = 1;
                   2791:                 }
                   2792:                 $cfile = $resurl;
                   2793:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2794:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2795:                     $incourse = 1;
                   2796:                     if ($env{'form.forceedit'}) {
                   2797:                         $forceview = 1;
                   2798:                     } else {
                   2799:                         $forceedit = 1;
                   2800:                     }
                   2801:                     $cfile = $resurl;
                   2802:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2803:                     $incourse = 1;
                   2804:                     $cfile = $resurl.'/smpedit';
                   2805:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2806:                     $incourse = 1;
                   2807:                     if ($env{'form.forceedit'}) {
                   2808:                         $forceview = 1;
                   2809:                     } else {
                   2810:                         $forceedit = 1;
                   2811:                     }
                   2812:                     $cfile = $resurl;
1.1172.2.15  raeburn  2813:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2814:                     $incourse = 1;
                   2815:                     if ($env{'form.forceedit'}) {
                   2816:                         $forceview = 1;
                   2817:                     } else {
                   2818:                         $forceedit = 1;
                   2819:                     }
                   2820:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2821:                 }
                   2822:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2823:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2824:                 if (&is_on_map($template)) {
                   2825:                     $incourse = 1;
                   2826:                     $forceview = 1;
                   2827:                     $cfile = $template;
                   2828:                 }
                   2829:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2830:                     $incourse = 1;
                   2831:                     if ($env{'form.forceedit'}) {
                   2832:                         $forceview = 1;
                   2833:                     } else {
                   2834:                         $forceedit = 1;
                   2835:                     }
                   2836:                     $cfile = $resurl;
                   2837:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2838:                 $incourse = 1;
                   2839:                 $forceview = 1;
                   2840:                 if ($symb) {
                   2841:                     my ($map,$id,$res)=&decode_symb($symb);
                   2842:                     $env{'request.symb'} = $symb;
                   2843:                     $cfile = &clutter($res);
                   2844:                 } else {
                   2845:                     $cfile = $env{'form.suppurl'};
                   2846:                     $cfile =~ s{^http://}{};
                   2847:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2848:                 }
                   2849:             }
                   2850:         }
                   2851:         if ($uploaded || $incourse) {
                   2852:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2853:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2854:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2855:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2856:             # Check that the user has permission to edit this resource
                   2857:             my $setpriv = 1;
                   2858:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2859:             if (defined($cfudom)) {
                   2860:                 $home=&homeserver($cfuname,$cfudom);
                   2861:                 $cfile=$file;
                   2862:             }
                   2863:         }
                   2864:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2865:             (($home ne '') && ($home ne 'no_host'))) {
                   2866:             my @ids=&current_machine_ids();
                   2867:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2868:                 $switchserver=1;
                   2869:             }
                   2870:         }
                   2871:     }
                   2872:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2873: }
                   2874: 
                   2875: sub is_course_upload {
                   2876:     my ($file,$cnum,$cdom) = @_;
                   2877:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2878:     $uploadpath =~ s{^\/}{};
                   2879:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2880:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2881:         return 1;
                   2882:     }
                   2883:     return;
                   2884: }
                   2885: 
                   2886: sub in_course {
                   2887:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2888:     if ($hideprivileged) {
                   2889:         my $skipuser;
1.1172.2.23  raeburn  2890:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2891:         my @possdoms = ($cdom);
                   2892:         if ($coursehash{'checkforpriv'}) {
                   2893:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2894:         }
                   2895:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2896:             $skipuser = 1;
                   2897:             if ($coursehash{'nothideprivileged'}) {
                   2898:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2899:                     my $user;
                   2900:                     if ($item =~ /:/) {
                   2901:                         $user = $item;
                   2902:                     } else {
                   2903:                         $user = join(':',split(/[\@]/,$item));
                   2904:                     }
                   2905:                     if ($user eq $uname.':'.$udom) {
                   2906:                         undef($skipuser);
                   2907:                         last;
                   2908:                     }
                   2909:                 }
                   2910:             }
                   2911:             if ($skipuser) {
                   2912:                 return 0;
                   2913:             }
                   2914:         }
                   2915:     }
                   2916:     $type ||= 'any';
                   2917:     if (!defined($cdom) || !defined($cnum)) {
                   2918:         my $cid  = $env{'request.course.id'};
                   2919:         $cdom = $env{'course.'.$cid.'.domain'};
                   2920:         $cnum = $env{'course.'.$cid.'.num'};
                   2921:     }
                   2922:     my $typesref;
                   2923:     if (($type eq 'any') || ($type eq 'all')) {
                   2924:         $typesref = ['active','previous','future'];
                   2925:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2926:         $typesref = [$type];
                   2927:     }
                   2928:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2929:                               $typesref,undef,[$cdom]);
                   2930:     my ($tmp) = keys(%roles);
                   2931:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2932:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2933:     if (@course_roles > 0) {
                   2934:         return 1;
                   2935:     }
                   2936:     return 0;
                   2937: }
                   2938: 
1.478     albertel 2939: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2940: # input: action, courseID, current domain, intended
1.637     raeburn  2941: #        path to file, source of file, instruction to parse file for objects,
                   2942: #        ref to hash for embedded objects,
                   2943: #        ref to hash for codebase of java objects.
1.1095    raeburn  2944: #        reference to scalar to accommodate mime type determined
                   2945: #          from File::MMagic if $parser = parse.
1.637     raeburn  2946: #
1.485     raeburn  2947: # output: url to file (if action was uploaddoc), 
                   2948: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2949: #
1.478     albertel 2950: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2951: # course.
1.477     raeburn  2952: #
1.478     albertel 2953: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2954: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2955: #          course's home server.
1.477     raeburn  2956: #
1.478     albertel 2957: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2958: #          be copied from $source (current location) to 
                   2959: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2960: #         and will then be copied to
                   2961: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2962: #         course's home server.
1.485     raeburn  2963: #
1.481     raeburn  2964: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2965: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2966: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2967: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2968: #         in course's home server.
1.637     raeburn  2969: #
1.477     raeburn  2970: 
                   2971: sub process_coursefile {
1.1095    raeburn  2972:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2973:         $mimetype)=@_;
1.477     raeburn  2974:     my $fetchresult;
1.638     albertel 2975:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2976:     if ($action eq 'propagate') {
1.638     albertel 2977:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2978: 			     $home);
1.481     raeburn  2979:     } else {
1.477     raeburn  2980:         my $fpath = '';
                   2981:         my $fname = $file;
1.478     albertel 2982:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2983:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2984:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2985:         if ($action eq 'copy') {
                   2986:             if ($source eq '') {
                   2987:                 $fetchresult = 'no source file';
                   2988:                 return $fetchresult;
                   2989:             } else {
                   2990:                 my $destination = $filepath.'/'.$fname;
                   2991:                 rename($source,$destination);
                   2992:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2993:                                  $home);
1.481     raeburn  2994:             }
                   2995:         } elsif ($action eq 'uploaddoc') {
                   2996:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2997:             print $fh $env{'form.'.$source};
1.481     raeburn  2998:             close($fh);
1.637     raeburn  2999:             if ($parser eq 'parse') {
1.1024    raeburn  3000:                 my $mm = new File::MMagic;
1.1095    raeburn  3001:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3002:                 if ($type eq 'text/html') {
1.1024    raeburn  3003:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3004:                     unless ($parse_result eq 'ok') {
                   3005:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3006:                     }
1.637     raeburn  3007:                 }
1.1095    raeburn  3008:                 if (ref($mimetype)) {
                   3009:                     $$mimetype = $type;
                   3010:                 } 
1.637     raeburn  3011:             }
1.477     raeburn  3012:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3013:                                  $home);
1.481     raeburn  3014:             if ($fetchresult eq 'ok') {
                   3015:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3016:             } else {
                   3017:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3018:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3019:                 return '/adm/notfound.html';
                   3020:             }
1.477     raeburn  3021:         }
                   3022:     }
1.485     raeburn  3023:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3024:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3025:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3026:     }
                   3027:     return $fetchresult;
                   3028: }
                   3029: 
1.637     raeburn  3030: sub build_filepath {
                   3031:     my ($fpath) = @_;
                   3032:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3033:     unless ($fpath eq '') {
                   3034:         my @parts=split('/',$fpath);
                   3035:         foreach my $part (@parts) {
                   3036:             $filepath.= '/'.$part;
                   3037:             if ((-e $filepath)!=1) {
                   3038:                 mkdir($filepath,0777);
                   3039:             }
                   3040:         }
                   3041:     }
                   3042:     return $filepath;
                   3043: }
                   3044: 
                   3045: sub store_edited_file {
1.638     albertel 3046:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3047:     my $file = $primary_url;
                   3048:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3049:     my $fpath = '';
                   3050:     my $fname = $file;
                   3051:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3052:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3053:     my $filepath = &build_filepath($fpath);
                   3054:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3055:     print $fh $content;
                   3056:     close($fh);
1.638     albertel 3057:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3058:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3059: 			  $home);
1.637     raeburn  3060:     if ($$fetchresult eq 'ok') {
                   3061:         return '/uploaded/'.$fpath.'/'.$fname;
                   3062:     } else {
1.638     albertel 3063:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3064: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3065:         return '/adm/notfound.html';
                   3066:     }
                   3067: }
                   3068: 
1.531     albertel 3069: sub clean_filename {
1.831     albertel 3070:     my ($fname,$args)=@_;
1.315     www      3071: # Replace Windows backslashes by forward slashes
1.257     www      3072:     $fname=~s/\\/\//g;
1.831     albertel 3073:     if (!$args->{'keep_path'}) {
                   3074:         # Get rid of everything but the actual filename
                   3075: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3076:     }
1.315     www      3077: # Replace spaces by underscores
                   3078:     $fname=~s/\s+/\_/g;
                   3079: # Replace all other weird characters by nothing
1.831     albertel 3080:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3081: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3082: # numbers
                   3083:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3084:     return $fname;
                   3085: }
1.1051    raeburn  3086: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3087: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3088: # image with the same aspect ratio as the original, but with dimensions which do 
                   3089: # not exceed $resizewidth and $resizeheight.
                   3090:  
1.984     neumanie 3091: sub resizeImage {
1.1051    raeburn  3092:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3093:     my $ima = Image::Magick->new;
                   3094:     my $resized;
                   3095:     if (-e $img_path) {
                   3096:         $ima->Read($img_path);
                   3097:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3098:             my $width = $ima->Get('width');
                   3099:             my $height = $ima->Get('height');
                   3100:             if ($width > $resizewidth) {
                   3101: 	        my $factor = $width/$resizewidth;
                   3102:                 my $newheight = $height/$factor;
                   3103:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3104:                 $resized = 1;
                   3105:             }
                   3106:         }
                   3107:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3108:             my $width = $ima->Get('width');
                   3109:             my $height = $ima->Get('height');
                   3110:             if ($height > $resizeheight) {
                   3111:                 my $factor = $height/$resizeheight;
                   3112:                 my $newwidth = $width/$factor;
                   3113:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3114:                 $resized = 1;
                   3115:             }
                   3116:         }
                   3117:         if ($resized) {
                   3118:             $ima->Write($img_path);
                   3119:         }
                   3120:     }
                   3121:     return;
1.977     amueller 3122: }
                   3123: 
1.608     albertel 3124: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3125: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3126: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3127: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3128: #                                    canceloverwrite, or ''. 
                   3129: #                   if 'coursedoc': upload to the current course
                   3130: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3131: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3132: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3133: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3134: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3135: #        $allfiles - reference to hash for embedded objects
                   3136: #        $codebase - reference to hash for codebase of java objects
                   3137: #        $desuname - username for permanent storage of uploaded file
                   3138: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3139: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3140: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3141: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3142: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3143: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3144: #                    from File::MMagic.
1.858     raeburn  3145: # 
1.686     albertel 3146: # output: url of file in userspace, or error: <message> 
                   3147: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3148: 
1.531     albertel 3149: sub userfileupload {
1.1090    raeburn  3150:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3151:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3152:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3153:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3154:     $fname=&clean_filename($fname);
1.1090    raeburn  3155:     # See if there is anything left
1.257     www      3156:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3157:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3158:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3159:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3160:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3161:         my $now = time;
1.1090    raeburn  3162:         my $filepath;
1.1095    raeburn  3163:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3164:              $filepath = 'tmp/helprequests/'.$now;
                   3165:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3166:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3167:                          '_'.$env{'user.domain'}.'/pending';
                   3168:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3169:             my ($docuname,$docudom);
                   3170:             if ($destudom) {
                   3171:                 $docudom = $destudom;
                   3172:             } else {
                   3173:                 $docudom = $env{'user.domain'};
                   3174:             }
                   3175:             if ($destuname) {
                   3176:                 $docuname = $destuname;
                   3177:             } else {
                   3178:                 $docuname = $env{'user.name'};
                   3179:             }
                   3180:             if (exists($env{'form.group'})) {
                   3181:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3182:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3183:             }
                   3184:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3185:             if ($context eq 'canceloverwrite') {
                   3186:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3187:                 if (-e  $tempfile) {
                   3188:                     my @info = stat($tempfile);
                   3189:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3190:                         unlink($tempfile);
                   3191:                     }
                   3192:                 }
                   3193:                 return;
1.523     raeburn  3194:             }
                   3195:         }
1.1090    raeburn  3196:         # Create the directory if not present
1.741     raeburn  3197:         my @parts=split(/\//,$filepath);
                   3198:         my $fullpath = $perlvar{'lonDaemons'};
                   3199:         for (my $i=0;$i<@parts;$i++) {
                   3200:             $fullpath .= '/'.$parts[$i];
                   3201:             if ((-e $fullpath)!=1) {
                   3202:                 mkdir($fullpath,0777);
                   3203:             }
                   3204:         }
                   3205:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3206:         print $fh $env{'form.'.$formname};
                   3207:         close($fh);
1.1090    raeburn  3208:         if ($context eq 'existingfile') {
                   3209:             my @info = stat($fullpath.'/'.$fname);
                   3210:             return ($fullpath.'/'.$fname,$info[9]);
                   3211:         } else {
                   3212:             return $fullpath.'/'.$fname;
                   3213:         }
1.523     raeburn  3214:     }
1.995     raeburn  3215:     if ($subdir eq 'scantron') {
                   3216:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3217:     } else {
1.995     raeburn  3218:         $fname="$subdir/$fname";
                   3219:     }
1.1090    raeburn  3220:     if ($context eq 'coursedoc') {
1.638     albertel 3221: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3222: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3223:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3224:             return &finishuserfileupload($docuname,$docudom,
                   3225: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3226: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3227:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3228:         } else {
1.1172.2.21  raeburn  3229:             if ($env{'form.folder'}) {
                   3230:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3231:             }
1.638     albertel 3232:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3233: 				       $fname,$formname,$parser,
1.1095    raeburn  3234: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3235:         }
1.719     banghart 3236:     } elsif (defined($destuname)) {
                   3237:         my $docuname=$destuname;
                   3238:         my $docudom=$destudom;
1.860     raeburn  3239: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3240: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3241:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3242:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3243:     } else {
1.638     albertel 3244:         my $docuname=$env{'user.name'};
                   3245:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3246:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3247:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3248:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3249:         }
1.860     raeburn  3250: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3251: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3252:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3253:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3254:     }
1.271     www      3255: }
                   3256: 
                   3257: sub finishuserfileupload {
1.860     raeburn  3258:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3259:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3260:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3261:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3262:   
1.860     raeburn  3263:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3264:     $file=$fname;
                   3265:     if ($fname=~m|/|) {
                   3266:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3267: 	$path.=$fnamepath.'/';
                   3268:     }
1.259     www      3269:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3270:     my $count;
                   3271:     for ($count=4;$count<=$#parts;$count++) {
                   3272:         $filepath.="/$parts[$count]";
                   3273:         if ((-e $filepath)!=1) {
                   3274: 	    mkdir($filepath,0777);
                   3275:         }
                   3276:     }
1.984     neumanie 3277: 
1.258     www      3278: # Save the file
                   3279:     {
1.701     albertel 3280: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3281: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3282: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3283: 	    return '/adm/notfound.html';
                   3284: 	}
1.1090    raeburn  3285:         if ($context eq 'overwrite') {
1.1117    foxr     3286:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3287:             my $target = $filepath.'/'.$file;
                   3288:             if (-e $source) {
                   3289:                 my @info = stat($source);
                   3290:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3291:                     unless (&File::Copy::move($source,$target)) {
                   3292:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3293:                         return "Moving from $source failed";
                   3294:                     }
                   3295:                 } else {
                   3296:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3297:                 }
                   3298:             } else {
                   3299:                 return "Temporary file: $source missing";
                   3300:             }
                   3301:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3302: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3303: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3304: 	    return '/adm/notfound.html';
                   3305: 	}
1.570     albertel 3306: 	close(FH);
1.1051    raeburn  3307:         if ($resizewidth && $resizeheight) {
                   3308:             my $mm = new File::MMagic;
                   3309:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3310:             if ($mime_type =~ m{^image/}) {
                   3311: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3312:             }  
1.977     amueller 3313: 	}
1.258     www      3314:     }
1.1152    raeburn  3315:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3316:         if (ref($mimetype)) {
                   3317:             if ($$mimetype eq '') {
                   3318:                 my $mm = new File::MMagic;
                   3319:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3320:                 $$mimetype = $type;
                   3321:             }
                   3322:         }
                   3323:     }
1.637     raeburn  3324:     if ($parser eq 'parse') {
1.1152    raeburn  3325:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3326:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3327:                                                        $allfiles,$codebase);
                   3328:             unless ($parse_result eq 'ok') {
                   3329:                 &logthis('Failed to parse '.$filepath.$file.
                   3330: 	   	         ' for embedded media: '.$parse_result); 
                   3331:             }
1.637     raeburn  3332:         }
                   3333:     }
1.860     raeburn  3334:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3335:         my $input = $filepath.'/'.$file;
                   3336:         my $output = $filepath.'/'.'tn-'.$file;
                   3337:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3338:         system("convert -sample $thumbsize $input $output");
                   3339:         if (-e $filepath.'/'.'tn-'.$file) {
                   3340:             $fetchthumb  = 1; 
                   3341:         }
                   3342:     }
1.858     raeburn  3343:  
1.259     www      3344: # Notify homeserver to grep it
                   3345: #
1.984     neumanie 3346:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3347:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3348:     if ($fetchresult eq 'ok') {
1.860     raeburn  3349:         if ($fetchthumb) {
                   3350:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3351:             if ($thumbresult ne 'ok') {
                   3352:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3353:                          $docuhome.': '.$thumbresult);
                   3354:             }
                   3355:         }
1.259     www      3356: #
1.258     www      3357: # Return the URL to it
1.494     albertel 3358:         return '/uploaded/'.$path.$file;
1.263     www      3359:     } else {
1.494     albertel 3360:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3361: 		 ': '.$fetchresult);
1.263     www      3362:         return '/adm/notfound.html';
1.858     raeburn  3363:     }
1.493     albertel 3364: }
                   3365: 
1.637     raeburn  3366: sub extract_embedded_items {
1.961     raeburn  3367:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3368:     my @state = ();
1.1164    raeburn  3369:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3370:     my %javafiles = (
                   3371:                       codebase => '',
                   3372:                       code => '',
                   3373:                       archive => ''
                   3374:                     );
                   3375:     my %mediafiles = (
                   3376:                       src => '',
                   3377:                       movie => '',
                   3378:                      );
1.648     raeburn  3379:     my $p;
                   3380:     if ($content) {
                   3381:         $p = HTML::LCParser->new($content);
                   3382:     } else {
1.961     raeburn  3383:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3384:     }
1.641     albertel 3385:     while (my $t=$p->get_token()) {
1.640     albertel 3386: 	if ($t->[0] eq 'S') {
                   3387: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3388: 	    push(@state, $tagname);
1.648     raeburn  3389:             if (lc($tagname) eq 'allow') {
                   3390:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3391:             }
1.640     albertel 3392: 	    if (lc($tagname) eq 'img') {
                   3393: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3394: 	    }
1.886     albertel 3395: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3396:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3397: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3398:                 }
1.886     albertel 3399: 	    }
1.645     raeburn  3400:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3401:                 my $src;
1.645     raeburn  3402:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3403:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3404:                 } else {
1.1164    raeburn  3405:                     if ($attr->{'src'} ne '') {
                   3406:                         $src = $attr->{'src'};
                   3407:                         &add_filetype($allfiles,$src,'src');
                   3408:                     }
                   3409:                 }
                   3410:                 my $text = $p->get_trimmed_text();
                   3411:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3412:                     my @swfargs = split(/,/,$1);
                   3413:                     foreach my $item (@swfargs) {
                   3414:                         $item =~ s/["']//g;
                   3415:                         $item =~ s/^\s+//;
                   3416:                         $item =~ s/\s+$//;
                   3417:                     }
                   3418:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3419:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3420:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3421:                         } else {
                   3422:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3423:                         }
                   3424:                     }
1.645     raeburn  3425:                 }
                   3426:             }
                   3427:             if (lc($tagname) eq 'link') {
                   3428:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3429:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3430:                 }
                   3431:             }
1.640     albertel 3432: 	    if (lc($tagname) eq 'object' ||
                   3433: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3434: 		foreach my $item (keys(%javafiles)) {
                   3435: 		    $javafiles{$item} = '';
                   3436: 		}
1.1164    raeburn  3437:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3438:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3439:                 }
1.640     albertel 3440: 	    }
                   3441: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3442: 		my $name = lc($attr->{'name'});
                   3443: 		foreach my $item (keys(%javafiles)) {
                   3444: 		    if ($name eq $item) {
                   3445: 			$javafiles{$item} = $attr->{'value'};
                   3446: 			last;
                   3447: 		    }
                   3448: 		}
1.1164    raeburn  3449:                 my $pathfrom;
1.640     albertel 3450: 		foreach my $item (keys(%mediafiles)) {
                   3451: 		    if ($name eq $item) {
1.1164    raeburn  3452:                         $pathfrom = $attr->{'value'};
                   3453:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3454: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3455: 			last;
                   3456: 		    }
                   3457: 		}
1.1164    raeburn  3458:                 if ($name eq 'flashvars') {
                   3459:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3460:                 }
                   3461:                 if ($pathfrom ne '') {
                   3462:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3463:                                          $pathfrom);
                   3464:                 }
1.640     albertel 3465: 	    }
                   3466: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3467: 		foreach my $item (keys(%javafiles)) {
                   3468: 		    if ($attr->{$item}) {
                   3469: 			$javafiles{$item} = $attr->{$item};
                   3470: 			last;
                   3471: 		    }
                   3472: 		}
                   3473: 		foreach my $item (keys(%mediafiles)) {
                   3474: 		    if ($attr->{$item}) {
                   3475: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3476: 			last;
                   3477: 		    }
                   3478: 		}
1.1164    raeburn  3479:                 if (lc($tagname) eq 'embed') {
                   3480:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3481:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3482:                                              $attr->{'src'});
                   3483:                     }
                   3484:                 }
1.640     albertel 3485: 	    }
1.1164    raeburn  3486:             if ($t->[4] =~ m{/>$}) {
                   3487:                 pop(@state);  
                   3488:             }
1.640     albertel 3489: 	} elsif ($t->[0] eq 'E') {
                   3490: 	    my ($tagname) = ($t->[1]);
                   3491: 	    if ($javafiles{'codebase'} ne '') {
                   3492: 		$javafiles{'codebase'} .= '/';
                   3493: 	    }  
                   3494: 	    if (lc($tagname) eq 'applet' ||
                   3495: 		lc($tagname) eq 'object' ||
                   3496: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3497: 		) {
                   3498: 		foreach my $item (keys(%javafiles)) {
                   3499: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3500: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3501: 			&add_filetype($allfiles,$file,$item);
                   3502: 		    }
                   3503: 		}
                   3504: 	    } 
                   3505: 	    pop @state;
                   3506: 	}
                   3507:     }
1.1164    raeburn  3508:     foreach my $id (sort(keys(%flashvars))) {
                   3509:         if ($shockwave{$id} ne '') {
                   3510:             my @pairs = split(/\&/,$flashvars{$id});
                   3511:             foreach my $pair (@pairs) {
                   3512:                 my ($key,$value) = split(/\=/,$pair);
                   3513:                 if ($key eq 'thumb') {
                   3514:                     &add_filetype($allfiles,$value,$key);
                   3515:                 } elsif ($key eq 'content') {
                   3516:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3517:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3518:                     if ($ext ne '') {
                   3519:                         &add_filetype($allfiles,$path.$value,$ext);
                   3520:                     }
                   3521:                 }
                   3522:             }
                   3523:         }
                   3524:     }
1.637     raeburn  3525:     return 'ok';
                   3526: }
                   3527: 
1.639     albertel 3528: sub add_filetype {
                   3529:     my ($allfiles,$file,$type)=@_;
                   3530:     if (exists($allfiles->{$file})) {
                   3531: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3532: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3533: 	}
                   3534:     } else {
                   3535: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3536:     }
                   3537: }
                   3538: 
1.1164    raeburn  3539: sub embedded_dependency {
                   3540:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3541:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3542:         if (($identifier ne '') &&
                   3543:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3544:             ($pathfrom ne '')) {
                   3545:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3546:             foreach my $dep (@{$related->{$identifier}}) {
                   3547:                 &add_filetype($allfiles,$path.$dep,'object');
                   3548:             }
                   3549:         }
                   3550:     }
                   3551:     return;
                   3552: }
                   3553: 
1.493     albertel 3554: sub removeuploadedurl {
1.984     neumanie 3555:     my ($url)=@_;	
                   3556:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3557:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3558: }
                   3559: 
                   3560: sub removeuserfile {
                   3561:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3562:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3563:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3564:     if ($result eq 'ok') {	
1.798     raeburn  3565:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3566:             my $metafile = $fname.'.meta';
                   3567:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3568: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3569:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3570:             my $sqlresult = 
1.823     albertel 3571:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3572:                                         'portfolio_metadata',$group,
                   3573:                                         'delete');
1.798     raeburn  3574:         }
                   3575:     }
                   3576:     return $result;
1.257     www      3577: }
1.15      www      3578: 
1.530     albertel 3579: sub mkdiruserfile {
                   3580:     my ($docuname,$docudom,$dir)=@_;
                   3581:     my $home=&homeserver($docuname,$docudom);
                   3582:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3583: }
                   3584: 
1.531     albertel 3585: sub renameuserfile {
                   3586:     my ($docuname,$docudom,$old,$new)=@_;
                   3587:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3588:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3589:                         &escape("$old").':'.&escape("$new"),$home);
                   3590:     if ($result eq 'ok') {
                   3591:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3592:             my $oldmeta = $old.'.meta';
                   3593:             my $newmeta = $new.'.meta';
                   3594:             my $metaresult = 
                   3595:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3596: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3597:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3598:             my $sqlresult = 
1.823     albertel 3599:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3600:                                         'portfolio_metadata',$group,
                   3601:                                         'delete');
1.798     raeburn  3602:         }
                   3603:     }
                   3604:     return $result;
1.531     albertel 3605: }
                   3606: 
1.14      www      3607: # ------------------------------------------------------------------------- Log
                   3608: 
                   3609: sub log {
                   3610:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3611:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3612: }
                   3613: 
                   3614: # ------------------------------------------------------------------ Course Log
1.352     www      3615: #
                   3616: # This routine flushes several buffers of non-mission-critical nature
                   3617: #
1.157     www      3618: 
                   3619: sub flushcourselogs {
1.352     www      3620:     &logthis('Flushing log buffers');
                   3621: #
                   3622: # course logs
                   3623: # This is a log of all transactions in a course, which can be used
                   3624: # for data mining purposes
                   3625: #
                   3626: # It also collects the courseid database, which lists last transaction
                   3627: # times and course titles for all courseids
                   3628: #
                   3629:     my %courseidbuffer=();
1.921     raeburn  3630:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3631:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3632: 		          &escape($courselogs{$crsid}),
                   3633: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3634: 	    delete $courselogs{$crsid};
                   3635:         } else {
                   3636:             &logthis('Failed to flush log buffer for '.$crsid);
                   3637:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3638:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3639:                         " exceeded maximum size, deleting.</font>");
                   3640:                delete $courselogs{$crsid};
                   3641:             }
1.352     www      3642:         }
1.920     raeburn  3643:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3644:             'description' => $coursedescrbuf{$crsid},
                   3645:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3646:             'type'        => $coursetypebuf{$crsid},
                   3647:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3648:         };
1.191     harris41 3649:     }
1.352     www      3650: #
                   3651: # Write course id database (reverse lookup) to homeserver of courses 
                   3652: # Is used in pickcourse
                   3653: #
1.840     albertel 3654:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3655:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3656:                                     $courseidbuffer{$crs_home},
                   3657:                                     $crs_home,'timeonly');
1.352     www      3658:     }
                   3659: #
                   3660: # File accesses
                   3661: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3662: #
1.449     matthew  3663:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3664:         if ($entry =~ /___count$/) {
                   3665:             my ($dom,$name);
1.807     albertel 3666:             ($dom,$name,undef)=
1.811     albertel 3667: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3668:             if (! defined($dom) || $dom eq '' || 
                   3669:                 ! defined($name) || $name eq '') {
1.620     albertel 3670:                 my $cid = $env{'request.course.id'};
                   3671:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3672:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3673:             }
1.450     matthew  3674:             my $value = $accesshash{$entry};
                   3675:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3676:             my %temphash=($url => $value);
1.449     matthew  3677:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3678:             if ($result eq 'ok') {
                   3679:                 delete $accesshash{$entry};
                   3680:             }
                   3681:         } else {
1.811     albertel 3682:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3683:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3684:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3685:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3686:                 delete $accesshash{$entry};
                   3687:             }
1.185     www      3688:         }
1.191     harris41 3689:     }
1.352     www      3690: #
                   3691: # Roles
                   3692: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3693: #
1.800     albertel 3694:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3695:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3696: 	    split(/\:/,$entry);
                   3697:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3698:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3699:                 $rudom,$runame) eq 'ok') {
                   3700: 	    delete $userrolehash{$entry};
                   3701:         }
                   3702:     }
1.662     raeburn  3703: #
                   3704: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3705: #
                   3706:     my %domrolebuffer = ();
1.1000    raeburn  3707:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3708:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3709:         if ($domrolebuffer{$rudom}) {
                   3710:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3711:                       '='.&escape($domainrolehash{$entry});
                   3712:         } else {
                   3713:             $domrolebuffer{$rudom}.=&escape($entry).
                   3714:                       '='.&escape($domainrolehash{$entry});
                   3715:         }
                   3716:         delete $domainrolehash{$entry};
                   3717:     }
                   3718:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3719: 	my %servers = &get_servers($dom,'library');
                   3720: 	foreach my $tryserver (keys(%servers)) {
                   3721: 	    unless (&reply('domroleput:'.$dom.':'.
                   3722: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3723: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3724: 	    }
1.662     raeburn  3725:         }
                   3726:     }
1.186     www      3727:     $dumpcount++;
1.157     www      3728: }
                   3729: 
                   3730: sub courselog {
                   3731:     my $what=shift;
1.158     www      3732:     $what=time.':'.$what;
1.620     albertel 3733:     unless ($env{'request.course.id'}) { return ''; }
                   3734:     $coursedombuf{$env{'request.course.id'}}=
                   3735:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3736:     $coursenumbuf{$env{'request.course.id'}}=
                   3737:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3738:     $coursehombuf{$env{'request.course.id'}}=
                   3739:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3740:     $coursedescrbuf{$env{'request.course.id'}}=
                   3741:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3742:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3743:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3744:     $courseownerbuf{$env{'request.course.id'}}=
                   3745:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3746:     $coursetypebuf{$env{'request.course.id'}}=
                   3747:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3748:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3749: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3750:     } else {
1.620     albertel 3751: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3752:     }
1.620     albertel 3753:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3754: 	&flushcourselogs();
                   3755:     }
1.158     www      3756: }
                   3757: 
                   3758: sub courseacclog {
                   3759:     my $fnsymb=shift;
1.620     albertel 3760:     unless ($env{'request.course.id'}) { return ''; }
                   3761:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3762:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3763:         $what.=':POST';
1.583     matthew  3764:         # FIXME: Probably ought to escape things....
1.800     albertel 3765: 	foreach my $key (keys(%env)) {
                   3766:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3767:                 my $formitem = $1;
                   3768:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3769:                     $what.=':'.$formitem.'='.$env{$key};
                   3770:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3771:                     $what.=':'.$formitem.'='.$env{$key};
                   3772:                 }
1.158     www      3773:             }
1.191     harris41 3774:         }
1.583     matthew  3775:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3776:         # FIXME: We should not be depending on a form parameter that someone
                   3777:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3778:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3779:             $what.= ':POST';
                   3780:             # FIXME: Probably ought to escape things....
                   3781:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3782:                                  'crsdiscuss') {
1.620     albertel 3783:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3784:             }
                   3785:         }
1.158     www      3786:     }
                   3787:     &courselog($what);
1.149     www      3788: }
                   3789: 
1.185     www      3790: sub countacc {
                   3791:     my $url=&declutter(shift);
1.458     matthew  3792:     return if (! defined($url) || $url eq '');
1.620     albertel 3793:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3794: #
                   3795: # Mark that this url was used in this course
                   3796: #
1.620     albertel 3797:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3798: #
                   3799: # Increase the access count for this resource in this child process
                   3800: #
1.281     www      3801:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3802:     $accesshash{$key}++;
1.185     www      3803: }
1.349     www      3804: 
1.361     www      3805: sub linklog {
                   3806:     my ($from,$to)=@_;
                   3807:     $from=&declutter($from);
                   3808:     $to=&declutter($to);
                   3809:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3810:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3811: }
1.1160    www      3812: 
                   3813: sub statslog {
                   3814:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3815:     if ($users<2) { return; }
                   3816:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3817:             'course'       => $env{'request.course.id'},
                   3818:             'sections'     => '"all"',
                   3819:             'num_students' => $users,
                   3820:             'part'         => $part,
                   3821:             'symb'         => $symb,
                   3822:             'mean_tries'   => $av_attempts,
                   3823:             'deg_of_diff'  => $degdiff});
                   3824:     foreach my $key (keys(%dynstore)) {
                   3825:         $accesshash{$key}=$dynstore{$key};
                   3826:     }
                   3827: }
1.361     www      3828:   
1.349     www      3829: sub userrolelog {
                   3830:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3831:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3832:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3833:        $userrolehash
                   3834:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3835:                     =$tend.':'.$tstart;
1.662     raeburn  3836:     }
1.1169    droeschl 3837:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3838:        $userrolehash
                   3839:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3840:                     =$tend.':'.$tstart;
                   3841:     }
1.1169    droeschl 3842:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3843:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3844:        $domainrolehash
                   3845:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3846:                     = $tend.':'.$tstart;
                   3847:     }
1.351     www      3848: }
                   3849: 
1.957     raeburn  3850: sub courserolelog {
                   3851:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3852:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3853:         my $cdom = $1;
                   3854:         my $cnum = $2;
                   3855:         my $sec = $3;
                   3856:         my $namespace = 'rolelog';
                   3857:         my %storehash = (
                   3858:                            role    => $trole,
                   3859:                            start   => $tstart,
                   3860:                            end     => $tend,
                   3861:                            selfenroll => $selfenroll,
                   3862:                            context    => $context,
                   3863:                         );
                   3864:         if ($trole eq 'gr') {
                   3865:             $namespace = 'groupslog';
                   3866:             $storehash{'group'} = $sec;
                   3867:         } else {
                   3868:             $storehash{'section'} = $sec;
                   3869:         }
                   3870:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3871:                    $domain,$cnum,$cdom);
                   3872:         if (($trole ne 'st') || ($sec ne '')) {
                   3873:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3874:         }
                   3875:     }
                   3876:     return;
                   3877: }
                   3878: 
1.1172.2.9  raeburn  3879: sub domainrolelog {
                   3880:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3881:     if ($area =~ m{^/($match_domain)/$}) {
                   3882:         my $cdom = $1;
                   3883:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3884:         my $namespace = 'rolelog';
                   3885:         my %storehash = (
                   3886:                            role    => $trole,
                   3887:                            start   => $tstart,
                   3888:                            end     => $tend,
                   3889:                            context => $context,
                   3890:                         );
                   3891:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3892:                    $domain,$domconfiguser,$cdom);
                   3893:     }
                   3894:     return;
                   3895: 
                   3896: }
                   3897: 
                   3898: sub coauthorrolelog {
                   3899:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3900:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3901:         my $audom = $1;
                   3902:         my $auname = $2;
                   3903:         my $namespace = 'rolelog';
                   3904:         my %storehash = (
                   3905:                            role    => $trole,
                   3906:                            start   => $tstart,
                   3907:                            end     => $tend,
                   3908:                            context => $context,
                   3909:                         );
                   3910:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3911:                    $domain,$auname,$audom);
                   3912:     }
                   3913:     return;
                   3914: }
                   3915: 
1.351     www      3916: sub get_course_adv_roles {
1.948     raeburn  3917:     my ($cid,$codes) = @_;
1.620     albertel 3918:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3919:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3920:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3921:     my %nothide=();
1.800     albertel 3922:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3923:         if ($user !~ /:/) {
                   3924: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3925:         } else {
                   3926:             $nothide{$user}=1;
                   3927:         }
1.470     www      3928:     }
1.1172.2.23  raeburn  3929:     my @possdoms = ($coursehash{'domain'});
                   3930:     if ($coursehash{'checkforpriv'}) {
                   3931:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3932:     }
1.351     www      3933:     my %returnhash=();
                   3934:     my %dumphash=
                   3935:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3936:     my $now=time;
1.997     raeburn  3937:     my %privileged;
1.1000    raeburn  3938:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3939: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3940:         if (($tstart) && ($tstart<0)) { next; }
                   3941:         if (($tend) && ($tend<$now)) { next; }
                   3942:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3943:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3944: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  3945:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3946:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3947: 	if ($role eq 'cr') { next; }
1.948     raeburn  3948:         if ($codes) {
                   3949:             if ($section) { $role .= ':'.$section; }
                   3950:             if ($returnhash{$role}) {
                   3951:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3952:             } else {
                   3953:                 $returnhash{$role}=$username.':'.$domain;
                   3954:             }
1.351     www      3955:         } else {
1.988     raeburn  3956:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3957:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3958:             if ($returnhash{$key}) {
                   3959: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3960:             } else {
                   3961:                 $returnhash{$key}=$username.':'.$domain;
                   3962:             }
1.351     www      3963:         }
1.948     raeburn  3964:     }
1.400     www      3965:     return %returnhash;
                   3966: }
                   3967: 
                   3968: sub get_my_roles {
1.937     raeburn  3969:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3970:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3971:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3972:     my (%dumphash,%nothide);
1.1086    raeburn  3973:     if ($context eq 'userroles') {
1.1166    raeburn  3974:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3975:     } else {
1.1172.2.23  raeburn  3976:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3977:         if ($hidepriv) {
                   3978:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3979:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3980:                 if ($user !~ /:/) {
                   3981:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3982:                 } else {
                   3983:                     $nothide{$user} = 1;
                   3984:                 }
                   3985:             }
                   3986:         }
1.858     raeburn  3987:     }
1.400     www      3988:     my %returnhash=();
                   3989:     my $now=time;
1.999     raeburn  3990:     my %privileged;
1.800     albertel 3991:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3992:         my ($role,$tend,$tstart);
                   3993:         if ($context eq 'userroles') {
1.1149    raeburn  3994:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3995: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3996:         } else {
                   3997:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3998:         }
1.400     www      3999:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4000:         my $status = 'active';
1.939     raeburn  4001:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4002:             $status = 'previous';
                   4003:         } 
                   4004:         if (($tstart) && ($now<$tstart)) {
                   4005:             $status = 'future';
                   4006:         }
                   4007:         if (ref($types) eq 'ARRAY') {
                   4008:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4009:                 next;
                   4010:             } 
                   4011:         } else {
                   4012:             if ($status ne 'active') {
                   4013:                 next;
                   4014:             }
                   4015:         }
1.867     raeburn  4016:         my ($rolecode,$username,$domain,$section,$area);
                   4017:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4018:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4019:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4020:         } else {
                   4021:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4022:         }
1.832     raeburn  4023:         if (ref($roledoms) eq 'ARRAY') {
                   4024:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4025:                 next;
                   4026:             }
                   4027:         }
                   4028:         if (ref($roles) eq 'ARRAY') {
                   4029:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4030:                 if ($role =~ /^cr\//) {
                   4031:                     if (!grep(/^cr$/,@{$roles})) {
                   4032:                         next;
                   4033:                     }
1.1104    raeburn  4034:                 } elsif ($role =~ /^gr\//) {
                   4035:                     if (!grep(/^gr$/,@{$roles})) {
                   4036:                         next;
                   4037:                     }
1.922     raeburn  4038:                 } else {
                   4039:                     next;
                   4040:                 }
1.832     raeburn  4041:             }
1.867     raeburn  4042:         }
1.937     raeburn  4043:         if ($hidepriv) {
1.1172.2.23  raeburn  4044:             my @privroles = ('dc','su');
1.999     raeburn  4045:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4046:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4047:             } else {
1.1172.2.23  raeburn  4048:                 my $possdoms = [$domain];
                   4049:                 if (ref($roledoms) eq 'ARRAY') {
                   4050:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4051:                 }
1.1172.2.23  raeburn  4052:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4053:                     if (!$nothide{$username.':'.$domain}) {
                   4054:                         next;
                   4055:                     }
                   4056:                 }
1.937     raeburn  4057:             }
                   4058:         }
1.933     raeburn  4059:         if ($withsec) {
                   4060:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4061:                 $tstart.':'.$tend;
                   4062:         } else {
                   4063:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4064:         }
1.832     raeburn  4065:     }
1.373     www      4066:     return %returnhash;
1.399     www      4067: }
                   4068: 
                   4069: # ----------------------------------------------------- Frontpage Announcements
                   4070: #
                   4071: #
                   4072: 
                   4073: sub postannounce {
                   4074:     my ($server,$text)=@_;
1.844     albertel 4075:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4076:     unless ($text=~/\w/) { $text=''; }
                   4077:     return &reply('setannounce:'.&escape($text),$server);
                   4078: }
                   4079: 
                   4080: sub getannounce {
1.448     albertel 4081: 
                   4082:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4083: 	my $announcement='';
1.800     albertel 4084: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4085: 	close($fh);
1.399     www      4086: 	if ($announcement=~/\w/) { 
                   4087: 	    return 
                   4088:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4089:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4090: 	} else {
                   4091: 	    return '';
                   4092: 	}
                   4093:     } else {
                   4094: 	return '';
                   4095:     }
1.351     www      4096: }
1.353     www      4097: 
                   4098: # ---------------------------------------------------------- Course ID routines
                   4099: # Deal with domain's nohist_courseid.db files
                   4100: #
                   4101: 
                   4102: sub courseidput {
1.921     raeburn  4103:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4104:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4105:     my $outcome;
                   4106:     if ($caller eq 'timeonly') {
                   4107:         my $cids = '';
                   4108:         foreach my $item (keys(%$storehash)) {
                   4109:             $cids.=&escape($item).'&';
                   4110:         }
                   4111:         $cids=~s/\&$//;
                   4112:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4113:                           $coursehome);       
                   4114:     } else {
                   4115:         my $items = '';
                   4116:         foreach my $item (keys(%$storehash)) {
                   4117:             $items.= &escape($item).'='.
                   4118:                      &freeze_escape($$storehash{$item}).'&';
                   4119:         }
                   4120:         $items=~s/\&$//;
                   4121:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4122:                           $coursehome);
1.918     raeburn  4123:     }
                   4124:     if ($outcome eq 'unknown_cmd') {
                   4125:         my $what;
                   4126:         foreach my $cid (keys(%$storehash)) {
                   4127:             $what .= &escape($cid).'=';
1.921     raeburn  4128:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4129:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4130:             }
                   4131:             $what =~ s/\:$/&/;
                   4132:         }
                   4133:         $what =~ s/\&$//;  
                   4134:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4135:     } else {
                   4136:         return $outcome;
                   4137:     }
1.353     www      4138: }
                   4139: 
                   4140: sub courseiddump {
1.921     raeburn  4141:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4142:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4143:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4144:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4145:     my $as_hash = 1;
                   4146:     my %returnhash;
                   4147:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4148:     my %libserv = &all_library();
                   4149:     foreach my $tryserver (keys(%libserv)) {
                   4150:         if ( (  $hostidflag == 1 
                   4151: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4152: 	     || (!defined($hostidflag)) ) {
                   4153: 
1.918     raeburn  4154: 	    if (($domfilter eq '') ||
                   4155: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4156:                 my $rep;
                   4157:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4158:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4159:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4160:                                 &escape($descfilter), &escape($instcodefilter),
                   4161:                                 &escape($ownerfilter), &escape($coursefilter),
                   4162:                                 &escape($typefilter), &escape($regexp_ok),
                   4163:                                 $as_hash, &escape($selfenrollonly),
                   4164:                                 &escape($catfilter), $showhidden, $caller,
                   4165:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4166:                                 &escape($createdbefore), &escape($createdafter),
                   4167:                                 &escape($creationcontext), $domcloner)));
                   4168:                 } else {
                   4169:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4170:                              $sincefilter.':'.&escape($descfilter).':'.
                   4171:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4172:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4173:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4174:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4175:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4176:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4177:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4178:                              &escape($creationcontext).':'.$domcloner,
                   4179:                              $tryserver);
                   4180:                 }
                   4181: 
1.918     raeburn  4182:                 my @pairs=split(/\&/,$rep);
                   4183:                 foreach my $item (@pairs) {
                   4184:                     my ($key,$value)=split(/\=/,$item,2);
                   4185:                     $key = &unescape($key);
                   4186:                     next if ($key =~ /^error: 2 /);
                   4187:                     my $result = &thaw_unescape($value);
                   4188:                     if (ref($result) eq 'HASH') {
                   4189:                         $returnhash{$key}=$result;
                   4190:                     } else {
1.921     raeburn  4191:                         my @responses = split(/:/,$value);
                   4192:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4193:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4194:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4195:                         }
1.1008    raeburn  4196:                     }
1.353     www      4197:                 }
                   4198:             }
                   4199:         }
                   4200:     }
                   4201:     return %returnhash;
                   4202: }
                   4203: 
1.1055    raeburn  4204: sub courselastaccess {
                   4205:     my ($cdom,$cnum,$hostidref) = @_;
                   4206:     my %returnhash;
                   4207:     if ($cdom && $cnum) {
                   4208:         my $chome = &homeserver($cnum,$cdom);
                   4209:         if ($chome ne 'no_host') {
                   4210:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4211:             &extract_lastaccess(\%returnhash,$rep);
                   4212:         }
                   4213:     } else {
                   4214:         if (!$cdom) { $cdom=''; }
                   4215:         my %libserv = &all_library();
                   4216:         foreach my $tryserver (keys(%libserv)) {
                   4217:             if (ref($hostidref) eq 'ARRAY') {
                   4218:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4219:             } 
                   4220:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4221:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4222:                 &extract_lastaccess(\%returnhash,$rep);
                   4223:             }
                   4224:         }
                   4225:     }
                   4226:     return %returnhash;
                   4227: }
                   4228: 
                   4229: sub extract_lastaccess {
                   4230:     my ($returnhash,$rep) = @_;
                   4231:     if (ref($returnhash) eq 'HASH') {
                   4232:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4233:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4234:                  $rep eq '') {
                   4235:             my @pairs=split(/\&/,$rep);
                   4236:             foreach my $item (@pairs) {
                   4237:                 my ($key,$value)=split(/\=/,$item,2);
                   4238:                 $key = &unescape($key);
                   4239:                 next if ($key =~ /^error: 2 /);
                   4240:                 $returnhash->{$key} = &thaw_unescape($value);
                   4241:             }
                   4242:         }
                   4243:     }
                   4244:     return;
                   4245: }
                   4246: 
1.658     raeburn  4247: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4248: 
                   4249: sub dcmailput {
1.685     raeburn  4250:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4251:     my $status = &Apache::lonnet::critical(
1.740     www      4252:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4253:        &escape($message),$server);
1.662     raeburn  4254:     return $status;
                   4255: }
                   4256: 
1.658     raeburn  4257: sub dcmaildump {
                   4258:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4259:     my %returnhash=();
1.846     albertel 4260: 
                   4261:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4262:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4263:                                                          &escape($enddate).':';
                   4264: 	my @esc_senders=map { &escape($_)} @$senders;
                   4265: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4266: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4267:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4268:             if (($key) && ($value)) {
                   4269:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4270:             }
                   4271:         }
                   4272:     }
                   4273:     return %returnhash;
                   4274: }
1.662     raeburn  4275: # ---------------------------------------------------------- Domain roles
                   4276: 
                   4277: sub get_domain_roles {
                   4278:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4279:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4280:         $startdate = '.';
                   4281:     }
1.1018    raeburn  4282:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4283:         $enddate = '.';
                   4284:     }
1.922     raeburn  4285:     my $rolelist;
                   4286:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4287:         $rolelist = join('&',@{$roles});
1.922     raeburn  4288:     }
1.662     raeburn  4289:     my %personnel = ();
1.841     albertel 4290: 
                   4291:     my %servers = &get_servers($dom,'library');
                   4292:     foreach my $tryserver (keys(%servers)) {
                   4293: 	%{$personnel{$tryserver}}=();
                   4294: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4295: 					    &escape($startdate).':'.
                   4296: 					    &escape($enddate).':'.
                   4297: 					    &escape($rolelist), $tryserver))) {
                   4298: 	    my ($key,$value) = split(/\=/,$line,2);
                   4299: 	    if (($key) && ($value)) {
                   4300: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4301: 	    }
                   4302: 	}
1.662     raeburn  4303:     }
                   4304:     return %personnel;
                   4305: }
1.658     raeburn  4306: 
1.1057    www      4307: # ----------------------------------------------------------- Interval timing 
1.149     www      4308: 
1.1153    www      4309: {
                   4310: # Caches needed for speedup of navmaps
                   4311: # We don't want to cache this for very long at all (5 seconds at most)
                   4312: # 
                   4313: # The user for whom we cache
                   4314: my $cachedkey='';
                   4315: # The cached times for this user
                   4316: my %cachedtimes=();
                   4317: # When this was last done
                   4318: my $cachedtime=();
                   4319: 
                   4320: sub load_all_first_access {
1.1154    raeburn  4321:     my ($uname,$udom)=@_;
1.1156    www      4322:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4323:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4324:         return;
                   4325:     }
                   4326:     $cachedtime=time;
                   4327:     $cachedkey=$uname.':'.$udom;
                   4328:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4329: }
                   4330: 
1.504     albertel 4331: sub get_first_access {
1.1162    raeburn  4332:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4333:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4334:     if ($argsymb) { $symb=$argsymb; }
                   4335:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4336:     if ($argmap) { $map = $argmap; }
1.926     albertel 4337:     if ($type eq 'course') {
                   4338: 	$res='course';
                   4339:     } elsif ($type eq 'map') {
1.588     albertel 4340: 	$res=&symbread($map);
                   4341:     } else {
                   4342: 	$res=$symb;
                   4343:     }
1.1153    www      4344:     &load_all_first_access($uname,$udom);
                   4345:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4346: }
                   4347: 
                   4348: sub set_first_access {
1.1162    raeburn  4349:     my ($type,$interval)=@_;
1.790     albertel 4350:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4351:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4352:     if ($type eq 'course') {
                   4353: 	$res='course';
                   4354:     } elsif ($type eq 'map') {
1.588     albertel 4355: 	$res=&symbread($map);
                   4356:     } else {
                   4357: 	$res=$symb;
                   4358:     }
1.1153    www      4359:     $cachedkey='';
1.1162    raeburn  4360:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4361:     if (!$firstaccess) {
1.1162    raeburn  4362:         my $start = time;
                   4363: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4364:                           $udom,$uname);
                   4365:         if ($putres eq 'ok') {
                   4366:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4367:                  $udom,$uname); 
                   4368:             &appenv(
                   4369:                      {
                   4370:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4371:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4372:                      }
                   4373:                   );
                   4374:         }
                   4375:         return $putres;
1.505     albertel 4376:     }
                   4377:     return 'already_set';
1.504     albertel 4378: }
1.1153    www      4379: }
1.110     www      4380: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4381: 
                   4382: sub expirespread {
                   4383:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4384:     my $cid=$env{'request.course.id'}; 
1.110     www      4385:     if ($cid) {
                   4386:        my $now=time;
                   4387:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4388:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4389:                             $env{'course.'.$cid.'.num'}.
1.110     www      4390: 	        	    ':nohist_expirationdates:'.
                   4391:                             &escape($key).'='.$now,
1.620     albertel 4392:                             $env{'course.'.$cid.'.home'})
1.110     www      4393:     }
                   4394:     return 'ok';
1.14      www      4395: }
                   4396: 
1.109     www      4397: # ----------------------------------------------------- Devalidate Spreadsheets
                   4398: 
                   4399: sub devalidate {
1.325     www      4400:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4401:     my $cid=$env{'request.course.id'}; 
1.109     www      4402:     if ($cid) {
1.391     matthew  4403:         # delete the stored spreadsheets for
                   4404:         # - the student level sheet of this user in course's homespace
                   4405:         # - the assessment level sheet for this resource 
                   4406:         #   for this user in user's homespace
1.553     albertel 4407: 	# - current conditional state info
1.325     www      4408: 	my $key=$uname.':'.$udom.':';
1.109     www      4409:         my $status=
1.299     matthew  4410: 	    &del('nohist_calculatedsheets',
1.391     matthew  4411: 		 [$key.'studentcalc:'],
1.620     albertel 4412: 		 $env{'course.'.$cid.'.domain'},
                   4413: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4414: 		.' '.
                   4415: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4416: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4417:         unless ($status eq 'ok ok') {
                   4418:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4419:                     $uname.' at '.$udom.' for '.
1.109     www      4420: 		    $symb.': '.$status);
1.133     albertel 4421:         }
1.553     albertel 4422: 	&delenv('user.state.'.$cid);
1.109     www      4423:     }
                   4424: }
                   4425: 
1.265     albertel 4426: sub get_scalar {
                   4427:     my ($string,$end) = @_;
                   4428:     my $value;
                   4429:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4430: 	$value = $1;
                   4431:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4432: 	$value = $1;
                   4433:     }
                   4434:     return &unescape($value);
                   4435: }
                   4436: 
                   4437: sub array2str {
                   4438:   my (@array) = @_;
                   4439:   my $result=&arrayref2str(\@array);
                   4440:   $result=~s/^__ARRAY_REF__//;
                   4441:   $result=~s/__END_ARRAY_REF__$//;
                   4442:   return $result;
                   4443: }
                   4444: 
1.204     albertel 4445: sub arrayref2str {
                   4446:   my ($arrayref) = @_;
1.265     albertel 4447:   my $result='__ARRAY_REF__';
1.204     albertel 4448:   foreach my $elem (@$arrayref) {
1.265     albertel 4449:     if(ref($elem) eq 'ARRAY') {
                   4450:       $result.=&arrayref2str($elem).'&';
                   4451:     } elsif(ref($elem) eq 'HASH') {
                   4452:       $result.=&hashref2str($elem).'&';
                   4453:     } elsif(ref($elem)) {
                   4454:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4455:     } else {
                   4456:       $result.=&escape($elem).'&';
                   4457:     }
                   4458:   }
                   4459:   $result=~s/\&$//;
1.265     albertel 4460:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4461:   return $result;
                   4462: }
                   4463: 
1.168     albertel 4464: sub hash2str {
1.204     albertel 4465:   my (%hash) = @_;
                   4466:   my $result=&hashref2str(\%hash);
1.265     albertel 4467:   $result=~s/^__HASH_REF__//;
                   4468:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4469:   return $result;
                   4470: }
                   4471: 
                   4472: sub hashref2str {
                   4473:   my ($hashref)=@_;
1.265     albertel 4474:   my $result='__HASH_REF__';
1.800     albertel 4475:   foreach my $key (sort(keys(%$hashref))) {
                   4476:     if (ref($key) eq 'ARRAY') {
                   4477:       $result.=&arrayref2str($key).'=';
                   4478:     } elsif (ref($key) eq 'HASH') {
                   4479:       $result.=&hashref2str($key).'=';
                   4480:     } elsif (ref($key)) {
1.265     albertel 4481:       $result.='=';
1.800     albertel 4482:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4483:     } else {
1.1132    raeburn  4484: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4485:     }
                   4486: 
1.800     albertel 4487:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4488:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4489:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4490:       $result.=&hashref2str($hashref->{$key}).'&';
                   4491:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4492:        $result.='&';
1.800     albertel 4493:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4494:     } else {
1.800     albertel 4495:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4496:     }
                   4497:   }
1.168     albertel 4498:   $result=~s/\&$//;
1.265     albertel 4499:   $result .= '__END_HASH_REF__';
1.168     albertel 4500:   return $result;
                   4501: }
                   4502: 
                   4503: sub str2hash {
1.265     albertel 4504:     my ($string)=@_;
                   4505:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4506:     return %$hash;
                   4507: }
                   4508: 
                   4509: sub str2hashref {
1.168     albertel 4510:   my ($string) = @_;
1.265     albertel 4511: 
                   4512:   my %hash;
                   4513: 
                   4514:   if($string !~ /^__HASH_REF__/) {
                   4515:       if (! ($string eq '' || !defined($string))) {
                   4516: 	  $hash{'error'}='Not hash reference';
                   4517:       }
                   4518:       return (\%hash, $string);
                   4519:   }
                   4520: 
                   4521:   $string =~ s/^__HASH_REF__//;
                   4522: 
                   4523:   while($string !~ /^__END_HASH_REF__/) {
                   4524:       #key
                   4525:       my $key='';
                   4526:       if($string =~ /^__HASH_REF__/) {
                   4527:           ($key, $string)=&str2hashref($string);
                   4528:           if(defined($key->{'error'})) {
                   4529:               $hash{'error'}='Bad data';
                   4530:               return (\%hash, $string);
                   4531:           }
                   4532:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4533:           ($key, $string)=&str2arrayref($string);
                   4534:           if($key->[0] eq 'Array reference error') {
                   4535:               $hash{'error'}='Bad data';
                   4536:               return (\%hash, $string);
                   4537:           }
                   4538:       } else {
                   4539:           $string =~ s/^(.*?)=//;
1.267     albertel 4540: 	  $key=&unescape($1);
1.265     albertel 4541:       }
                   4542:       $string =~ s/^=//;
                   4543: 
                   4544:       #value
                   4545:       my $value='';
                   4546:       if($string =~ /^__HASH_REF__/) {
                   4547:           ($value, $string)=&str2hashref($string);
                   4548:           if(defined($value->{'error'})) {
                   4549:               $hash{'error'}='Bad data';
                   4550:               return (\%hash, $string);
                   4551:           }
                   4552:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4553:           ($value, $string)=&str2arrayref($string);
                   4554:           if($value->[0] eq 'Array reference error') {
                   4555:               $hash{'error'}='Bad data';
                   4556:               return (\%hash, $string);
                   4557:           }
                   4558:       } else {
                   4559: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4560:       }
                   4561:       $string =~ s/^&//;
                   4562: 
                   4563:       $hash{$key}=$value;
1.204     albertel 4564:   }
1.265     albertel 4565: 
                   4566:   $string =~ s/^__END_HASH_REF__//;
                   4567: 
                   4568:   return (\%hash, $string);
1.204     albertel 4569: }
                   4570: 
                   4571: sub str2array {
1.265     albertel 4572:     my ($string)=@_;
                   4573:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4574:     return @$array;
                   4575: }
                   4576: 
                   4577: sub str2arrayref {
1.204     albertel 4578:   my ($string) = @_;
1.265     albertel 4579:   my @array;
                   4580: 
                   4581:   if($string !~ /^__ARRAY_REF__/) {
                   4582:       if (! ($string eq '' || !defined($string))) {
                   4583: 	  $array[0]='Array reference error';
                   4584:       }
                   4585:       return (\@array, $string);
                   4586:   }
                   4587: 
                   4588:   $string =~ s/^__ARRAY_REF__//;
                   4589: 
                   4590:   while($string !~ /^__END_ARRAY_REF__/) {
                   4591:       my $value='';
                   4592:       if($string =~ /^__HASH_REF__/) {
                   4593:           ($value, $string)=&str2hashref($string);
                   4594:           if(defined($value->{'error'})) {
                   4595:               $array[0] ='Array reference error';
                   4596:               return (\@array, $string);
                   4597:           }
                   4598:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4599:           ($value, $string)=&str2arrayref($string);
                   4600:           if($value->[0] eq 'Array reference error') {
                   4601:               $array[0] ='Array reference error';
                   4602:               return (\@array, $string);
                   4603:           }
                   4604:       } else {
                   4605: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4606:       }
                   4607:       $string =~ s/^&//;
                   4608: 
                   4609:       push(@array, $value);
1.191     harris41 4610:   }
1.265     albertel 4611: 
                   4612:   $string =~ s/^__END_ARRAY_REF__//;
                   4613: 
                   4614:   return (\@array, $string);
1.168     albertel 4615: }
                   4616: 
1.167     albertel 4617: # -------------------------------------------------------------------Temp Store
                   4618: 
1.168     albertel 4619: sub tmpreset {
                   4620:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4621:   if (!$symb) {
                   4622:     $symb=&symbread();
1.620     albertel 4623:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4624:   }
                   4625:   $symb=escape($symb);
                   4626: 
1.620     albertel 4627:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4628:   $namespace=~s/\//\_/g;
                   4629:   $namespace=~s/\W//g;
                   4630: 
1.620     albertel 4631:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4632:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4633:   if ($domain eq 'public' && $stuname eq 'public') {
                   4634:       $stuname=$ENV{'REMOTE_ADDR'};
                   4635:   }
1.1117    foxr     4636:   my $path=LONCAPA::tempdir();
1.168     albertel 4637:   my %hash;
                   4638:   if (tie(%hash,'GDBM_File',
                   4639: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4640: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4641:     foreach my $key (keys(%hash)) {
1.180     albertel 4642:       if ($key=~ /:$symb/) {
1.168     albertel 4643: 	delete($hash{$key});
                   4644:       }
                   4645:     }
                   4646:   }
                   4647: }
                   4648: 
1.167     albertel 4649: sub tmpstore {
1.168     albertel 4650:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4651: 
                   4652:   if (!$symb) {
                   4653:     $symb=&symbread();
1.620     albertel 4654:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4655:   }
                   4656:   $symb=escape($symb);
                   4657: 
                   4658:   if (!$namespace) {
                   4659:     # I don't think we would ever want to store this for a course.
                   4660:     # it seems this will only be used if we don't have a course.
1.620     albertel 4661:     #$namespace=$env{'request.course.id'};
1.168     albertel 4662:     #if (!$namespace) {
1.620     albertel 4663:       $namespace=$env{'request.state'};
1.168     albertel 4664:     #}
                   4665:   }
                   4666:   $namespace=~s/\//\_/g;
                   4667:   $namespace=~s/\W//g;
1.620     albertel 4668:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4669:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4670:   if ($domain eq 'public' && $stuname eq 'public') {
                   4671:       $stuname=$ENV{'REMOTE_ADDR'};
                   4672:   }
1.168     albertel 4673:   my $now=time;
                   4674:   my %hash;
1.1117    foxr     4675:   my $path=LONCAPA::tempdir();
1.168     albertel 4676:   if (tie(%hash,'GDBM_File',
                   4677: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4678: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4679:     $hash{"version:$symb"}++;
                   4680:     my $version=$hash{"version:$symb"};
                   4681:     my $allkeys=''; 
                   4682:     foreach my $key (keys(%$storehash)) {
                   4683:       $allkeys.=$key.':';
1.591     albertel 4684:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4685:     }
                   4686:     $hash{"$version:$symb:timestamp"}=$now;
                   4687:     $allkeys.='timestamp';
                   4688:     $hash{"$version:keys:$symb"}=$allkeys;
                   4689:     if (untie(%hash)) {
                   4690:       return 'ok';
                   4691:     } else {
                   4692:       return "error:$!";
                   4693:     }
                   4694:   } else {
                   4695:     return "error:$!";
                   4696:   }
                   4697: }
1.167     albertel 4698: 
1.168     albertel 4699: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4700: 
1.168     albertel 4701: sub tmprestore {
                   4702:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4703: 
1.168     albertel 4704:   if (!$symb) {
                   4705:     $symb=&symbread();
1.620     albertel 4706:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4707:   }
                   4708:   $symb=escape($symb);
                   4709: 
1.620     albertel 4710:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4711: 
1.620     albertel 4712:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4713:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4714:   if ($domain eq 'public' && $stuname eq 'public') {
                   4715:       $stuname=$ENV{'REMOTE_ADDR'};
                   4716:   }
1.168     albertel 4717:   my %returnhash;
                   4718:   $namespace=~s/\//\_/g;
                   4719:   $namespace=~s/\W//g;
                   4720:   my %hash;
1.1117    foxr     4721:   my $path=LONCAPA::tempdir();
1.168     albertel 4722:   if (tie(%hash,'GDBM_File',
                   4723: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4724: 	  &GDBM_READER(),0640)) {
1.168     albertel 4725:     my $version=$hash{"version:$symb"};
                   4726:     $returnhash{'version'}=$version;
                   4727:     my $scope;
                   4728:     for ($scope=1;$scope<=$version;$scope++) {
                   4729:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4730:       my @keys=split(/:/,$vkeys);
                   4731:       my $key;
                   4732:       $returnhash{"$scope:keys"}=$vkeys;
                   4733:       foreach $key (@keys) {
1.591     albertel 4734: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4735: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4736:       }
                   4737:     }
1.168     albertel 4738:     if (!(untie(%hash))) {
                   4739:       return "error:$!";
                   4740:     }
                   4741:   } else {
                   4742:     return "error:$!";
                   4743:   }
                   4744:   return %returnhash;
1.167     albertel 4745: }
                   4746: 
1.9       www      4747: # ----------------------------------------------------------------------- Store
                   4748: 
                   4749: sub store {
1.124     www      4750:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4751:     my $home='';
                   4752: 
1.168     albertel 4753:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4754: 
1.213     www      4755:     $symb=&symbclean($symb);
1.122     albertel 4756:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4757: 
1.620     albertel 4758:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4759:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4760: 
                   4761:     &devalidate($symb,$stuname,$domain);
1.109     www      4762: 
                   4763:     $symb=escape($symb);
1.187     www      4764:     if (!$namespace) { 
1.620     albertel 4765:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4766:           return ''; 
                   4767:        } 
                   4768:     }
1.620     albertel 4769:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4770: 
                   4771:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4772:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4773: 
1.12      www      4774:     my $namevalue='';
1.800     albertel 4775:     foreach my $key (keys(%$storehash)) {
                   4776:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4777:     }
1.12      www      4778:     $namevalue=~s/\&$//;
1.187     www      4779:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4780:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4781: }
                   4782: 
1.47      www      4783: # -------------------------------------------------------------- Critical Store
                   4784: 
                   4785: sub cstore {
1.124     www      4786:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4787:     my $home='';
                   4788: 
1.168     albertel 4789:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4790: 
1.213     www      4791:     $symb=&symbclean($symb);
1.122     albertel 4792:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4793: 
1.620     albertel 4794:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4795:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4796: 
                   4797:     &devalidate($symb,$stuname,$domain);
1.109     www      4798: 
                   4799:     $symb=escape($symb);
1.187     www      4800:     if (!$namespace) { 
1.620     albertel 4801:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4802:           return ''; 
                   4803:        } 
                   4804:     }
1.620     albertel 4805:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4806: 
                   4807:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4808:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4809: 
1.47      www      4810:     my $namevalue='';
1.800     albertel 4811:     foreach my $key (keys(%$storehash)) {
                   4812:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4813:     }
1.47      www      4814:     $namevalue=~s/\&$//;
1.187     www      4815:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4816:     return critical
                   4817:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4818: }
                   4819: 
1.9       www      4820: # --------------------------------------------------------------------- Restore
                   4821: 
                   4822: sub restore {
1.124     www      4823:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4824:     my $home='';
                   4825: 
1.168     albertel 4826:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4827: 
1.122     albertel 4828:     if (!$symb) {
1.1172.2.26  raeburn  4829:         return if ($namespace eq 'courserequests');
                   4830:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4831:     } else {
1.1172.2.26  raeburn  4832:         unless ($namespace eq 'courserequests') {
                   4833:             $symb=&escape(&symbclean($symb));
                   4834:         }
1.122     albertel 4835:     }
1.188     www      4836:     if (!$namespace) { 
1.620     albertel 4837:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4838:           return ''; 
                   4839:        } 
                   4840:     }
1.620     albertel 4841:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4842:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4843:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4844:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4845: 
1.12      www      4846:     my %returnhash=();
1.800     albertel 4847:     foreach my $line (split(/\&/,$answer)) {
                   4848: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4849:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4850:     }
1.75      www      4851:     my $version;
                   4852:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4853:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4854:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4855:        }
1.75      www      4856:     }
1.13      www      4857:     return %returnhash;
1.34      www      4858: }
                   4859: 
                   4860: # ---------------------------------------------------------- Course Description
1.1118    foxr     4861: #
                   4862: #  
1.34      www      4863: 
                   4864: sub coursedescription {
1.731     albertel 4865:     my ($courseid,$args)=@_;
1.34      www      4866:     $courseid=~s/^\///;
1.49      www      4867:     $courseid=~s/\_/\//g;
1.34      www      4868:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4869:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4870:     my $normalid=$cdomain.'_'.$cnum;
                   4871:     # need to always cache even if we get errors otherwise we keep 
                   4872:     # trying and trying and trying to get the course description.
                   4873:     my %envhash=();
                   4874:     my %returnhash=();
1.731     albertel 4875:     
                   4876:     my $expiretime=600;
                   4877:     if ($env{'request.course.id'} eq $normalid) {
                   4878: 	$expiretime=120;
                   4879:     }
                   4880: 
                   4881:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4882:     if (!$args->{'freshen_cache'}
                   4883: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4884: 	foreach my $key (keys(%env)) {
                   4885: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4886: 	    my ($setting) = $1;
                   4887: 	    $returnhash{$setting} = $env{$key};
                   4888: 	}
                   4889: 	return %returnhash;
                   4890:     }
                   4891: 
1.1118    foxr     4892:     # get the data again
                   4893: 
1.731     albertel 4894:     if (!$args->{'one_time'}) {
                   4895: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4896:     }
1.811     albertel 4897: 
1.34      www      4898:     if ($chome ne 'no_host') {
1.302     albertel 4899:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4900:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4901: 	   my $username = $env{'user.name'}; # Defult username
                   4902: 	   if(defined $args->{'user'}) {
                   4903: 	       $username = $args->{'user'};
                   4904: 	   }
1.129     albertel 4905:            $returnhash{'home'}= $chome;
                   4906: 	   $returnhash{'domain'} = $cdomain;
                   4907: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4908:            if (!defined($returnhash{'type'})) {
                   4909:                $returnhash{'type'} = 'Course';
                   4910:            }
1.130     albertel 4911:            while (my ($name,$value) = each %returnhash) {
1.53      www      4912:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4913:            }
1.270     www      4914:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4915:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4916: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4917:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4918:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4919:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4920:        }
                   4921:     }
1.731     albertel 4922:     if (!$args->{'one_time'}) {
1.949     raeburn  4923: 	&appenv(\%envhash);
1.731     albertel 4924:     }
1.302     albertel 4925:     return %returnhash;
1.461     www      4926: }
                   4927: 
1.1080    raeburn  4928: sub update_released_required {
                   4929:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4930:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4931:         $cid = $env{'request.course.id'};
                   4932:         $cdom = $env{'course.'.$cid.'.domain'};
                   4933:         $cnum = $env{'course.'.$cid.'.num'};
                   4934:         $chome = $env{'course.'.$cid.'.home'};
                   4935:     }
                   4936:     if ($needsrelease) {
                   4937:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4938:         my $needsupdate;
                   4939:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4940:             $needsupdate = 1;
                   4941:         } else {
                   4942:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4943:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4944:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4945:                 $needsupdate = 1;
                   4946:             }
                   4947:         }
                   4948:         if ($needsupdate) {
                   4949:             my %needshash = (
                   4950:                              'internal.releaserequired' => $needsrelease,
                   4951:                             );
                   4952:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4953:             if ($putresult eq 'ok') {
                   4954:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4955:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4956:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4957:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4958:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4959:                 }
                   4960:             }
                   4961:         }
                   4962:     }
                   4963:     return;
                   4964: }
                   4965: 
1.461     www      4966: # -------------------------------------------------See if a user is privileged
                   4967: 
                   4968: sub privileged {
1.1172.2.23  raeburn  4969:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4970:     my $now = time;
1.1172.2.23  raeburn  4971:     my $roles;
                   4972:     if (ref($possroles) eq 'ARRAY') {
                   4973:         $roles = $possroles;
                   4974:     } else {
                   4975:         $roles = ['dc','su'];
                   4976:     }
                   4977:     if (ref($possdomains) eq 'ARRAY') {
                   4978:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   4979:         foreach my $dom (@{$possdomains}) {
                   4980:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   4981:                 (ref($privileged{$dom}) eq 'HASH')) {
                   4982:                 foreach my $role (@{$roles}) {
                   4983:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   4984:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   4985:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   4986:                             return 1 unless (($end && $end < $now) ||
                   4987:                                              ($start && $start > $now));
                   4988:                         }
                   4989:                     }
                   4990:                 }
                   4991:             }
                   4992:         }
                   4993:     } else {
                   4994:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4995:         my $now = time;
1.1170    droeschl 4996: 
1.1172.2.23  raeburn  4997:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 4998:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  4999:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5000:                 return 1 unless ($tend && $tend < $now)
                   5001:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5002:             }
1.1172.2.23  raeburn  5003:         }
                   5004:     }
1.461     www      5005:     return 0;
1.9       www      5006: }
1.1       albertel 5007: 
1.1172.2.23  raeburn  5008: sub privileged_by_domain {
                   5009:     my ($domains,$roles) = @_;
                   5010:     my %privileged = ();
                   5011:     my $cachetime = 60*60*24;
                   5012:     my $now = time;
                   5013:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5014:         return %privileged;
                   5015:     }
                   5016:     foreach my $dom (@{$domains}) {
                   5017:         next if (ref($privileged{$dom}) eq 'HASH');
                   5018:         my $needroles;
                   5019:         foreach my $role (@{$roles}) {
                   5020:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5021:             if (defined($cached)) {
                   5022:                 if (ref($result) eq 'HASH') {
                   5023:                     $privileged{$dom}{$role} = $result;
                   5024:                 }
                   5025:             } else {
                   5026:                 $needroles = 1;
                   5027:             }
                   5028:         }
                   5029:         if ($needroles) {
                   5030:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5031:             $privileged{$dom} = {};
                   5032:             foreach my $server (keys(%dompersonnel)) {
                   5033:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5034:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5035:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5036:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5037:                         next if ($end && $end < $now);
                   5038:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5039:                             $dompersonnel{$server}{$item};
                   5040:                     }
                   5041:                 }
                   5042:             }
                   5043:             if (ref($privileged{$dom}) eq 'HASH') {
                   5044:                 foreach my $role (@{$roles}) {
                   5045:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5046:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5047:                     } else {
                   5048:                         my %hash = ();
                   5049:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5050:                     }
                   5051:                 }
                   5052:             }
                   5053:         }
                   5054:     }
                   5055:     return %privileged;
                   5056: }
                   5057: 
1.103     harris41 5058: # -------------------------------------------------------- Get user privileges
1.11      www      5059: 
                   5060: sub rolesinit {
1.1169    droeschl 5061:     my ($domain, $username) = @_;
                   5062:     my %userroles = ('user.login.time' => time);
                   5063:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5064: 
                   5065:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5066:     # also, blocking can be triggered by an activating timer
                   5067:     # it's saved in the user's %env.
                   5068:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5069:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5070:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5071:         %timerintchk, %timerintenv);
                   5072: 
1.1162    raeburn  5073:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5074:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5075:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5076:     }
1.1169    droeschl 5077: 
1.1162    raeburn  5078:     foreach my $key (keys(%timerinterval)) {
                   5079:         my ($cid,$rest) = split(/\0/,$key);
                   5080:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5081:     }
1.1169    droeschl 5082: 
1.11      www      5083:     my %allroles=();
1.1162    raeburn  5084:     my %allgroups=();
1.11      www      5085: 
1.1169    droeschl 5086:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5087:         my $role = $rolesdump{$area};
                   5088:         $area =~ s/\_\w\w$//;
                   5089: 
                   5090:         my ($trole, $tend, $tstart, $group_privs);
                   5091: 
                   5092:         if ($role =~ /^cr/) {
                   5093:         # Custom role, defined by a user 
                   5094:         # e.g., user.role.cr/msu/smith/mynewrole
                   5095:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5096:                 $trole = $1;
                   5097:                 ($tend, $tstart) = split('_', $2);
                   5098:             } else {
                   5099:                 $trole = $role;
                   5100:             }
                   5101:         } elsif ($role =~ m|^gr/|) {
                   5102:         # Role of member in a group, defined within a course/community
                   5103:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5104:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5105:             next if $tstart eq '-1';
                   5106:             ($trole, $group_privs) = split(/\//, $trole);
                   5107:             $group_privs = &unescape($group_privs);
                   5108:         } else {
                   5109:         # Just a normal role, defined in roles.tab
                   5110:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5111:         }
                   5112: 
                   5113:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5114:                  $username);
                   5115:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5116: 
                   5117:         # role expired or not available yet?
                   5118:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5119:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5120: 
                   5121:         next if $area eq '' or $trole eq '';
                   5122: 
                   5123:         my $spec = "$trole.$area";
                   5124:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5125: 
                   5126:         if ($trole =~ /^cr\//) {
                   5127:         # Custom role, defined by a user
                   5128:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5129:         } elsif ($trole eq 'gr') {
                   5130:         # Role of a member in a group, defined within a course/community
                   5131:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5132:             next;
                   5133:         } else {
                   5134:         # Normal role, defined in roles.tab
                   5135:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5136:         }
                   5137: 
                   5138:         my $cid = $tdomain.'_'.$trest;
                   5139:         unless ($firstaccchk{$cid}) {
                   5140:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5141:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5142:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5143:                         $coursetimerstarts{$cid}{$item}; 
                   5144:                 }
                   5145:             }
                   5146:             $firstaccchk{$cid} = 1;
                   5147:         }
                   5148:         unless ($timerintchk{$cid}) {
                   5149:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5150:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5151:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5152:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5153:                 }
1.12      www      5154:             }
1.1169    droeschl 5155:             $timerintchk{$cid} = 1;
1.191     harris41 5156:         }
1.11      www      5157:     }
1.1169    droeschl 5158: 
                   5159:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5160:         \%allroles, \%allgroups);
                   5161:     $env{'user.adv'} = $userroles{'user.adv'};
                   5162: 
1.1162    raeburn  5163:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5164: }
                   5165: 
1.567     raeburn  5166: sub set_arearole {
1.1172.2.19  raeburn  5167:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5168:     unless ($nolog) {
1.567     raeburn  5169: # log the associated role with the area
1.1172.2.19  raeburn  5170:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5171:     }
1.743     albertel 5172:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5173: }
                   5174: 
                   5175: sub custom_roleprivs {
                   5176:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5177:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5178:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5179:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5180:         my ($rdummy,$roledef)=
                   5181:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5182:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5183:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5184:             if (defined($syspriv)) {
1.1043    raeburn  5185:                 if ($trest =~ /^$match_community$/) {
                   5186:                     $syspriv =~ s/bre\&S//; 
                   5187:                 }
1.567     raeburn  5188:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5189:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5190:             }
                   5191:             if ($tdomain ne '') {
                   5192:                 if (defined($dompriv)) {
                   5193:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5194:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5195:                 }
                   5196:                 if (($trest ne '') && (defined($coursepriv))) {
                   5197:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5198:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5199:                 }
                   5200:             }
                   5201:         }
                   5202:     }
                   5203: }
                   5204: 
1.678     raeburn  5205: sub group_roleprivs {
                   5206:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5207:     my $access = 1;
                   5208:     my $now = time;
                   5209:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5210:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5211:     if ($access) {
1.811     albertel 5212:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5213:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5214:     }
                   5215: }
1.567     raeburn  5216: 
                   5217: sub standard_roleprivs {
                   5218:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5219:     if (defined($pr{$trole.':s'})) {
                   5220:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5221:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5222:     }
                   5223:     if ($tdomain ne '') {
                   5224:         if (defined($pr{$trole.':d'})) {
                   5225:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5226:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5227:         }
                   5228:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5229:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5230:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5231:         }
                   5232:     }
                   5233: }
                   5234: 
                   5235: sub set_userprivs {
1.1064    raeburn  5236:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5237:     my $author=0;
                   5238:     my $adv=0;
1.678     raeburn  5239:     my %grouproles = ();
                   5240:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5241:         my @groupkeys; 
1.1000    raeburn  5242:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5243:             push(@groupkeys,$role);
                   5244:         }
                   5245:         if (ref($groups_roles) eq 'HASH') {
                   5246:             foreach my $key (keys(%{$groups_roles})) {
                   5247:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5248:                     push(@groupkeys,$key);
                   5249:                 }
                   5250:             }
                   5251:         }
                   5252:         if (@groupkeys > 0) {
                   5253:             foreach my $role (@groupkeys) {
                   5254:                 my ($trole,$area,$sec,$extendedarea);
                   5255:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5256:                     $trole = $1;
                   5257:                     $area = $2;
                   5258:                     $sec = $3;
                   5259:                     $extendedarea = $area.$sec;
                   5260:                     if (exists($$allgroups{$area})) {
                   5261:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5262:                             my $spec = $trole.'.'.$extendedarea;
                   5263:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5264:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5265:                         }
1.678     raeburn  5266:                     }
                   5267:                 }
                   5268:             }
                   5269:         }
                   5270:     }
1.800     albertel 5271:     foreach my $group (keys(%grouproles)) {
                   5272:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5273:     }
1.800     albertel 5274:     foreach my $role (keys(%{$allroles})) {
                   5275:         my %thesepriv;
1.941     raeburn  5276:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5277:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5278:             if ($item ne '') {
                   5279:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5280:                 if ($restrictions eq '') {
                   5281:                     $thesepriv{$privilege}='F';
                   5282:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5283:                     $thesepriv{$privilege}.=$restrictions;
                   5284:                 }
                   5285:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5286:             }
                   5287:         }
                   5288:         my $thesestr='';
1.1104    raeburn  5289:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5290: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5291: 	}
                   5292:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5293:     }
                   5294:     return ($author,$adv);
                   5295: }
                   5296: 
1.994     raeburn  5297: sub role_status {
1.1104    raeburn  5298:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5299:     my @pwhere = ();
                   5300:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5301:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5302:         unless (!defined($$role) || $$role eq '') {
                   5303:             $$where=join('.',@pwhere);
                   5304:             $$trolecode=$$role.'.'.$$where;
                   5305:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5306:             $$tstatus='is';
1.1104    raeburn  5307:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5308:                 $$tstatus='future';
1.1034    raeburn  5309:                 if ($$tstart<$now) {
                   5310:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5311:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5312:                             my (%allroles,%allgroups,$group_privs,
                   5313:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5314:                             my %userroles = (
                   5315:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5316:                             );
1.1064    raeburn  5317:                             @rolecodes = ('cm'); 
1.1002    raeburn  5318:                             my $spec=$$role.'.'.$$where;
                   5319:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5320:                             if ($$role =~ /^cr\//) {
                   5321:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5322:                                 push(@rolecodes,'cr');
1.1002    raeburn  5323:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5324:                                 push(@rolecodes,$$role);
1.1002    raeburn  5325:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5326:                                                     $env{'user.name'});
1.1064    raeburn  5327:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5328:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5329:                                 $group_privs = &unescape($group_privs);
                   5330:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5331:                                 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  5332:                                 &get_groups_roles($tdomain,$trest,
                   5333:                                                   \%course_roles,\@rolecodes,
                   5334:                                                   \%groups_roles);
1.1002    raeburn  5335:                             } else {
1.1064    raeburn  5336:                                 push(@rolecodes,$$role);
1.1002    raeburn  5337:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5338:                             }
1.1064    raeburn  5339:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5340:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5341:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5342:                         }
                   5343:                     }
1.1034    raeburn  5344:                     $$tstatus = 'is';
1.1002    raeburn  5345:                 }
1.994     raeburn  5346:             }
                   5347:             if ($$tend) {
1.1104    raeburn  5348:                 if ($$tend<$update) {
1.994     raeburn  5349:                     $$tstatus='expired';
                   5350:                 } elsif ($$tend<$now) {
                   5351:                     $$tstatus='will_not';
                   5352:                 }
                   5353:             }
                   5354:         }
                   5355:     }
                   5356: }
                   5357: 
1.1104    raeburn  5358: sub get_groups_roles {
                   5359:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5360:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5361:                   (ref($rolecodes) eq 'ARRAY') && 
                   5362:                   (ref($groups_roles) eq 'HASH')); 
                   5363:     if (keys(%{$cdom_courseroles}) > 0) {
                   5364:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5365:         if ($cdom ne '' && $cnum ne '') {
                   5366:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5367:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5368:                     my $crsrole = $1;
                   5369:                     my $crssec = $2;
                   5370:                     if ($crsrole =~ /^cr/) {
                   5371:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5372:                             push(@{$rolecodes},'cr');
                   5373:                         }
                   5374:                     } else {
                   5375:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5376:                             push(@{$rolecodes},$crsrole);
                   5377:                         }
                   5378:                     }
                   5379:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5380:                     if ($crssec ne '') {
                   5381:                         $rolekey .= "/$crssec";
                   5382:                     }
                   5383:                     $rolekey .= './';
                   5384:                     $groups_roles->{$rolekey} = $rolecodes;
                   5385:                 }
                   5386:             }
                   5387:         }
                   5388:     }
                   5389:     return;
                   5390: }
                   5391: 
                   5392: sub delete_env_groupprivs {
                   5393:     my ($where,$courseroles,$possroles) = @_;
                   5394:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5395:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5396:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5397:         %{$courseroles->{$udom}} =
                   5398:             &get_my_roles('','','userroles',['active'],
                   5399:                           $possroles,[$udom],1);
                   5400:     }
                   5401:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5402:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5403:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5404:             my $area = '/'.$cdom.'/'.$cnum;
                   5405:             my $privkey = "user.priv.$crsrole.$area";
                   5406:             if ($crssec ne '') {
                   5407:                 $privkey .= '/'.$crssec;
                   5408:             }
                   5409:             $privkey .= ".$area/$group";
                   5410:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5411:         }
                   5412:     }
                   5413:     return;
                   5414: }
                   5415: 
1.994     raeburn  5416: sub check_adhoc_privs {
1.1104    raeburn  5417:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5418:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5419:     my $setprivs;
1.994     raeburn  5420:     if ($env{$cckey}) {
                   5421:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5422:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5423:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5424:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5425:             $setprivs = 1;
1.994     raeburn  5426:         }
                   5427:     } else {
1.1088    raeburn  5428:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5429:         $setprivs = 1;
1.994     raeburn  5430:     }
1.1172.2.9  raeburn  5431:     return $setprivs;
1.994     raeburn  5432: }
                   5433: 
                   5434: sub set_adhoc_privileges {
                   5435: # role can be cc or ca
1.1088    raeburn  5436:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5437:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5438:     my $spec = $role.'.'.$area;
                   5439:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5440:                                   $env{'user.name'},1);
1.994     raeburn  5441:     my %ccrole = ();
                   5442:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5443:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5444:     &appenv(\%userroles,[$role,'cm']);
                   5445:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5446:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5447:         &appenv( {'request.role'        => $spec,
                   5448:                   'request.role.domain' => $dcdom,
                   5449:                   'request.course.sec'  => ''
                   5450:                  }
                   5451:                );
                   5452:         my $tadv=0;
                   5453:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5454:         &appenv({'request.role.adv'    => $tadv});
                   5455:     }
1.994     raeburn  5456: }
                   5457: 
1.12      www      5458: # --------------------------------------------------------------- get interface
                   5459: 
                   5460: sub get {
1.131     albertel 5461:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5462:    my $items='';
1.800     albertel 5463:    foreach my $item (@$storearr) {
                   5464:        $items.=&escape($item).'&';
1.191     harris41 5465:    }
1.12      www      5466:    $items=~s/\&$//;
1.620     albertel 5467:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5468:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5469:    my $uhome=&homeserver($uname,$udomain);
                   5470: 
1.133     albertel 5471:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5472:    my @pairs=split(/\&/,$rep);
1.273     albertel 5473:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5474:      return @pairs;
                   5475:    }
1.15      www      5476:    my %returnhash=();
1.42      www      5477:    my $i=0;
1.800     albertel 5478:    foreach my $item (@$storearr) {
                   5479:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5480:       $i++;
1.191     harris41 5481:    }
1.15      www      5482:    return %returnhash;
1.27      www      5483: }
                   5484: 
                   5485: # --------------------------------------------------------------- del interface
                   5486: 
                   5487: sub del {
1.133     albertel 5488:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5489:    my $items='';
1.800     albertel 5490:    foreach my $item (@$storearr) {
                   5491:        $items.=&escape($item).'&';
1.191     harris41 5492:    }
1.984     neumanie 5493: 
1.27      www      5494:    $items=~s/\&$//;
1.620     albertel 5495:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5496:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5497:    my $uhome=&homeserver($uname,$udomain);
                   5498:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5499: }
                   5500: 
                   5501: # -------------------------------------------------------------- dump interface
                   5502: 
1.1172.2.22  raeburn  5503: sub unserialize {
                   5504:     my ($rep, $escapedkeys) = @_;
                   5505: 
                   5506:     return {} if $rep =~ /^error/;
                   5507: 
                   5508:     my %returnhash=();
                   5509:     foreach my $item (split(/\&/,$rep)) {
                   5510:         my ($key, $value) = split(/=/, $item, 2);
                   5511:         $key = unescape($key) unless $escapedkeys;
                   5512:         next if $key =~ /^error: 2 /;
                   5513:         $returnhash{$key} = &thaw_unescape($value);
                   5514:     }
                   5515:     return \%returnhash;
                   5516: }
                   5517: 
                   5518: # see Lond::dump_with_regexp
                   5519: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5520: sub dump {
1.1172.2.22  raeburn  5521:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5522:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5523:     if (!$uname) { $uname=$env{'user.name'}; }
                   5524:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5525: 
1.1172.2.22  raeburn  5526:     my $reply;
                   5527:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5528:         # user is hosted on this machine
                   5529:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5530:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5531:         return %{&unserialize($reply, $escapedkeys)};
                   5532:     }
1.755     albertel 5533:     if ($regexp) {
                   5534: 	$regexp=&escape($regexp);
                   5535:     } else {
                   5536: 	$regexp='.';
                   5537:     }
1.1166    raeburn  5538:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5539:     my @pairs=split(/\&/,$rep);
                   5540:     my %returnhash=();
1.1098    foxr     5541:     if (!($rep =~ /^error/ )) {
                   5542: 	foreach my $item (@pairs) {
                   5543: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5544:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5545: 	    next if ($key =~ /^error: 2 /);
                   5546: 	    $returnhash{$key}=&thaw_unescape($value);
                   5547: 	}
1.755     albertel 5548:     }
                   5549:     return %returnhash;
1.407     www      5550: }
                   5551: 
1.1098    foxr     5552: 
1.717     albertel 5553: # --------------------------------------------------------- dumpstore interface
                   5554: 
                   5555: sub dumpstore {
                   5556:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5557:    # same as dump but keys must be escaped. They may contain colon separated
                   5558:    # lists of values that may themself contain colons (e.g. symbs).
                   5559:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5560: }
                   5561: 
1.407     www      5562: # -------------------------------------------------------------- keys interface
                   5563: 
                   5564: sub getkeys {
                   5565:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5566:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5567:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5568:    my $uhome=&homeserver($uname,$udomain);
                   5569:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5570:    my @keyarray=();
1.800     albertel 5571:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5572:       next if ($key =~ /^error: 2 /);
1.800     albertel 5573:       push(@keyarray,&unescape($key));
1.407     www      5574:    }
                   5575:    return @keyarray;
1.318     matthew  5576: }
                   5577: 
1.319     matthew  5578: # --------------------------------------------------------------- currentdump
                   5579: sub currentdump {
1.328     matthew  5580:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5581:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5582:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5583:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5584:    my $uhome = &homeserver($sname,$sdom);
                   5585:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5586:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5587:    #
1.318     matthew  5588:    my %returnhash=();
1.319     matthew  5589:    #
                   5590:    if ($rep eq "unknown_cmd") { 
                   5591:        # an old lond will not know currentdump
                   5592:        # Do a dump and make it look like a currentdump
1.822     albertel 5593:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5594:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5595:        my %hash = @tmp;
                   5596:        @tmp=();
1.424     matthew  5597:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5598:    } else {
                   5599:        my @pairs=split(/\&/,$rep);
1.800     albertel 5600:        foreach my $pair (@pairs) {
                   5601:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5602:            my ($symb,$param) = split(/:/,$key);
                   5603:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5604:                                                         &thaw_unescape($value);
1.319     matthew  5605:        }
1.191     harris41 5606:    }
1.12      www      5607:    return %returnhash;
1.424     matthew  5608: }
                   5609: 
                   5610: sub convert_dump_to_currentdump{
                   5611:     my %hash = %{shift()};
                   5612:     my %returnhash;
                   5613:     # Code ripped from lond, essentially.  The only difference
                   5614:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5615:     # we might run in to problems with parameter names =~ /^v\./
                   5616:     while (my ($key,$value) = each(%hash)) {
                   5617:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5618: 	$symb  = &unescape($symb);
                   5619: 	$param = &unescape($param);
1.424     matthew  5620:         next if ($v eq 'version' || $symb eq 'keys');
                   5621:         next if (exists($returnhash{$symb}) &&
                   5622:                  exists($returnhash{$symb}->{$param}) &&
                   5623:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5624:         $returnhash{$symb}->{$param}=$value;
                   5625:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5626:     }
                   5627:     #
                   5628:     # Remove all of the keys in the hashes which keep track of
                   5629:     # the version of the parameter.
                   5630:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5631:         # use a foreach because we are going to delete from the hash.
                   5632:         foreach my $key (keys(%$param_hash)) {
                   5633:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5634:         }
                   5635:     }
                   5636:     return \%returnhash;
1.12      www      5637: }
                   5638: 
1.627     albertel 5639: # ------------------------------------------------------ critical inc interface
                   5640: 
                   5641: sub cinc {
                   5642:     return &inc(@_,'critical');
                   5643: }
                   5644: 
1.449     matthew  5645: # --------------------------------------------------------------- inc interface
                   5646: 
                   5647: sub inc {
1.627     albertel 5648:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5649:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5650:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5651:     my $uhome=&homeserver($uname,$udomain);
                   5652:     my $items='';
                   5653:     if (! ref($store)) {
                   5654:         # got a single value, so use that instead
                   5655:         $items = &escape($store).'=&';
                   5656:     } elsif (ref($store) eq 'SCALAR') {
                   5657:         $items = &escape($$store).'=&';        
                   5658:     } elsif (ref($store) eq 'ARRAY') {
                   5659:         $items = join('=&',map {&escape($_);} @{$store});
                   5660:     } elsif (ref($store) eq 'HASH') {
                   5661:         while (my($key,$value) = each(%{$store})) {
                   5662:             $items.= &escape($key).'='.&escape($value).'&';
                   5663:         }
                   5664:     }
                   5665:     $items=~s/\&$//;
1.627     albertel 5666:     if ($critical) {
                   5667: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5668:     } else {
                   5669: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5670:     }
1.449     matthew  5671: }
                   5672: 
1.12      www      5673: # --------------------------------------------------------------- put interface
                   5674: 
                   5675: sub put {
1.134     albertel 5676:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5677:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5678:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5679:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5680:    my $items='';
1.800     albertel 5681:    foreach my $item (keys(%$storehash)) {
                   5682:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5683:    }
1.12      www      5684:    $items=~s/\&$//;
1.134     albertel 5685:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5686: }
                   5687: 
1.631     albertel 5688: # ------------------------------------------------------------ newput interface
                   5689: 
                   5690: sub newput {
                   5691:    my ($namespace,$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 $items='';
                   5696:    foreach my $key (keys(%$storehash)) {
                   5697:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5698:    }
                   5699:    $items=~s/\&$//;
                   5700:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5701: }
                   5702: 
                   5703: # ---------------------------------------------------------  putstore interface
                   5704: 
1.524     raeburn  5705: sub putstore {
1.715     albertel 5706:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5707:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5708:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5709:    my $uhome=&homeserver($uname,$udomain);
                   5710:    my $items='';
1.715     albertel 5711:    foreach my $key (keys(%$storehash)) {
                   5712:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5713:    }
1.715     albertel 5714:    $items=~s/\&$//;
1.716     albertel 5715:    my $esc_symb=&escape($symb);
                   5716:    my $esc_v=&escape($version);
1.715     albertel 5717:    my $reply =
1.716     albertel 5718:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5719: 	      $uhome);
                   5720:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5721:        # gfall back to way things use to be done
1.715     albertel 5722:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5723: 			    $uname);
1.524     raeburn  5724:    }
1.715     albertel 5725:    return $reply;
                   5726: }
                   5727: 
                   5728: sub old_putstore {
1.716     albertel 5729:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5730:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5731:     if (!$uname) { $uname=$env{'user.name'}; }
                   5732:     my $uhome=&homeserver($uname,$udomain);
                   5733:     my %newstorehash;
1.800     albertel 5734:     foreach my $item (keys(%$storehash)) {
                   5735: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5736: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5737:     }
                   5738:     my $items='';
                   5739:     my %allitems = ();
1.800     albertel 5740:     foreach my $item (keys(%newstorehash)) {
                   5741: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5742: 	    my $key = $1.':keys:'.$2;
                   5743: 	    $allitems{$key} .= $3.':';
                   5744: 	}
1.800     albertel 5745: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5746:     }
1.800     albertel 5747:     foreach my $item (keys(%allitems)) {
                   5748: 	$allitems{$item} =~ s/\:$//;
                   5749: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5750:     }
                   5751:     $items=~s/\&$//;
                   5752:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5753: }
                   5754: 
1.47      www      5755: # ------------------------------------------------------ critical put interface
                   5756: 
                   5757: sub cput {
1.134     albertel 5758:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5759:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5760:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5761:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5762:    my $items='';
1.800     albertel 5763:    foreach my $item (keys(%$storehash)) {
                   5764:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5765:    }
1.47      www      5766:    $items=~s/\&$//;
1.134     albertel 5767:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5768: }
                   5769: 
                   5770: # -------------------------------------------------------------- eget interface
                   5771: 
                   5772: sub eget {
1.133     albertel 5773:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5774:    my $items='';
1.800     albertel 5775:    foreach my $item (@$storearr) {
                   5776:        $items.=&escape($item).'&';
1.191     harris41 5777:    }
1.12      www      5778:    $items=~s/\&$//;
1.620     albertel 5779:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5780:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5781:    my $uhome=&homeserver($uname,$udomain);
                   5782:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5783:    my @pairs=split(/\&/,$rep);
                   5784:    my %returnhash=();
1.42      www      5785:    my $i=0;
1.800     albertel 5786:    foreach my $item (@$storearr) {
                   5787:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5788:       $i++;
1.191     harris41 5789:    }
1.12      www      5790:    return %returnhash;
                   5791: }
                   5792: 
1.667     albertel 5793: # ------------------------------------------------------------ tmpput interface
                   5794: sub tmpput {
1.802     raeburn  5795:     my ($storehash,$server,$context)=@_;
1.667     albertel 5796:     my $items='';
1.800     albertel 5797:     foreach my $item (keys(%$storehash)) {
                   5798: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5799:     }
                   5800:     $items=~s/\&$//;
1.802     raeburn  5801:     if (defined($context)) {
                   5802:         $items .= ':'.&escape($context);
                   5803:     }
1.667     albertel 5804:     return &reply("tmpput:$items",$server);
                   5805: }
                   5806: 
                   5807: # ------------------------------------------------------------ tmpget interface
                   5808: sub tmpget {
1.688     albertel 5809:     my ($token,$server)=@_;
                   5810:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5811:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5812:     my %returnhash;
                   5813:     foreach my $item (split(/\&/,$rep)) {
                   5814: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5815:         next if ($key =~ /^error: 2 /);
1.667     albertel 5816: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5817:     }
                   5818:     return %returnhash;
                   5819: }
                   5820: 
1.1113    raeburn  5821: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5822: sub tmpdel {
                   5823:     my ($token,$server)=@_;
                   5824:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5825:     return &reply("tmpdel:$token",$server);
                   5826: }
                   5827: 
1.1172.2.13  raeburn  5828: # ------------------------------------------------------------ get_timebased_id
                   5829: 
                   5830: sub get_timebased_id {
                   5831:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5832:         $maxtries) = @_;
                   5833:     my ($newid,$error,$dellock);
                   5834:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5835:         return ('','ok','invalid call to get suffix');
                   5836:     }
                   5837: 
                   5838: # set defaults for any optional args for which values were not supplied
                   5839:     if ($who eq '') {
                   5840:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5841:     }
                   5842:     if (!$locktries) {
                   5843:         $locktries = 3;
                   5844:     }
                   5845:     if (!$maxtries) {
                   5846:         $maxtries = 10;
                   5847:     }
                   5848: 
                   5849:     if (($cdom eq '') || ($cnum eq '')) {
                   5850:         if ($env{'request.course.id'}) {
                   5851:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5852:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5853:         }
                   5854:         if (($cdom eq '') || ($cnum eq '')) {
                   5855:             return ('','ok','call to get suffix not in course context');
                   5856:         }
                   5857:     }
                   5858: 
                   5859: # construct locking item
                   5860:     my $lockhash = {
                   5861:                       $prefix."\0".'locked_'.$keyid => $who,
                   5862:                    };
                   5863:     my $tries = 0;
                   5864: 
                   5865: # attempt to get lock on nohist_$namespace file
                   5866:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5867:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5868:         $tries ++;
                   5869:         sleep 1;
                   5870:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5871:     }
                   5872: 
                   5873: # attempt to get unique identifier, based on current timestamp
                   5874:     if ($gotlock eq 'ok') {
                   5875:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5876:         my $id = time;
                   5877:         $newid = $id;
                   5878:         my $idtries = 0;
                   5879:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5880:             if ($idtype eq 'concat') {
                   5881:                 $newid = $id.$idtries;
                   5882:             } else {
                   5883:                 $newid ++;
                   5884:             }
                   5885:             $idtries ++;
                   5886:         }
                   5887:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5888:             my %new_item =  (
                   5889:                               $prefix."\0".$newid => $who,
                   5890:                             );
                   5891:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5892:                                                  $cdom,$cnum);
                   5893:             if ($putresult ne 'ok') {
                   5894:                 undef($newid);
                   5895:                 $error = 'error saving new item: '.$putresult;
                   5896:             }
                   5897:         } else {
                   5898:              $error = ('error: no unique suffix available for the new item ');
                   5899:         }
                   5900: #  remove lock
                   5901:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5902:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5903:     } else {
                   5904:         $error = "error: could not obtain lockfile\n";
                   5905:         $dellock = 'ok';
                   5906:     }
                   5907:     return ($newid,$dellock,$error);
                   5908: }
                   5909: 
1.765     albertel 5910: # -------------------------------------------------- portfolio access checking
                   5911: 
                   5912: sub portfolio_access {
1.766     albertel 5913:     my ($requrl) = @_;
1.765     albertel 5914:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5915:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5916:     if ($result) {
                   5917:         my %setters;
                   5918:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5919:             my ($startblock,$endblock) =
                   5920:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5921:             if ($startblock && $endblock) {
                   5922:                 return 'B';
                   5923:             }
                   5924:         } else {
                   5925:             my ($startblock,$endblock) =
                   5926:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5927:             if ($startblock && $endblock) {
                   5928:                 return 'B';
                   5929:             }
                   5930:         }
                   5931:     }
1.765     albertel 5932:     if ($result eq 'ok') {
1.766     albertel 5933:        return 'F';
1.765     albertel 5934:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5935:        return 'A';
1.765     albertel 5936:     }
1.766     albertel 5937:     return '';
1.765     albertel 5938: }
                   5939: 
                   5940: sub get_portfolio_access {
1.767     albertel 5941:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5942: 
                   5943:     if (!ref($access_hash)) {
                   5944: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5945: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5946: 						   $file_name);
                   5947: 	$access_hash = $access_controls{$file_name};
                   5948:     }
                   5949: 
1.765     albertel 5950:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5951:     my $now = time;
                   5952:     if (ref($access_hash) eq 'HASH') {
                   5953:         foreach my $key (keys(%{$access_hash})) {
                   5954:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5955:             if ($start > $now) {
                   5956:                 next;
                   5957:             }
                   5958:             if ($end && $end<$now) {
                   5959:                 next;
                   5960:             }
                   5961:             if ($scope eq 'public') {
                   5962:                 $public = $key;
                   5963:                 last;
                   5964:             } elsif ($scope eq 'guest') {
                   5965:                 $guest = $key;
                   5966:             } elsif ($scope eq 'domains') {
                   5967:                 push(@domains,$key);
                   5968:             } elsif ($scope eq 'users') {
                   5969:                 push(@users,$key);
                   5970:             } elsif ($scope eq 'course') {
                   5971:                 push(@courses,$key);
                   5972:             } elsif ($scope eq 'group') {
                   5973:                 push(@groups,$key);
                   5974:             }
                   5975:         }
                   5976:         if ($public) {
                   5977:             return 'ok';
                   5978:         }
                   5979:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5980:             if ($guest) {
                   5981:                 return $guest;
                   5982:             }
                   5983:         } else {
                   5984:             if (@domains > 0) {
                   5985:                 foreach my $domkey (@domains) {
                   5986:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5987:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5988:                             return 'ok';
                   5989:                         }
                   5990:                     }
                   5991:                 }
                   5992:             }
                   5993:             if (@users > 0) {
                   5994:                 foreach my $userkey (@users) {
1.865     raeburn  5995:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5996:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5997:                             if (ref($item) eq 'HASH') {
                   5998:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5999:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6000:                                     return 'ok';
                   6001:                                 }
                   6002:                             }
                   6003:                         }
                   6004:                     } 
1.765     albertel 6005:                 }
                   6006:             }
                   6007:             my %roleshash;
                   6008:             my @courses_and_groups = @courses;
                   6009:             push(@courses_and_groups,@groups); 
                   6010:             if (@courses_and_groups > 0) {
                   6011:                 my (%allgroups,%allroles); 
                   6012:                 my ($start,$end,$role,$sec,$group);
                   6013:                 foreach my $envkey (%env) {
1.1060    raeburn  6014:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6015:                         my $cid = $2.'_'.$3; 
                   6016:                         if ($1 eq 'gr') {
                   6017:                             $group = $4;
                   6018:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6019:                         } else {
                   6020:                             if ($4 eq '') {
                   6021:                                 $sec = 'none';
                   6022:                             } else {
                   6023:                                 $sec = $4;
                   6024:                             }
                   6025:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6026:                         }
1.811     albertel 6027:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6028:                         my $cid = $2.'_'.$3;
                   6029:                         if ($4 eq '') {
                   6030:                             $sec = 'none';
                   6031:                         } else {
                   6032:                             $sec = $4;
                   6033:                         }
                   6034:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6035:                     }
                   6036:                 }
                   6037:                 if (keys(%allroles) == 0) {
                   6038:                     return;
                   6039:                 }
                   6040:                 foreach my $key (@courses_and_groups) {
                   6041:                     my %content = %{$$access_hash{$key}};
                   6042:                     my $cnum = $content{'number'};
                   6043:                     my $cdom = $content{'domain'};
                   6044:                     my $cid = $cdom.'_'.$cnum;
                   6045:                     if (!exists($allroles{$cid})) {
                   6046:                         next;
                   6047:                     }    
                   6048:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6049:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6050:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6051:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6052:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6053:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6054:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6055:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6056:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6057:                                         if (grep/^all$/,@sections) {
                   6058:                                             return 'ok';
                   6059:                                         } else {
                   6060:                                             if (grep/^$sec$/,@sections) {
                   6061:                                                 return 'ok';
                   6062:                                             }
                   6063:                                         }
                   6064:                                     }
                   6065:                                 }
                   6066:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6067:                                     if (grep/^none$/,@groups) {
                   6068:                                         return 'ok';
                   6069:                                     }
                   6070:                                 } else {
                   6071:                                     if (grep/^all$/,@groups) {
                   6072:                                         return 'ok';
                   6073:                                     } 
                   6074:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6075:                                         if (grep/^$group$/,@groups) {
                   6076:                                             return 'ok';
                   6077:                                         }
                   6078:                                     }
                   6079:                                 } 
                   6080:                             }
                   6081:                         }
                   6082:                     }
                   6083:                 }
                   6084:             }
                   6085:             if ($guest) {
                   6086:                 return $guest;
                   6087:             }
                   6088:         }
                   6089:     }
                   6090:     return;
                   6091: }
                   6092: 
                   6093: sub course_group_datechecker {
                   6094:     my ($dates,$now,$status) = @_;
                   6095:     my ($start,$end) = split(/\./,$dates);
                   6096:     if (!$start && !$end) {
                   6097:         return 'ok';
                   6098:     }
                   6099:     if (grep/^active$/,@{$status}) {
                   6100:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6101:             return 'ok';
                   6102:         }
                   6103:     }
                   6104:     if (grep/^previous$/,@{$status}) {
                   6105:         if ($end > $now ) {
                   6106:             return 'ok';
                   6107:         }
                   6108:     }
                   6109:     if (grep/^future$/,@{$status}) {
                   6110:         if ($start > $now) {
                   6111:             return 'ok';
                   6112:         }
                   6113:     }
                   6114:     return; 
                   6115: }
                   6116: 
                   6117: sub parse_portfolio_url {
                   6118:     my ($url) = @_;
                   6119: 
                   6120:     my ($type,$udom,$unum,$group,$file_name);
                   6121:     
1.823     albertel 6122:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6123: 	$type = 1;
                   6124:         $udom = $1;
                   6125:         $unum = $2;
                   6126:         $file_name = $3;
1.823     albertel 6127:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6128: 	$type = 2;
                   6129:         $udom = $1;
                   6130:         $unum = $2;
                   6131:         $group = $3;
                   6132:         $file_name = $3.'/'.$4;
                   6133:     }
                   6134:     if (wantarray) {
                   6135: 	return ($type,$udom,$unum,$file_name,$group);
                   6136:     }
                   6137:     return $type;
                   6138: }
                   6139: 
                   6140: sub is_portfolio_url {
                   6141:     my ($url) = @_;
                   6142:     return scalar(&parse_portfolio_url($url));
                   6143: }
                   6144: 
1.798     raeburn  6145: sub is_portfolio_file {
                   6146:     my ($file) = @_;
1.820     raeburn  6147:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6148:         return 1;
                   6149:     }
                   6150:     return;
                   6151: }
                   6152: 
1.976     raeburn  6153: sub usertools_access {
1.1084    raeburn  6154:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6155:     my ($access,%tools);
                   6156:     if ($context eq '') {
                   6157:         $context = 'tools';
                   6158:     }
                   6159:     if ($context eq 'requestcourses') {
                   6160:         %tools = (
                   6161:                       official   => 1,
                   6162:                       unofficial => 1,
1.1006    raeburn  6163:                       community  => 1,
1.985     raeburn  6164:                  );
1.1172.2.9  raeburn  6165:     } elsif ($context eq 'requestauthor') {
                   6166:         %tools = (
                   6167:                       requestauthor => 1,
                   6168:                  );
1.985     raeburn  6169:     } else {
                   6170:         %tools = (
                   6171:                       aboutme   => 1,
                   6172:                       blog      => 1,
1.1172.2.6  raeburn  6173:                       webdav    => 1,
1.985     raeburn  6174:                       portfolio => 1,
                   6175:                  );
                   6176:     }
1.976     raeburn  6177:     return if (!defined($tools{$tool}));
                   6178: 
                   6179:     if ((!defined($udom)) || (!defined($uname))) {
                   6180:         $udom = $env{'user.domain'};
                   6181:         $uname = $env{'user.name'};
                   6182:     }
                   6183: 
1.978     raeburn  6184:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6185:         if ($action ne 'reload') {
1.985     raeburn  6186:             if ($context eq 'requestcourses') {
                   6187:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6188:             } elsif ($context eq 'requestauthor') {
                   6189:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6190:             } else {
                   6191:                 return $env{'environment.availabletools.'.$tool};
                   6192:             }
                   6193:         }
1.976     raeburn  6194:     }
                   6195: 
1.1172.2.9  raeburn  6196:     my ($toolstatus,$inststatus,$envkey);
                   6197:     if ($context eq 'requestauthor') {
                   6198:         $envkey = $context;
                   6199:     } else {
                   6200:         $envkey = $context.'.'.$tool;
                   6201:     }
1.976     raeburn  6202: 
1.985     raeburn  6203:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6204:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6205:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6206:         $inststatus = $env{'environment.inststatus'};
                   6207:     } else {
1.1084    raeburn  6208:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6209:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6210:             $inststatus = $userenvref->{'inststatus'};
                   6211:         } else {
1.1172.2.9  raeburn  6212:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6213:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6214:             $inststatus = $userenv{'inststatus'};
                   6215:         }
1.976     raeburn  6216:     }
                   6217: 
                   6218:     if ($toolstatus ne '') {
                   6219:         if ($toolstatus) {
                   6220:             $access = 1;
                   6221:         } else {
                   6222:             $access = 0;
                   6223:         }
                   6224:         return $access;
                   6225:     }
                   6226: 
1.1084    raeburn  6227:     my ($is_adv,%domdef);
                   6228:     if (ref($is_advref) eq 'HASH') {
                   6229:         $is_adv = $is_advref->{'is_adv'};
                   6230:     } else {
                   6231:         $is_adv = &is_advanced_user($udom,$uname);
                   6232:     }
                   6233:     if (ref($domdefref) eq 'HASH') {
                   6234:         %domdef = %{$domdefref};
                   6235:     } else {
                   6236:         %domdef = &get_domain_defaults($udom);
                   6237:     }
1.976     raeburn  6238:     if (ref($domdef{$tool}) eq 'HASH') {
                   6239:         if ($is_adv) {
                   6240:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6241:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6242:                     $access = 1;
                   6243:                 } else {
                   6244:                     $access = 0;
                   6245:                 }
                   6246:                 return $access;
                   6247:             }
                   6248:         }
                   6249:         if ($inststatus ne '') {
                   6250:             my ($hasaccess,$hasnoaccess);
                   6251:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6252:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6253:                     if ($domdef{$tool}{$affiliation}) {
                   6254:                         $hasaccess = 1;
                   6255:                     } else {
                   6256:                         $hasnoaccess = 1;
                   6257:                     }
                   6258:                 }
                   6259:             }
                   6260:             if ($hasaccess || $hasnoaccess) {
                   6261:                 if ($hasaccess) {
                   6262:                     $access = 1;
                   6263:                 } elsif ($hasnoaccess) {
                   6264:                     $access = 0; 
                   6265:                 }
                   6266:                 return $access;
                   6267:             }
                   6268:         } else {
                   6269:             if ($domdef{$tool}{'default'} ne '') {
                   6270:                 if ($domdef{$tool}{'default'}) {
                   6271:                     $access = 1;
                   6272:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6273:                     $access = 0;
                   6274:                 }
                   6275:                 return $access;
                   6276:             }
                   6277:         }
                   6278:     } else {
1.1172.2.6  raeburn  6279:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6280:             $access = 1;
                   6281:         } else {
                   6282:             $access = 0;
                   6283:         }
1.976     raeburn  6284:         return $access;
                   6285:     }
                   6286: }
                   6287: 
1.1050    raeburn  6288: sub is_course_owner {
                   6289:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6290:     if (($udom eq '') || ($uname eq '')) {
                   6291:         $udom = $env{'user.domain'};
                   6292:         $uname = $env{'user.name'};
                   6293:     }
                   6294:     unless (($udom eq '') || ($uname eq '')) {
                   6295:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6296:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6297:                 return 1;
                   6298:             } else {
                   6299:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6300:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6301:                     return 1;
                   6302:                 }
                   6303:             }
                   6304:         }
                   6305:     }
                   6306:     return;
                   6307: }
                   6308: 
1.976     raeburn  6309: sub is_advanced_user {
                   6310:     my ($udom,$uname) = @_;
1.1085    raeburn  6311:     if ($udom ne '' && $uname ne '') {
                   6312:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6313:             if (wantarray) {
                   6314:                 return ($env{'user.adv'},$env{'user.author'});
                   6315:             } else {
                   6316:                 return $env{'user.adv'};
                   6317:             }
1.1085    raeburn  6318:         }
                   6319:     }
1.976     raeburn  6320:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6321:     my %allroles;
1.1128    raeburn  6322:     my ($is_adv,$is_author);
1.976     raeburn  6323:     foreach my $role (keys(%roleshash)) {
                   6324:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6325:         my $area = '/'.$tdomain.'/'.$trest;
                   6326:         if ($sec ne '') {
                   6327:             $area .= '/'.$sec;
                   6328:         }
                   6329:         if (($area ne '') && ($trole ne '')) {
                   6330:             my $spec=$trole.'.'.$area;
                   6331:             if ($trole =~ /^cr\//) {
                   6332:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6333:             } elsif ($trole ne 'gr') {
                   6334:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6335:             }
1.1128    raeburn  6336:             if ($trole eq 'au') {
                   6337:                 $is_author = 1;
                   6338:             }
1.976     raeburn  6339:         }
                   6340:     }
                   6341:     foreach my $role (keys(%allroles)) {
                   6342:         last if ($is_adv);
                   6343:         foreach my $item (split(/:/,$allroles{$role})) {
                   6344:             if ($item ne '') {
                   6345:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6346:                 if ($privilege eq 'adv') {
                   6347:                     $is_adv = 1;
                   6348:                     last;
                   6349:                 }
                   6350:             }
                   6351:         }
                   6352:     }
1.1128    raeburn  6353:     if (wantarray) {
                   6354:         return ($is_adv,$is_author);
                   6355:     }
1.976     raeburn  6356:     return $is_adv;
                   6357: }
1.798     raeburn  6358: 
1.1035    raeburn  6359: sub check_can_request {
1.1036    raeburn  6360:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6361:     my $canreq = 0;
                   6362:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6363:     my @options = ('approval','validate','autolimit');
                   6364:     my $optregex = join('|',@options);
                   6365:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6366:         foreach my $type (@{$types}) {
                   6367:             if (&usertools_access($env{'user.name'},
                   6368:                                   $env{'user.domain'},
                   6369:                                   $type,undef,'requestcourses')) {
                   6370:                 $canreq ++;
1.1036    raeburn  6371:                 if (ref($request_domains) eq 'HASH') {
                   6372:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6373:                 }
1.1035    raeburn  6374:                 if ($dom eq $env{'user.domain'}) {
                   6375:                     $can_request->{$type} = 1;
                   6376:                 }
                   6377:             }
                   6378:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6379:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6380:                 if (@curr > 0) {
1.1036    raeburn  6381:                     foreach my $item (@curr) {
                   6382:                         if (ref($request_domains) eq 'HASH') {
                   6383:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6384:                             if ($otherdom ne '') {
                   6385:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6386:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6387:                                         push(@{$request_domains->{$type}},$otherdom);
                   6388:                                     }
                   6389:                                 } else {
                   6390:                                     push(@{$request_domains->{$type}},$otherdom);
                   6391:                                 }
                   6392:                             }
                   6393:                         }
                   6394:                     }
                   6395:                     unless($dom eq $env{'user.domain'}) {
                   6396:                         $canreq ++;
1.1035    raeburn  6397:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6398:                             $can_request->{$type} = 1;
                   6399:                         }
                   6400:                     }
                   6401:                 }
                   6402:             }
                   6403:         }
                   6404:     }
                   6405:     return $canreq;
                   6406: }
                   6407: 
1.341     www      6408: # ---------------------------------------------- Custom access rule evaluation
                   6409: 
                   6410: sub customaccess {
                   6411:     my ($priv,$uri)=@_;
1.807     albertel 6412:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6413:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6414:     $udom = &LONCAPA::clean_domain($udom);
                   6415:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6416:     my $access=0;
1.800     albertel 6417:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6418: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6419: 	if ($type eq 'user') {
                   6420: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6421: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6422: 		if ($tdom) {
                   6423: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6424: 		}
1.896     albertel 6425: 		if ($tuname) {
                   6426: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6427: 		}
                   6428: 		$access=($effect eq 'allow');
                   6429: 		last;
                   6430: 	    }
                   6431: 	} else {
                   6432: 	    if ($role) {
                   6433: 		if ($role ne $urole) { next; }
                   6434: 	    }
                   6435: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6436: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6437: 		if ($tdom) {
                   6438: 		    if ($tdom ne $udom) { next; }
                   6439: 		}
                   6440: 		if ($tcrs) {
                   6441: 		    if ($tcrs ne $ucrs) { next; }
                   6442: 		}
                   6443: 		if ($tsec) {
                   6444: 		    if ($tsec ne $usec) { next; }
                   6445: 		}
                   6446: 		$access=($effect eq 'allow');
                   6447: 		last;
                   6448: 	    }
                   6449: 	    if ($realm eq '' && $role eq '') {
                   6450: 		$access=($effect eq 'allow');
                   6451: 	    }
1.402     bowersj2 6452: 	}
1.341     www      6453:     }
                   6454:     return $access;
                   6455: }
                   6456: 
1.103     harris41 6457: # ------------------------------------------------- Check for a user privilege
1.12      www      6458: 
                   6459: sub allowed {
1.810     raeburn  6460:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6461:     my $ver_orguri=$uri;
1.439     www      6462:     $uri=&deversion($uri);
1.152     www      6463:     my $orguri=$uri;
1.52      www      6464:     $uri=&declutter($uri);
1.809     raeburn  6465: 
1.810     raeburn  6466:     if ($priv eq 'evb') {
                   6467: # Evade communication block restrictions for specified role in a course
                   6468:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6469:             return $1;
                   6470:         } else {
                   6471:             return;
                   6472:         }
                   6473:     }
                   6474: 
1.620     albertel 6475:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6476: # Free bre access to adm and meta resources
1.775     albertel 6477:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6478: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6479: 	&& ($priv eq 'bre')) {
1.14      www      6480: 	return 'F';
1.159     www      6481:     }
                   6482: 
1.545     banghart 6483: # Free bre access to user's own portfolio contents
1.714     raeburn  6484:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6485:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6486: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6487:         my %setters;
                   6488:         my ($startblock,$endblock) = 
                   6489:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6490:         if ($startblock && $endblock) {
                   6491:             return 'B';
                   6492:         } else {
                   6493:             return 'F';
                   6494:         }
1.545     banghart 6495:     }
                   6496: 
1.762     raeburn  6497: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6498:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6499:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6500:         if (exists($env{'request.course.id'})) {
                   6501:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6502:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6503:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6504:                 my $courseprivid=$env{'request.course.id'};
                   6505:                 $courseprivid=~s/\_/\//;
                   6506:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6507:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6508:                     return $1; 
1.762     raeburn  6509:                 } else {
                   6510:                     if ($env{'request.course.sec'}) {
                   6511:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6512:                     }
                   6513:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6514:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6515:                         return $2;
                   6516:                     }
1.714     raeburn  6517:                 }
                   6518:             }
                   6519:         }
                   6520:     }
                   6521: 
1.159     www      6522: # Free bre to public access
                   6523: 
                   6524:     if ($priv eq 'bre') {
1.238     www      6525:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6526: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6527:            return 'F'; 
                   6528:         }
1.238     www      6529:         if ($copyright eq 'priv') {
                   6530:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6531: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6532: 		return '';
                   6533:             }
                   6534:         }
                   6535:         if ($copyright eq 'domain') {
                   6536:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6537: 	    unless (($env{'user.domain'} eq $1) ||
                   6538:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6539: 		return '';
                   6540:             }
1.262     matthew  6541:         }
1.620     albertel 6542:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6543:             # Library role, so allow browsing of resources in this domain.
                   6544:             return 'F';
1.238     www      6545:         }
1.341     www      6546:         if ($copyright eq 'custom') {
                   6547: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6548:         }
1.14      www      6549:     }
1.264     matthew  6550:     # Domain coordinator is trying to create a course
1.620     albertel 6551:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6552:         # uri is the requested domain in this case.
                   6553:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6554:         # a role of dc for the domain in question.
1.620     albertel 6555:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6556:     }
1.29      www      6557: 
1.52      www      6558:     my $thisallowed='';
                   6559:     my $statecond=0;
                   6560:     my $courseprivid='';
                   6561: 
1.1039    raeburn  6562:     my $ownaccess;
1.1043    raeburn  6563:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6564:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6565:         if ($uri eq '') {
                   6566:             $ownaccess = 1;
                   6567:         } else {
                   6568:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6569:                 my $udom = $env{'user.domain'};
                   6570:                 my $uname = $env{'user.name'};
                   6571:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6572:                     $ownaccess = 1;
1.1040    raeburn  6573:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6574:                     unless ($uri =~ m{\.\./}) {
                   6575:                         $ownaccess = 1;
                   6576:                     }
                   6577:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6578:                     my $now = time;
                   6579:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6580:                         my $adom = $1;
                   6581:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6582:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6583:                                 my ($start,$end) = split('.',$env{$key});
                   6584:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6585:                                     $ownaccess = 1;
                   6586:                                     last;
                   6587:                                 }
                   6588:                             }
                   6589:                         }
                   6590:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6591:                         my $adom = $1;
                   6592:                         my $aname = $2;
1.1042    raeburn  6593:                         foreach my $role ('ca','aa') { 
                   6594:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6595:                                 my ($start,$end) =
                   6596:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6597:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6598:                                     $ownaccess = 1;
                   6599:                                     last;
                   6600:                                 }
1.1039    raeburn  6601:                             }
                   6602:                         }
                   6603:                     }
                   6604:                 }
                   6605:             }
                   6606:         }
                   6607:     }
                   6608: 
1.52      www      6609: # Course
                   6610: 
1.620     albertel 6611:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6612:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6613:             $thisallowed.=$1;
                   6614:         }
1.52      www      6615:     }
1.29      www      6616: 
1.52      www      6617: # Domain
                   6618: 
1.620     albertel 6619:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6620:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6621:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6622:             $thisallowed.=$1;
                   6623:         }
1.12      www      6624:     }
1.52      www      6625: 
1.1141    raeburn  6626: # User who is not author or co-author might still be able to edit
                   6627: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6628:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6629:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6630:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6631:             $thisallowed.=$1;
                   6632:         }
                   6633:     }
                   6634: 
1.52      www      6635: # Course: uri itself is a course
1.66      www      6636:     my $courseuri=$uri;
                   6637:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6638:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6639: 
1.620     albertel 6640:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6641:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6642:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6643:             $thisallowed.=$1;
                   6644:         }
1.12      www      6645:     }
1.29      www      6646: 
1.665     albertel 6647: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6648: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6649:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6650: 	$thisallowed='';
1.671     raeburn  6651:         my ($match)=&is_on_map($uri);
                   6652:         if ($match) {
                   6653:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6654:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6655:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6656:                 if (@blockers > 0) {
                   6657:                     $thisallowed = 'B';
                   6658:                 } else {
                   6659:                     $thisallowed.=$1;
                   6660:                 }
1.671     raeburn  6661:             }
                   6662:         } else {
1.705     albertel 6663:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6664:             if ($refuri) {
                   6665:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6666:                     $thisallowed='F';
1.671     raeburn  6667:                 } else {
                   6668:                     $refuri=&declutter($refuri);
                   6669:                     my ($match) = &is_on_map($refuri);
                   6670:                     if ($match) {
1.1162    raeburn  6671:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6672:                         if (@blockers > 0) {
                   6673:                             $thisallowed = 'B';
                   6674:                         } else {
                   6675:                             $thisallowed='F';
                   6676:                         }
1.671     raeburn  6677:                     }
1.669     raeburn  6678:                 }
1.671     raeburn  6679:             }
                   6680:         }
1.314     www      6681:     }
1.492     albertel 6682: 
1.766     albertel 6683:     if ($priv eq 'bre'
                   6684: 	&& $thisallowed ne 'F' 
                   6685: 	&& $thisallowed ne '2'
                   6686: 	&& &is_portfolio_url($uri)) {
                   6687: 	$thisallowed = &portfolio_access($uri);
                   6688:     }
                   6689:     
1.52      www      6690: # Full access at system, domain or course-wide level? Exit.
1.29      www      6691:     if ($thisallowed=~/F/) {
                   6692: 	return 'F';
                   6693:     }
                   6694: 
1.52      www      6695: # If this is generating or modifying users, exit with special codes
1.29      www      6696: 
1.643     www      6697:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6698: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6699: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6700: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6701: 	    unless ($auname) { return $thisallowed; }
                   6702: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6703: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6704: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6705: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6706: 	}
1.52      www      6707: 	return $thisallowed;
                   6708:     }
                   6709: #
1.103     harris41 6710: # Gathered so far: system, domain and course wide privileges
1.52      www      6711: #
                   6712: # Course: See if uri or referer is an individual resource that is part of 
                   6713: # the course
                   6714: 
1.620     albertel 6715:     if ($env{'request.course.id'}) {
1.232     www      6716: 
1.620     albertel 6717:        $courseprivid=$env{'request.course.id'};
                   6718:        if ($env{'request.course.sec'}) {
                   6719:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6720:        }
                   6721:        $courseprivid=~s/\_/\//;
                   6722:        my $checkreferer=1;
1.232     www      6723:        my ($match,$cond)=&is_on_map($uri);
                   6724:        if ($match) {
                   6725:            $statecond=$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,$uri);
                   6731:                    if (@blockers > 0) {
                   6732:                        $thisallowed = 'B';
                   6733:                    } else {
                   6734:                        $thisallowed.=$value;
                   6735:                    }
                   6736:                } else {
                   6737:                    $thisallowed.=$value;
                   6738:                }
1.52      www      6739:                $checkreferer=0;
                   6740:            }
1.29      www      6741:        }
1.83      www      6742:        
1.148     www      6743:        if ($checkreferer) {
1.620     albertel 6744: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6745:             unless ($refuri) {
1.800     albertel 6746:                 foreach my $key (keys(%env)) {
                   6747: 		    if ($key=~/^httpref\..*\*/) {
                   6748: 			my $pattern=$key;
1.156     www      6749:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6750:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6751:                         $pattern=~s/\//\\\//g;
1.152     www      6752:                         if ($orguri=~/$pattern/) {
1.800     albertel 6753: 			    $refuri=$env{$key};
1.148     www      6754:                         }
                   6755:                     }
1.191     harris41 6756:                 }
1.148     www      6757:             }
1.232     www      6758: 
1.148     www      6759:          if ($refuri) { 
1.152     www      6760: 	  $refuri=&declutter($refuri);
1.232     www      6761:           my ($match,$cond)=&is_on_map($refuri);
                   6762:             if ($match) {
                   6763:               my $refstatecond=$cond;
1.620     albertel 6764:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6765:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6766:                   my $value = $1;
                   6767:                   if ($priv eq 'bre') {
                   6768:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6769:                       if (@blockers > 0) {
                   6770:                           $thisallowed = 'B';
                   6771:                       } else {
                   6772:                           $thisallowed.=$value;
                   6773:                       }
                   6774:                   } else {
                   6775:                       $thisallowed.=$value;
                   6776:                   }
1.53      www      6777:                   $uri=$refuri;
                   6778:                   $statecond=$refstatecond;
1.52      www      6779:               }
                   6780:           }
1.148     www      6781:         }
1.29      www      6782:        }
1.52      www      6783:    }
1.29      www      6784: 
1.52      www      6785: #
1.103     harris41 6786: # Gathered now: all privileges that could apply, and condition number
1.52      www      6787: # 
                   6788: #
                   6789: # Full or no access?
                   6790: #
1.29      www      6791: 
1.52      www      6792:     if ($thisallowed=~/F/) {
                   6793: 	return 'F';
                   6794:     }
1.29      www      6795: 
1.52      www      6796:     unless ($thisallowed) {
                   6797:         return '';
                   6798:     }
1.29      www      6799: 
1.52      www      6800: # Restrictions exist, deal with them
                   6801: #
                   6802: #   C:according to course preferences
                   6803: #   R:according to resource settings
                   6804: #   L:unless locked
                   6805: #   X:according to user session state
                   6806: #
                   6807: 
                   6808: # Possibly locked functionality, check all courses
1.54      www      6809: # Locks might take effect only after 10 minutes cache expiration for other
                   6810: # courses, and 2 minutes for current course
1.52      www      6811: 
                   6812:     my $envkey;
                   6813:     if ($thisallowed=~/L/) {
1.1000    raeburn  6814:         foreach $envkey (keys(%env)) {
1.54      www      6815:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6816:                my $courseid=$2;
                   6817:                my $roleid=$1.'.'.$2;
1.92      www      6818:                $courseid=~s/^\///;
1.54      www      6819:                my $expiretime=600;
1.620     albertel 6820:                if ($env{'request.role'} eq $roleid) {
1.54      www      6821: 		  $expiretime=120;
                   6822:                }
                   6823: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6824:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6825:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6826: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6827:                }
1.620     albertel 6828:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6829:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6830: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6831:                        &log($env{'user.domain'},$env{'user.name'},
                   6832:                             $env{'user.home'},
1.57      www      6833:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6834:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6835:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6836: 		       return '';
                   6837:                    }
                   6838:                }
1.620     albertel 6839:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6840:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6841: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6842:                        &log($env{'user.domain'},$env{'user.name'},
                   6843:                             $env{'user.home'},
1.57      www      6844:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6845:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6846:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6847: 		       return '';
                   6848:                    }
                   6849:                }
                   6850: 	   }
1.29      www      6851:        }
1.52      www      6852:     }
                   6853:    
                   6854: #
                   6855: # Rest of the restrictions depend on selected course
                   6856: #
                   6857: 
1.620     albertel 6858:     unless ($env{'request.course.id'}) {
1.766     albertel 6859: 	if ($thisallowed eq 'A') {
                   6860: 	    return 'A';
1.814     raeburn  6861:         } elsif ($thisallowed eq 'B') {
                   6862:             return 'B';
1.766     albertel 6863: 	} else {
                   6864: 	    return '1';
                   6865: 	}
1.52      www      6866:     }
1.29      www      6867: 
1.52      www      6868: #
                   6869: # Now user is definitely in a course
                   6870: #
1.53      www      6871: 
                   6872: 
                   6873: # Course preferences
                   6874: 
                   6875:    if ($thisallowed=~/C/) {
1.620     albertel 6876:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6877:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6878:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6879: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6880: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6881: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6882: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6883: 			$env{'request.course.id'});
                   6884: 	   }
1.237     www      6885:            return '';
                   6886:        }
                   6887: 
1.620     albertel 6888:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6889: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6890: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6891: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6892: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6893: 			$env{'request.course.id'});
                   6894: 	   }
1.54      www      6895:            return '';
                   6896:        }
1.53      www      6897:    }
                   6898: 
                   6899: # Resource preferences
                   6900: 
                   6901:    if ($thisallowed=~/R/) {
1.620     albertel 6902:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6903:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6904: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6905: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6906: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6907: 	   }
                   6908: 	   return '';
1.54      www      6909:        }
1.53      www      6910:    }
1.30      www      6911: 
1.246     www      6912: # Restricted by state or randomout?
1.30      www      6913: 
1.52      www      6914:    if ($thisallowed=~/X/) {
1.620     albertel 6915:       if ($env{'acc.randomout'}) {
1.579     albertel 6916: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6917:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6918:             return ''; 
                   6919:          }
1.247     www      6920:       }
                   6921:       if (&condval($statecond)) {
1.52      www      6922: 	 return '2';
                   6923:       } else {
                   6924:          return '';
                   6925:       }
                   6926:    }
1.30      www      6927: 
1.766     albertel 6928:     if ($thisallowed eq 'A') {
                   6929: 	return 'A';
1.814     raeburn  6930:     } elsif ($thisallowed eq 'B') {
                   6931:         return 'B';
1.766     albertel 6932:     }
1.52      www      6933:    return 'F';
1.232     www      6934: }
1.1162    raeburn  6935: 
1.1172.2.13  raeburn  6936: # ------------------------------------------- Check construction space access
                   6937: 
                   6938: sub constructaccess {
                   6939:     my ($url,$setpriv)=@_;
                   6940: 
                   6941: # We do not allow editing of previous versions of files
                   6942:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6943: 
                   6944: # Get username and domain from URL
                   6945:     my ($ownername,$ownerdomain,$ownerhome);
                   6946: 
                   6947:     ($ownerdomain,$ownername) =
                   6948:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6949: 
                   6950: # The URL does not really point to any authorspace, forget it
                   6951:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6952: 
                   6953: # Now we need to see if the user has access to the authorspace of
                   6954: # $ownername at $ownerdomain
                   6955: 
                   6956:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6957: # Real author for this?
                   6958:        $ownerhome = $env{'user.home'};
                   6959:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6960:           return ($ownername,$ownerdomain,$ownerhome);
                   6961:        }
                   6962:     } else {
                   6963: # Co-author for this?
                   6964:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6965:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6966:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6967:             return ($ownername,$ownerdomain,$ownerhome);
                   6968:         }
                   6969:     }
                   6970: 
                   6971: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6972: # we might as well leave
                   6973:    unless ($setpriv) { return ''; }
                   6974: 
                   6975: # Backdoor access?
                   6976:     my $allowed=&allowed('eco',$ownerdomain);
                   6977: # Nope
                   6978:     unless ($allowed) { return ''; }
                   6979: # Looks like we may have access, but could be locked by the owner of the construction space
                   6980:     if ($allowed eq 'U') {
                   6981:         my %blocked=&get('environment',['domcoord.author'],
                   6982:                          $ownerdomain,$ownername);
                   6983: # Is blocked by owner
                   6984:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6985:     }
                   6986:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6987: # Grant temporary access
                   6988:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6989:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6990:         if (!$update) { $update = $then; }
                   6991:         my $refresh=$env{'user.refresh.time'};
                   6992:         if (!$refresh) { $refresh = $update; }
                   6993:         my $now = time;
                   6994:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6995:                            $now,'ca','constructaccess');
                   6996:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6997:         return($ownername,$ownerdomain,$ownerhome);
                   6998:     }
                   6999: # No business here
                   7000:     return '';
                   7001: }
                   7002: 
1.1162    raeburn  7003: sub get_comm_blocks {
                   7004:     my ($cdom,$cnum) = @_;
                   7005:     if ($cdom eq '' || $cnum eq '') {
                   7006:         return unless ($env{'request.course.id'});
                   7007:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7008:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7009:     }
                   7010:     my %commblocks;
                   7011:     my $hashid=$cdom.'_'.$cnum;
                   7012:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7013:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7014:         %commblocks = %{$blocksref};
                   7015:     } else {
                   7016:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7017:         my $cachetime = 600;
                   7018:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7019:     }
                   7020:     return %commblocks;
                   7021: }
                   7022: 
                   7023: sub has_comm_blocking {
                   7024:     my ($priv,$symb,$uri,$blocks) = @_;
                   7025:     return unless ($env{'request.course.id'});
                   7026:     return unless ($priv eq 'bre');
                   7027:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7028:     my %commblocks;
                   7029:     if (ref($blocks) eq 'HASH') {
                   7030:         %commblocks = %{$blocks};
                   7031:     } else {
                   7032:         %commblocks = &get_comm_blocks();
                   7033:     }
                   7034:     return unless (keys(%commblocks) > 0);
                   7035:     if (!$symb) { $symb=&symbread($uri,1); }
                   7036:     my ($map,$resid,undef)=&decode_symb($symb);
                   7037:     my %tocheck = (
                   7038:                     maps      => $map,
                   7039:                     resources => $symb,
                   7040:                   );
                   7041:     my @blockers;
                   7042:     my $now = time;
1.1163    raeburn  7043:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7044:     foreach my $block (keys(%commblocks)) {
                   7045:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7046:             my ($start,$end) = ($1,$2);
                   7047:             if ($start <= $now && $end >= $now) {
                   7048:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7049:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7050:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7051:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7052:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7053:                                     push(@blockers,$block);
                   7054:                                 }
                   7055:                             }
                   7056:                         }
                   7057:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7058:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7059:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7060:                                     push(@blockers,$block);
                   7061:                                 }
                   7062:                             }
                   7063:                         }
                   7064:                     }
                   7065:                 }
                   7066:             }
                   7067:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7068:             my $item = $1;
1.1163    raeburn  7069:             my @to_test;
1.1162    raeburn  7070:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7071:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7072:                     my $check_interval;
                   7073:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7074:                         my @interval;
                   7075:                         my $type = 'map';
                   7076:                         if ($item eq 'course') {
                   7077:                             $type = 'course';
                   7078:                             @interval=&EXT("resource.0.interval");
                   7079:                         } else {
                   7080:                             if ($item =~ /___\d+___/) {
                   7081:                                 $type = 'resource';
                   7082:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7083:                                 if (ref($navmap)) {                        
                   7084:                                     my $res = $navmap->getBySymb($item); 
                   7085:                                     push(@to_test,$res);
                   7086:                                 }
1.1162    raeburn  7087:                             } else {
                   7088:                                 my $mapsymb = &symbread($item,1);
                   7089:                                 if ($mapsymb) {
                   7090:                                     if (ref($navmap)) {
                   7091:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7092:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7093:                                         foreach my $res (@to_test) {
1.1162    raeburn  7094:                                             my $symb = $res->symb();
                   7095:                                             next if ($symb eq $mapsymb);
                   7096:                                             if ($symb ne '') {
                   7097:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7098:                                                 last;
                   7099:                                             }
                   7100:                                         }
                   7101:                                     }
                   7102:                                 }
                   7103:                             }
                   7104:                         }
                   7105:                         if ($interval[0] =~ /\d+/) {
                   7106:                             my $first_access;
                   7107:                             if ($type eq 'resource') {
                   7108:                                 $first_access=&get_first_access($interval[1],$item);
                   7109:                             } elsif ($type eq 'map') {
                   7110:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7111:                             } else {
                   7112:                                 $first_access=&get_first_access($interval[1]);
                   7113:                             }
                   7114:                             if ($first_access) {
                   7115:                                 my $timesup = $first_access+$interval[0];
                   7116:                                 if ($timesup > $now) {
1.1163    raeburn  7117:                                     foreach my $res (@to_test) {
                   7118:                                         if ($res->is_problem()) {
                   7119:                                             if ($res->completable()) {
                   7120:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7121:                                                     push(@blockers,$block);
                   7122:                                                 }
                   7123:                                                 last;
                   7124:                                             }
                   7125:                                         }
1.1162    raeburn  7126:                                     }
                   7127:                                 }
                   7128:                             }
                   7129:                         }
                   7130:                     }
                   7131:                 }
                   7132:             }
                   7133:         }
                   7134:     }
                   7135:     return @blockers;
                   7136: }
                   7137: 
                   7138: sub check_docs_block {
                   7139:     my ($docsblock,$tocheck) =@_;
                   7140:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7141:         return;
                   7142:     }
                   7143:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7144:         if ($tocheck->{'maps'}) {
                   7145:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7146:                 return 1;
                   7147:             }
                   7148:         }
                   7149:     }
                   7150:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7151:         if ($tocheck->{'resources'}) {
                   7152:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7153:                 return 1;
                   7154:             }
                   7155:         }
                   7156:     }
                   7157:     return;
                   7158: }
                   7159: 
1.1133    foxr     7160: #
                   7161: #   Removes the versino from a URI and
                   7162: #   splits it in to its filename and path to the filename.
                   7163: #   Seems like File::Basename could have done this more clearly.
                   7164: #   Parameters:
                   7165: #      $uri   - input URI
                   7166: #   Returns:
                   7167: #     Two element list consisting of 
                   7168: #     $pathname  - the URI up to and excluding the trailing /
                   7169: #     $filename  - The part of the URI following the last /
                   7170: #  NOTE:
                   7171: #    Another realization of this is simply:
                   7172: #    use File::Basename;
                   7173: #    ...
                   7174: #    $uri = shift;
                   7175: #    $filename = basename($uri);
                   7176: #    $path     = dirname($uri);
                   7177: #    return ($filename, $path);
                   7178: #
                   7179: #     The implementation below is probably faster however.
                   7180: #
1.710     albertel 7181: sub split_uri_for_cond {
                   7182:     my $uri=&deversion(&declutter(shift));
                   7183:     my @uriparts=split(/\//,$uri);
                   7184:     my $filename=pop(@uriparts);
                   7185:     my $pathname=join('/',@uriparts);
                   7186:     return ($pathname,$filename);
                   7187: }
1.232     www      7188: # --------------------------------------------------- Is a resource on the map?
                   7189: 
                   7190: sub is_on_map {
1.710     albertel 7191:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7192:     #Trying to find the conditional for the file
1.620     albertel 7193:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7194: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7195:     if ($match) {
1.289     bowersj2 7196: 	return (1,$1);
                   7197:     } else {
1.434     www      7198: 	return (0,0);
1.289     bowersj2 7199:     }
1.12      www      7200: }
                   7201: 
1.427     www      7202: # --------------------------------------------------------- Get symb from alias
                   7203: 
                   7204: sub get_symb_from_alias {
                   7205:     my $symb=shift;
                   7206:     my ($map,$resid,$url)=&decode_symb($symb);
                   7207: # Already is a symb
                   7208:     if ($url) { return $symb; }
                   7209: # Must be an alias
                   7210:     my $aliassymb='';
                   7211:     my %bighash;
1.620     albertel 7212:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7213:                             &GDBM_READER(),0640)) {
                   7214:         my $rid=$bighash{'mapalias_'.$symb};
                   7215: 	if ($rid) {
                   7216: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7217: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7218: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7219: 	}
                   7220:         untie %bighash;
                   7221:     }
                   7222:     return $aliassymb;
                   7223: }
                   7224: 
1.12      www      7225: # ----------------------------------------------------------------- Define Role
                   7226: 
                   7227: sub definerole {
                   7228:   if (allowed('mcr','/')) {
                   7229:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7230:     foreach my $role (split(':',$sysrole)) {
                   7231: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7232:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7233:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7234: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7235:                return "refused:s:$crole&$cqual"; 
                   7236:             }
                   7237:         }
1.191     harris41 7238:     }
1.800     albertel 7239:     foreach my $role (split(':',$domrole)) {
                   7240: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7241:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7242:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7243: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7244:                return "refused:d:$crole&$cqual"; 
                   7245:             }
                   7246:         }
1.191     harris41 7247:     }
1.800     albertel 7248:     foreach my $role (split(':',$courole)) {
                   7249: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7250:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7251:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7252: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7253:                return "refused:c:$crole&$cqual"; 
                   7254:             }
                   7255:         }
1.191     harris41 7256:     }
1.620     albertel 7257:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7258:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7259: 	        "rolesdef_$rolename=".
                   7260:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7261:     return reply($command,$env{'user.home'});
1.12      www      7262:   } else {
                   7263:     return 'refused';
                   7264:   }
1.105     harris41 7265: }
                   7266: 
                   7267: # ---------------- Make a metadata query against the network of library servers
                   7268: 
                   7269: sub metadata_query {
1.244     matthew  7270:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7271:     my %rhash;
1.845     albertel 7272:     my %libserv = &all_library();
1.244     matthew  7273:     my @server_list = (defined($server_array) ? @$server_array
                   7274:                                               : keys(%libserv) );
                   7275:     for my $server (@server_list) {
1.118     harris41 7276: 	unless ($custom or $customshow) {
                   7277: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7278: 	    $rhash{$server}=$reply;
                   7279: 	}
                   7280: 	else {
                   7281: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7282: 			     &escape($custom).':'.&escape($customshow),
                   7283: 			     $server);
                   7284: 	    $rhash{$server}=$reply;
                   7285: 	}
1.112     harris41 7286:     }
1.118     harris41 7287:     return \%rhash;
1.240     www      7288: }
                   7289: 
                   7290: # ----------------------------------------- Send log queries and wait for reply
                   7291: 
                   7292: sub log_query {
                   7293:     my ($uname,$udom,$query,%filters)=@_;
                   7294:     my $uhome=&homeserver($uname,$udom);
                   7295:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7296:     my $uhost=&hostname($uhome);
1.800     albertel 7297:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7298:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7299:                        $uhome);
1.479     albertel 7300:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7301:     return get_query_reply($queryid);
                   7302: }
                   7303: 
1.818     raeburn  7304: # -------------------------- Update MySQL table for portfolio file
                   7305: 
                   7306: sub update_portfolio_table {
1.821     raeburn  7307:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7308:     if ($group ne '') {
                   7309:         $file_name =~s /^\Q$group\E//;
                   7310:     }
1.818     raeburn  7311:     my $homeserver = &homeserver($uname,$udom);
                   7312:     my $queryid=
1.821     raeburn  7313:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7314:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7315:     my $reply = &get_query_reply($queryid);
                   7316:     return $reply;
                   7317: }
                   7318: 
1.899     raeburn  7319: # -------------------------- Update MySQL allusers table
                   7320: 
                   7321: sub update_allusers_table {
                   7322:     my ($uname,$udom,$names) = @_;
                   7323:     my $homeserver = &homeserver($uname,$udom);
                   7324:     my $queryid=
                   7325:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7326:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7327:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7328:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7329:                'generation='.&escape($names->{'generation'}).'%%'.
                   7330:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7331:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7332:     return;
1.899     raeburn  7333: }
                   7334: 
1.508     raeburn  7335: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7336: 
                   7337: sub fetch_enrollment_query {
1.511     raeburn  7338:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7339:     my $homeserver;
1.547     raeburn  7340:     my $maxtries = 1;
1.508     raeburn  7341:     if ($context eq 'automated') {
                   7342:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7343:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7344:     } else {
                   7345:         $homeserver = &homeserver($cnum,$dom);
                   7346:     }
1.838     albertel 7347:     my $host=&hostname($homeserver);
1.506     raeburn  7348:     my $cmd = '';
1.1000    raeburn  7349:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7350:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7351:     }
                   7352:     $cmd =~ s/%%$//;
                   7353:     $cmd = &escape($cmd);
                   7354:     my $query = 'fetchenrollment';
1.620     albertel 7355:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7356:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7357:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7358:         return 'error: '.$queryid;
                   7359:     }
1.506     raeburn  7360:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7361:     my $tries = 1;
                   7362:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7363:         $reply = &get_query_reply($queryid);
                   7364:         $tries ++;
                   7365:     }
1.526     raeburn  7366:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7367:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7368:     } else {
1.901     albertel 7369:         my @responses = split(/:/,$reply);
1.515     raeburn  7370:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7371:             foreach my $line (@responses) {
                   7372:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7373:                 $$replyref{$key} = $value;
                   7374:             }
                   7375:         } else {
1.1117    foxr     7376:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7377:             foreach my $line (@responses) {
                   7378:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7379:                 $$replyref{$key} = $value;
                   7380:                 if ($value > 0) {
1.800     albertel 7381:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7382:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7383:                         my $destname = $pathname.'/'.$filename;
                   7384:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7385:                         if ($xml_classlist =~ /^error/) {
                   7386:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7387:                         } else {
1.506     raeburn  7388:                             if ( open(FILE,">$destname") ) {
                   7389:                                 print FILE &unescape($xml_classlist);
                   7390:                                 close(FILE);
1.526     raeburn  7391:                             } else {
                   7392:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7393:                             }
                   7394:                         }
                   7395:                     }
                   7396:                 }
                   7397:             }
                   7398:         }
                   7399:         return 'ok';
                   7400:     }
                   7401:     return 'error';
                   7402: }
                   7403: 
1.242     www      7404: sub get_query_reply {
                   7405:     my $queryid=shift;
1.1117    foxr     7406:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7407:     my $reply='';
                   7408:     for (1..100) {
                   7409: 	sleep 2;
                   7410:         if (-e $replyfile.'.end') {
1.448     albertel 7411: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7412: 		$reply = join('',<$fh>);
                   7413: 		close($fh);
1.240     www      7414: 	   } else { return 'error: reply_file_error'; }
1.242     www      7415:            return &unescape($reply);
                   7416: 	}
1.240     www      7417:     }
1.242     www      7418:     return 'timeout:'.$queryid;
1.240     www      7419: }
                   7420: 
                   7421: sub courselog_query {
1.241     www      7422: #
                   7423: # possible filters:
                   7424: # url: url or symb
                   7425: # username
                   7426: # domain
                   7427: # action: view, submit, grade
                   7428: # start: timestamp
                   7429: # end: timestamp
                   7430: #
1.240     www      7431:     my (%filters)=@_;
1.620     albertel 7432:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7433:     if ($filters{'url'}) {
                   7434: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7435:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7436:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7437:     }
1.620     albertel 7438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7440:     return &log_query($cname,$cdom,'courselog',%filters);
                   7441: }
                   7442: 
                   7443: sub userlog_query {
1.858     raeburn  7444: #
                   7445: # possible filters:
                   7446: # action: log check role
                   7447: # start: timestamp
                   7448: # end: timestamp
                   7449: #
1.240     www      7450:     my ($uname,$udom,%filters)=@_;
                   7451:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7452: }
                   7453: 
1.506     raeburn  7454: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7455: 
                   7456: sub auto_run {
1.508     raeburn  7457:     my ($cnum,$cdom) = @_;
1.876     raeburn  7458:     my $response = 0;
                   7459:     my $settings;
                   7460:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7461:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7462:         $settings = $domconfig{'autoenroll'};
                   7463:         if ($settings->{'run'} eq '1') {
                   7464:             $response = 1;
                   7465:         }
                   7466:     } else {
1.934     raeburn  7467:         my $homeserver;
                   7468:         if (&is_course($cdom,$cnum)) {
                   7469:             $homeserver = &homeserver($cnum,$cdom);
                   7470:         } else {
                   7471:             $homeserver = &domain($cdom,'primary');
                   7472:         }
                   7473:         if ($homeserver ne 'no_host') {
                   7474:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7475:         }
1.876     raeburn  7476:     }
1.506     raeburn  7477:     return $response;
                   7478: }
1.776     albertel 7479: 
1.506     raeburn  7480: sub auto_get_sections {
1.508     raeburn  7481:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7482:     my $homeserver;
                   7483:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7484:         $homeserver = &homeserver($cnum,$cdom);
                   7485:     }
                   7486:     if (!defined($homeserver)) { 
                   7487:         if ($cdom =~ /^$match_domain$/) {
                   7488:             $homeserver = &domain($cdom,'primary');
                   7489:         }
                   7490:     }
                   7491:     my @secs;
                   7492:     if (defined($homeserver)) {
                   7493:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7494:         unless ($response eq 'refused') {
                   7495:             @secs = split(/:/,$response);
                   7496:         }
1.506     raeburn  7497:     }
                   7498:     return @secs;
                   7499: }
1.776     albertel 7500: 
1.506     raeburn  7501: sub auto_new_course {
1.1099    raeburn  7502:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7503:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7504:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7505:     return $response;
                   7506: }
1.776     albertel 7507: 
1.506     raeburn  7508: sub auto_validate_courseID {
1.508     raeburn  7509:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7510:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7511:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7512:     return $response;
                   7513: }
1.776     albertel 7514: 
1.1007    raeburn  7515: sub auto_validate_instcode {
1.1020    raeburn  7516:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7517:     my ($homeserver,$response);
                   7518:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7519:         $homeserver = &homeserver($cnum,$cdom);
                   7520:     }
                   7521:     if (!defined($homeserver)) {
                   7522:         if ($cdom =~ /^$match_domain$/) {
                   7523:             $homeserver = &domain($cdom,'primary');
                   7524:         }
                   7525:     }
1.1065    raeburn  7526:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7527:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7528:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7529:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7530: }
                   7531: 
1.506     raeburn  7532: sub auto_create_password {
1.873     raeburn  7533:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7534:     my ($homeserver,$response);
1.506     raeburn  7535:     my $create_passwd = 0;
                   7536:     my $authchk = '';
1.873     raeburn  7537:     if ($udom =~ /^$match_domain$/) {
                   7538:         $homeserver = &domain($udom,'primary');
                   7539:     }
                   7540:     if ($homeserver eq '') {
                   7541:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7542:             $homeserver = &homeserver($cnum,$cdom);
                   7543:         }
                   7544:     }
                   7545:     if ($homeserver eq '') {
                   7546:         $authchk = 'nodomain';
1.506     raeburn  7547:     } else {
1.873     raeburn  7548:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7549:         if ($response eq 'refused') {
                   7550:             $authchk = 'refused';
                   7551:         } else {
1.901     albertel 7552:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7553:         }
1.506     raeburn  7554:     }
                   7555:     return ($authparam,$create_passwd,$authchk);
                   7556: }
                   7557: 
1.706     raeburn  7558: sub auto_photo_permission {
                   7559:     my ($cnum,$cdom,$students) = @_;
                   7560:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7561:     my ($outcome,$perm_reqd,$conditions) = 
                   7562: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7563:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7564: 	return (undef,undef);
                   7565:     }
1.706     raeburn  7566:     return ($outcome,$perm_reqd,$conditions);
                   7567: }
                   7568: 
                   7569: sub auto_checkphotos {
                   7570:     my ($uname,$udom,$pid) = @_;
                   7571:     my $homeserver = &homeserver($uname,$udom);
                   7572:     my ($result,$resulttype);
                   7573:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7574: 				   &escape($uname).':'.&escape($pid),
                   7575: 				   $homeserver));
1.709     albertel 7576:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7577: 	return (undef,undef);
                   7578:     }
1.706     raeburn  7579:     if ($outcome) {
                   7580:         ($result,$resulttype) = split(/:/,$outcome);
                   7581:     } 
                   7582:     return ($result,$resulttype);
                   7583: }
                   7584: 
                   7585: sub auto_photochoice {
                   7586:     my ($cnum,$cdom) = @_;
                   7587:     my $homeserver = &homeserver($cnum,$cdom);
                   7588:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7589: 						       &escape($cdom),
                   7590: 						       $homeserver)));
1.709     albertel 7591:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7592: 	return (undef,undef);
                   7593:     }
1.706     raeburn  7594:     return ($update,$comment);
                   7595: }
                   7596: 
                   7597: sub auto_photoupdate {
                   7598:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7599:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7600:     my $host=&hostname($homeserver);
1.706     raeburn  7601:     my $cmd = '';
                   7602:     my $maxtries = 1;
1.800     albertel 7603:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7604:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7605:     }
                   7606:     $cmd =~ s/%%$//;
                   7607:     $cmd = &escape($cmd);
                   7608:     my $query = 'institutionalphotos';
                   7609:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7610:     unless ($queryid=~/^\Q$host\E\_/) {
                   7611:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7612:         return 'error: '.$queryid;
                   7613:     }
                   7614:     my $reply = &get_query_reply($queryid);
                   7615:     my $tries = 1;
                   7616:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7617:         $reply = &get_query_reply($queryid);
                   7618:         $tries ++;
                   7619:     }
                   7620:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7621:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7622:     } else {
                   7623:         my @responses = split(/:/,$reply);
                   7624:         my $outcome = shift(@responses); 
                   7625:         foreach my $item (@responses) {
                   7626:             my ($key,$value) = split(/=/,$item);
                   7627:             $$photo{$key} = $value;
                   7628:         }
                   7629:         return $outcome;
                   7630:     }
                   7631:     return 'error';
                   7632: }
                   7633: 
1.521     raeburn  7634: sub auto_instcode_format {
1.793     albertel 7635:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7636: 	$cat_order) = @_;
1.521     raeburn  7637:     my $courses = '';
1.772     raeburn  7638:     my @homeservers;
1.521     raeburn  7639:     if ($caller eq 'global') {
1.841     albertel 7640: 	my %servers = &get_servers($codedom,'library');
                   7641: 	foreach my $tryserver (keys(%servers)) {
                   7642: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7643: 		push(@homeservers,$tryserver);
                   7644: 	    }
1.584     raeburn  7645:         }
1.1022    raeburn  7646:     } elsif ($caller eq 'requests') {
                   7647:         if ($codedom =~ /^$match_domain$/) {
                   7648:             my $chome = &domain($codedom,'primary');
                   7649:             unless ($chome eq 'no_host') {
                   7650:                 push(@homeservers,$chome);
                   7651:             }
                   7652:         }
1.521     raeburn  7653:     } else {
1.772     raeburn  7654:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7655:     }
1.793     albertel 7656:     foreach my $code (keys(%{$instcodes})) {
                   7657:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7658:     }
                   7659:     chop($courses);
1.772     raeburn  7660:     my $ok_response = 0;
                   7661:     my $response;
                   7662:     while (@homeservers > 0 && $ok_response == 0) {
                   7663:         my $server = shift(@homeservers); 
                   7664:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7665:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7666:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7667: 		split(/:/,$response);
1.772     raeburn  7668:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7669:             push(@{$codetitles},&str2array($codetitles_str));
                   7670:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7671:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7672:             $ok_response = 1;
                   7673:         }
                   7674:     }
                   7675:     if ($ok_response) {
1.521     raeburn  7676:         return 'ok';
1.772     raeburn  7677:     } else {
                   7678:         return $response;
1.521     raeburn  7679:     }
                   7680: }
                   7681: 
1.792     raeburn  7682: sub auto_instcode_defaults {
                   7683:     my ($domain,$returnhash,$code_order) = @_;
                   7684:     my @homeservers;
1.841     albertel 7685: 
                   7686:     my %servers = &get_servers($domain,'library');
                   7687:     foreach my $tryserver (keys(%servers)) {
                   7688: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7689: 	    push(@homeservers,$tryserver);
                   7690: 	}
1.792     raeburn  7691:     }
1.841     albertel 7692: 
1.792     raeburn  7693:     my $response;
1.841     albertel 7694:     foreach my $server (@homeservers) {
1.792     raeburn  7695:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7696:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7697: 	
                   7698: 	foreach my $pair (split(/\&/,$response)) {
                   7699: 	    my ($name,$value)=split(/\=/,$pair);
                   7700: 	    if ($name eq 'code_order') {
                   7701: 		@{$code_order} = split(/\&/,&unescape($value));
                   7702: 	    } else {
                   7703: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7704: 	    }
                   7705: 	}
                   7706: 	return 'ok';
1.792     raeburn  7707:     }
1.841     albertel 7708: 
                   7709:     return $response;
1.1003    raeburn  7710: }
                   7711: 
                   7712: sub auto_possible_instcodes {
1.1007    raeburn  7713:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7714:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7715:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7716:         return;
                   7717:     }
1.1003    raeburn  7718:     my (@homeservers,$uhome);
                   7719:     if (defined(&domain($domain,'primary'))) {
                   7720:         $uhome=&domain($domain,'primary');
                   7721:         push(@homeservers,&domain($domain,'primary'));
                   7722:     } else {
                   7723:         my %servers = &get_servers($domain,'library');
                   7724:         foreach my $tryserver (keys(%servers)) {
                   7725:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7726:                 push(@homeservers,$tryserver);
                   7727:             }
                   7728:         }
                   7729:     }
                   7730:     my $response;
                   7731:     foreach my $server (@homeservers) {
                   7732:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7733:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7734:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7735:             split(':',$response);
                   7736:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7737:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7738:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7739:             my ($name,$value)=split('=',$item);
                   7740:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7741:         }
                   7742:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7743:             my ($name,$value)=split('=',$item);
                   7744:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7745:         }
                   7746:         return 'ok';
                   7747:     }
                   7748:     return $response;
                   7749: }
1.792     raeburn  7750: 
1.1010    raeburn  7751: sub auto_courserequest_checks {
                   7752:     my ($dom) = @_;
1.1020    raeburn  7753:     my ($homeserver,%validations);
                   7754:     if ($dom =~ /^$match_domain$/) {
                   7755:         $homeserver = &domain($dom,'primary');
                   7756:     }
                   7757:     unless ($homeserver eq 'no_host') {
                   7758:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7759:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7760:             my @items = split(/&/,$response);
                   7761:             foreach my $item (@items) {
                   7762:                 my ($key,$value) = split('=',$item);
                   7763:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7764:             }
                   7765:         }
                   7766:     }
1.1010    raeburn  7767:     return %validations; 
                   7768: }
                   7769: 
1.1020    raeburn  7770: sub auto_courserequest_validation {
                   7771:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7772:     my ($homeserver,$response);
                   7773:     if ($dom =~ /^$match_domain$/) {
                   7774:         $homeserver = &domain($dom,'primary');
                   7775:     }
                   7776:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7777:           
1.1020    raeburn  7778:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7779:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7780:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7781:                                     $homeserver));
                   7782:     }
                   7783:     return $response;
                   7784: }
                   7785: 
1.777     albertel 7786: sub auto_validate_class_sec {
1.918     raeburn  7787:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7788:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7789:     my $ownerlist;
                   7790:     if (ref($owners) eq 'ARRAY') {
                   7791:         $ownerlist = join(',',@{$owners});
                   7792:     } else {
                   7793:         $ownerlist = $owners;
                   7794:     }
1.773     raeburn  7795:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7796:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7797:     return $response;
                   7798: }
                   7799: 
1.679     raeburn  7800: # ------------------------------------------------------- Course Group routines
                   7801: 
                   7802: sub get_coursegroups {
1.809     raeburn  7803:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7804:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7805: }
                   7806: 
1.679     raeburn  7807: sub modify_coursegroup {
                   7808:     my ($cdom,$cnum,$groupsettings) = @_;
                   7809:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7810: }
                   7811: 
1.809     raeburn  7812: sub toggle_coursegroup_status {
                   7813:     my ($cdom,$cnum,$group,$action) = @_;
                   7814:     my ($from_namespace,$to_namespace);
                   7815:     if ($action eq 'delete') {
                   7816:         $from_namespace = 'coursegroups';
                   7817:         $to_namespace = 'deleted_groups';
                   7818:     } else {
                   7819:         $from_namespace = 'deleted_groups';
                   7820:         $to_namespace = 'coursegroups';
                   7821:     }
                   7822:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7823:     if (my $tmp = &error(%curr_group)) {
                   7824:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7825:         return ('read error',$tmp);
                   7826:     } else {
                   7827:         my %savedsettings = %curr_group; 
1.809     raeburn  7828:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7829:         my $deloutcome;
                   7830:         if ($result eq 'ok') {
1.809     raeburn  7831:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7832:         } else {
                   7833:             return ('write error',$result);
                   7834:         }
                   7835:         if ($deloutcome eq 'ok') {
                   7836:             return 'ok';
                   7837:         } else {
                   7838:             return ('delete error',$deloutcome);
                   7839:         }
                   7840:     }
                   7841: }
                   7842: 
1.679     raeburn  7843: sub modify_group_roles {
1.957     raeburn  7844:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7845:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7846:     my $role = 'gr/'.&escape($userprivs);
                   7847:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7848:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7849:     if ($result eq 'ok') {
                   7850:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7851:     }
1.679     raeburn  7852:     return $result;
                   7853: }
                   7854: 
                   7855: sub modify_coursegroup_membership {
                   7856:     my ($cdom,$cnum,$membership) = @_;
                   7857:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7858:     return $result;
                   7859: }
                   7860: 
1.682     raeburn  7861: sub get_active_groups {
                   7862:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7863:     my $now = time;
                   7864:     my %groups = ();
                   7865:     foreach my $key (keys(%env)) {
1.811     albertel 7866:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7867:             my ($start,$end) = split(/\./,$env{$key});
                   7868:             if (($end!=0) && ($end<$now)) { next; }
                   7869:             if (($start!=0) && ($start>$now)) { next; }
                   7870:             if ($1 eq $cdom && $2 eq $cnum) {
                   7871:                 $groups{$3} = $env{$key} ;
                   7872:             }
                   7873:         }
                   7874:     }
                   7875:     return %groups;
                   7876: }
                   7877: 
1.683     raeburn  7878: sub get_group_membership {
                   7879:     my ($cdom,$cnum,$group) = @_;
                   7880:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7881: }
                   7882: 
                   7883: sub get_users_groups {
                   7884:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7885:     my @usersgroups;
1.683     raeburn  7886:     my $cachetime=1800;
                   7887: 
                   7888:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7889:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7890:     if (defined($cached)) {
1.734     albertel 7891:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7892:     } else {  
                   7893:         $grouplist = '';
1.816     raeburn  7894:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7895:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7896:         my $access_end = $env{'course.'.$courseid.
                   7897:                               '.default_enrollment_end_date'};
                   7898:         my $now = time;
                   7899:         foreach my $key (keys(%roleshash)) {
                   7900:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7901:                 my $group = $1;
                   7902:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7903:                     my $start = $2;
                   7904:                     my $end = $1;
                   7905:                     if ($start == -1) { next; } # deleted from group
                   7906:                     if (($start!=0) && ($start>$now)) { next; }
                   7907:                     if (($end!=0) && ($end<$now)) {
                   7908:                         if ($access_end && $access_end < $now) {
                   7909:                             if ($access_end - $end < 86400) {
                   7910:                                 push(@usersgroups,$group);
1.733     raeburn  7911:                             }
                   7912:                         }
1.817     raeburn  7913:                         next;
1.733     raeburn  7914:                     }
1.817     raeburn  7915:                     push(@usersgroups,$group);
1.683     raeburn  7916:                 }
                   7917:             }
                   7918:         }
1.817     raeburn  7919:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7920:         $grouplist = join(':',@usersgroups);
                   7921:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7922:     }
1.733     raeburn  7923:     return @usersgroups;
1.683     raeburn  7924: }
                   7925: 
                   7926: sub devalidate_getgroups_cache {
                   7927:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7928:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7929: 
1.683     raeburn  7930:     my $hashid="$udom:$uname:$courseid";
                   7931:     &devalidate_cache_new('getgroups',$hashid);
                   7932: }
                   7933: 
1.12      www      7934: # ------------------------------------------------------------------ Plain Text
                   7935: 
                   7936: sub plaintext {
1.988     raeburn  7937:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7938:     if ($short =~ m{^cr/}) {
1.758     albertel 7939: 	return (split('/',$short))[-1];
                   7940:     }
1.742     raeburn  7941:     if (!defined($cid)) {
                   7942:         $cid = $env{'request.course.id'};
                   7943:     }
                   7944:     my %rolenames = (
1.1008    raeburn  7945:                       Course    => 'std',
                   7946:                       Community => 'alt1',
1.742     raeburn  7947:                     );
1.1037    raeburn  7948:     if ($cid ne '') {
                   7949:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7950:             unless ($forcedefault) {
                   7951:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7952:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7953:                 return &Apache::lonlocal::mt($roletext);
                   7954:             }
                   7955:         }
                   7956:     }
                   7957:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7958:         (defined($rolenames{$type})) && 
                   7959:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7960:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7961:     } elsif ($cid ne '') {
                   7962:         my $crstype = $env{'course.'.$cid.'.type'};
                   7963:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7964:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7965:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7966:         }
1.742     raeburn  7967:     }
1.1037    raeburn  7968:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7969: }
                   7970: 
                   7971: # ----------------------------------------------------------------- Assign Role
                   7972: 
                   7973: sub assignrole {
1.957     raeburn  7974:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7975:         $context)=@_;
1.21      www      7976:     my $mrole;
                   7977:     if ($role =~ /^cr\//) {
1.393     www      7978:         my $cwosec=$url;
1.811     albertel 7979:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7980: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7981:            my $refused = 1;
                   7982:            if ($context eq 'requestcourses') {
                   7983:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7984:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7985:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7986:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7987:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7988:                            if ($crsenv{'internal.courseowner'} eq
                   7989:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7990:                                $refused = '';
                   7991:                            }
                   7992:                        }
                   7993:                    }
                   7994:                }
                   7995:            }
                   7996:            if ($refused) {
                   7997:                &logthis('Refused custom assignrole: '.
                   7998:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7999:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8000:                return 'refused';
                   8001:            }
1.104     www      8002:         }
1.21      www      8003:         $mrole='cr';
1.678     raeburn  8004:     } elsif ($role =~ /^gr\//) {
                   8005:         my $cwogrp=$url;
1.811     albertel 8006:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8007:         unless (&allowed('mdg',$cwogrp)) {
                   8008:             &logthis('Refused group assignrole: '.
                   8009:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8010:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8011:             return 'refused';
                   8012:         }
                   8013:         $mrole='gr';
1.21      www      8014:     } else {
1.82      www      8015:         my $cwosec=$url;
1.811     albertel 8016:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8017:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8018:             my $refused;
                   8019:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8020:                 if (!(&allowed('c'.$role,$url))) {
                   8021:                     $refused = 1;
                   8022:                 }
                   8023:             } else {
                   8024:                 $refused = 1;
                   8025:             }
1.947     raeburn  8026:             if ($refused) {
1.1045    raeburn  8027:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8028:                 if (!$selfenroll && $context eq 'course') {
                   8029:                     my %crsenv;
                   8030:                     if ($role eq 'cc' || $role eq 'co') {
                   8031:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8032:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8033:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8034:                                 if ($crsenv{'internal.courseowner'} eq 
                   8035:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8036:                                     $refused = '';
                   8037:                                 }
                   8038:                             }
                   8039:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8040:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8041:                                 if ($crsenv{'internal.courseowner'} eq 
                   8042:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8043:                                     $refused = '';
                   8044:                                 }
                   8045:                             }
                   8046:                         }
                   8047:                     }
                   8048:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8049:                     $refused = '';
1.1017    raeburn  8050:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8051:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8052:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8053:                         my $wrongcc;
                   8054:                         if ($cnum =~ /^$match_community$/) {
                   8055:                             $wrongcc = 1 if ($role eq 'cc');
                   8056:                         } else {
                   8057:                             $wrongcc = 1 if ($role eq 'co');
                   8058:                         }
                   8059:                         unless ($wrongcc) {
                   8060:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8061:                             if ($crsenv{'internal.courseowner'} eq 
                   8062:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8063:                                 $refused = '';
                   8064:                             }
1.1017    raeburn  8065:                         }
                   8066:                     }
1.1172.2.9  raeburn  8067:                 } elsif ($context eq 'requestauthor') {
                   8068:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8069:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8070:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8071:                             $refused = '';
                   8072:                         } else {
                   8073:                             my %domdefaults = &get_domain_defaults($udom);
                   8074:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8075:                                 my $checkbystatus;
                   8076:                                 if ($env{'user.adv'}) {
                   8077:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8078:                                     if ($disposition eq 'automatic') {
                   8079:                                         $refused = '';
                   8080:                                     } elsif ($disposition eq '') {
                   8081:                                         $checkbystatus = 1;
                   8082:                                     }
                   8083:                                 } else {
                   8084:                                     $checkbystatus = 1;
                   8085:                                 }
                   8086:                                 if ($checkbystatus) {
                   8087:                                     if ($env{'environment.inststatus'}) {
                   8088:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8089:                                         foreach my $type (@inststatuses) {
                   8090:                                             if (($type ne '') &&
                   8091:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8092:                                                 $refused = '';
                   8093:                                             }
                   8094:                                         }
                   8095:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8096:                                         $refused = '';
                   8097:                                     }
                   8098:                                 }
                   8099:                             }
                   8100:                         }
                   8101:                     }
1.1017    raeburn  8102:                 }
                   8103:                 if ($refused) {
1.947     raeburn  8104:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8105:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8106: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8107:                     return 'refused';
                   8108:                 }
1.932     raeburn  8109:             }
1.1131    raeburn  8110:         } elsif ($role eq 'au') {
                   8111:             if ($url ne '/'.$udom.'/') {
                   8112:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8113:                          ' to assign author role for '.$uname.':'.$udom.
                   8114:                          ' in domain: '.$url.' refused (wrong domain).');
                   8115:                 return 'refused';
                   8116:             }
1.104     www      8117:         }
1.21      www      8118:         $mrole=$role;
                   8119:     }
1.620     albertel 8120:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8121:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8122:     if ($end) { $command.='_'.$end; }
1.21      www      8123:     if ($start) {
                   8124: 	if ($end) { 
1.81      www      8125:            $command.='_'.$start; 
1.21      www      8126:         } else {
1.81      www      8127:            $command.='_0_'.$start;
1.21      www      8128:         }
                   8129:     }
1.739     raeburn  8130:     my $origstart = $start;
                   8131:     my $origend = $end;
1.957     raeburn  8132:     my $delflag;
1.357     www      8133: # actually delete
                   8134:     if ($deleteflag) {
1.373     www      8135: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8136: # modify command to delete the role
1.620     albertel 8137:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8138:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8139: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8140: # set start and finish to negative values for userrolelog
                   8141:            $start=-1;
                   8142:            $end=-1;
1.957     raeburn  8143:            $delflag = 1;
1.357     www      8144:         }
                   8145:     }
                   8146: # send command
1.349     www      8147:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8148: # log new user role if status is ok
1.349     www      8149:     if ($answer eq 'ok') {
1.663     raeburn  8150: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8151:         if (($role eq 'cc') || ($role eq 'in') ||
                   8152:             ($role eq 'ep') || ($role eq 'ad') ||
                   8153:             ($role eq 'ta') || ($role eq 'st') ||
                   8154:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8155:             ($role eq 'co')) {
1.1172.2.13  raeburn  8156: # for course roles, perform group memberships changes triggered by role change.
                   8157:             unless ($role =~ /^gr/) {
                   8158:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8159:                                                  $origstart,$selfenroll,$context);
                   8160:             }
1.1172.2.9  raeburn  8161:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8162:                            $selfenroll,$context);
                   8163:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8164:                  ($role eq 'au') || ($role eq 'dc')) {
                   8165:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8166:                            $context);
                   8167:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8168:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8169:                              $context);
                   8170:         }
1.1053    raeburn  8171:         if ($role eq 'cc') {
                   8172:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8173:         }
1.349     www      8174:     }
                   8175:     return $answer;
1.169     harris41 8176: }
                   8177: 
1.1053    raeburn  8178: sub autoupdate_coowners {
                   8179:     my ($url,$end,$start,$uname,$udom) = @_;
                   8180:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8181:     if (($cdom ne '') && ($cnum ne '')) {
                   8182:         my $now = time;
                   8183:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8184:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8185:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8186:             my $instcode = $coursehash{'internal.coursecode'};
                   8187:             if ($instcode ne '') {
1.1056    raeburn  8188:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8189:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8190:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8191:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8192:                         if ($result eq 'valid') {
                   8193:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8194:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8195:                                     push(@newcoowners,$coowner);
                   8196:                                 }
                   8197:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8198:                                     push(@newcoowners,$uname.':'.$udom);
                   8199:                                 }
                   8200:                                 @newcoowners = sort(@newcoowners);
                   8201:                             } else {
                   8202:                                 push(@newcoowners,$uname.':'.$udom);
                   8203:                             }
                   8204:                         } else {
                   8205:                             if ($coursehash{'internal.co-owners'}) {
                   8206:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8207:                                     unless ($coowner eq $uname.':'.$udom) {
                   8208:                                         push(@newcoowners,$coowner);
                   8209:                                     }
                   8210:                                 }
                   8211:                                 unless (@newcoowners > 0) {
                   8212:                                     $delcoowners = 1;
                   8213:                                     $coowners = '';
                   8214:                                 }
                   8215:                             }
                   8216:                         }
                   8217:                         if (@newcoowners || $delcoowners) {
                   8218:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8219:                                             $delcoowners,@newcoowners);
                   8220:                         }
                   8221:                     }
                   8222:                 }
                   8223:             }
                   8224:         }
                   8225:     }
                   8226: }
                   8227: 
                   8228: sub store_coowners {
                   8229:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8230:     my $cid = $cdom.'_'.$cnum;
                   8231:     my ($coowners,$delresult,$putresult);
                   8232:     if (@newcoowners) {
                   8233:         $coowners = join(',',@newcoowners);
                   8234:         my %coownershash = (
                   8235:                             'internal.co-owners' => $coowners,
                   8236:                            );
                   8237:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8238:         if ($putresult eq 'ok') {
                   8239:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8240:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8241:             }
                   8242:         }
                   8243:     }
                   8244:     if ($delcoowners) {
                   8245:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8246:         if ($delresult eq 'ok') {
                   8247:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8248:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8249:             }
                   8250:         }
                   8251:     }
                   8252:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8253:         my %crsinfo =
                   8254:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8255:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8256:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8257:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8258:         }
                   8259:     }
                   8260: }
                   8261: 
1.169     harris41 8262: # -------------------------------------------------- Modify user authentication
1.197     www      8263: # Overrides without validation
                   8264: 
1.169     harris41 8265: sub modifyuserauth {
                   8266:     my ($udom,$uname,$umode,$upass)=@_;
                   8267:     my $uhome=&homeserver($uname,$udom);
1.197     www      8268:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8269:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8270:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8271:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8272:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8273: 		     &escape($upass),$uhome);
1.620     albertel 8274:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8275:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8276:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8277:     &log($udom,,$uname,$uhome,
1.620     albertel 8278:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8279:                                      $env{'user.name'}.', '.$umode.
1.197     www      8280:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8281:     unless ($reply eq 'ok') {
1.197     www      8282:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8283: 	return 'error: '.$reply;
                   8284:     }   
1.170     harris41 8285:     return 'ok';
1.80      www      8286: }
                   8287: 
1.81      www      8288: # --------------------------------------------------------------- Modify a user
1.80      www      8289: 
1.81      www      8290: sub modifyuser {
1.206     matthew  8291:     my ($udom,    $uname, $uid,
                   8292:         $umode,   $upass, $first,
                   8293:         $middle,  $last,  $gene,
1.1058    raeburn  8294:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8295:     $udom= &LONCAPA::clean_domain($udom);
                   8296:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8297:     my $showcandelete = 'none';
                   8298:     if (ref($candelete) eq 'ARRAY') {
                   8299:         if (@{$candelete} > 0) {
                   8300:             $showcandelete = join(', ',@{$candelete});
                   8301:         }
                   8302:     }
1.81      www      8303:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8304:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8305: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8306:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8307:                                      ' desiredhome not specified'). 
1.620     albertel 8308:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8309:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8310:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8311:     my $newuser;
                   8312:     if ($uhome eq 'no_host') {
                   8313:         $newuser = 1;
                   8314:     }
1.80      www      8315: # ----------------------------------------------------------------- Create User
1.406     albertel 8316:     if (($uhome eq 'no_host') && 
                   8317: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8318:         my $unhome='';
1.844     albertel 8319:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8320:             $unhome = $desiredhome;
1.620     albertel 8321: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8322: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8323:         } else { # load balancing routine for determining $unhome
1.81      www      8324:             my $loadm=10000000;
1.841     albertel 8325: 	    my %servers = &get_servers($udom,'library');
                   8326: 	    foreach my $tryserver (keys(%servers)) {
                   8327: 		my $answer=reply('load',$tryserver);
                   8328: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8329: 		    $loadm=$answer;
                   8330: 		    $unhome=$tryserver;
                   8331: 		}
1.80      www      8332: 	    }
                   8333:         }
                   8334:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8335: 	    return 'error: unable to find a home server for '.$uname.
                   8336:                    ' in domain '.$udom;
1.80      www      8337:         }
                   8338:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8339:                          &escape($upass),$unhome);
                   8340: 	unless ($reply eq 'ok') {
                   8341:             return 'error: '.$reply;
                   8342:         }   
1.230     stredwic 8343:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8344:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8345: 	    return 'error: unable verify users home machine.';
1.80      www      8346:         }
1.209     matthew  8347:     }   # End of creation of new user
1.80      www      8348: # ---------------------------------------------------------------------- Add ID
                   8349:     if ($uid) {
                   8350:        $uid=~tr/A-Z/a-z/;
                   8351:        my %uidhash=&idrget($udom,$uname);
1.196     www      8352:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8353:          && (!$forceid)) {
1.80      www      8354: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8355: 	      return 'error: user id "'.$uid.'" does not match '.
                   8356:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8357:           }
                   8358:        } else {
                   8359: 	  &idput($udom,($uname => $uid));
                   8360:        }
                   8361:     }
                   8362: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8363:     my @tmp=&get('environment',
1.899     raeburn  8364: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8365:                     'permanentemail','inststatus'],
1.134     albertel 8366: 		   $udom,$uname);
1.1075    raeburn  8367:     my (%names,%oldnames);
1.313     matthew  8368:     if ($tmp[0] =~ m/^error:.*/) { 
                   8369:         %names=(); 
                   8370:     } else {
                   8371:         %names = @tmp;
1.1075    raeburn  8372:         %oldnames = %names;
1.313     matthew  8373:     }
1.388     www      8374: #
1.1058    raeburn  8375: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8376: # of users did not contain them), do not overwrite existing values
                   8377: # unless field is in $candelete array ref.  
                   8378: #
                   8379: 
                   8380:     my @fields = ('firstname','middlename','lastname','generation',
                   8381:                   'permanentemail','id');
                   8382:     my %newvalues;
                   8383:     if (ref($candelete) eq 'ARRAY') {
                   8384:         foreach my $field (@fields) {
                   8385:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8386:                 if ($field eq 'firstname') {
                   8387:                     $names{$field} = $first;
                   8388:                 } elsif ($field eq 'middlename') {
                   8389:                     $names{$field} = $middle;
                   8390:                 } elsif ($field eq 'lastname') {
                   8391:                     $names{$field} = $last;
                   8392:                 } elsif ($field eq 'generation') { 
                   8393:                     $names{$field} = $gene;
                   8394:                 } elsif ($field eq 'permanentemail') {
                   8395:                     $names{$field} = $email;
                   8396:                 } elsif ($field eq 'id') {
                   8397:                     $names{$field}  = $uid;
                   8398:                 }
                   8399:             }
                   8400:         }
                   8401:     }
1.388     www      8402:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8403:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8404:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8405:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8406:     if ($email) {
                   8407:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8408:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8409:     }
1.899     raeburn  8410:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8411:     if (defined($inststatus)) {
                   8412:         $names{'inststatus'} = '';
                   8413:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8414:         if (ref($usertypes) eq 'HASH') {
                   8415:             my @okstatuses; 
                   8416:             foreach my $item (split(/:/,$inststatus)) {
                   8417:                 if (defined($usertypes->{$item})) {
                   8418:                     push(@okstatuses,$item);  
                   8419:                 }
                   8420:             }
                   8421:             if (@okstatuses) {
                   8422:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8423:             }
                   8424:         }
                   8425:     }
1.1075    raeburn  8426:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8427:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8428:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8429:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8430:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8431:     } else {
                   8432:         $logmsg .= ' during self creation';
                   8433:     }
1.1075    raeburn  8434:     my $changed;
                   8435:     if ($newuser) {
                   8436:         $changed = 1;
                   8437:     } else {
                   8438:         foreach my $field (@fields) {
                   8439:             if ($names{$field} ne $oldnames{$field}) {
                   8440:                 $changed = 1;
                   8441:                 last;
                   8442:             }
                   8443:         }
                   8444:     }
                   8445:     unless ($changed) {
                   8446:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8447:         &logthis($logmsg);
                   8448:         return 'ok';
                   8449:     }
                   8450:     my $reply = &put('environment', \%names, $udom,$uname);
                   8451:     if ($reply ne 'ok') { 
                   8452:         return 'error: '.$reply;
                   8453:     }
1.1087    raeburn  8454:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8455:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8456:     }
1.1075    raeburn  8457:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8458:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8459:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8460:     &logthis($logmsg);
1.134     albertel 8461:     return 'ok';
1.80      www      8462: }
                   8463: 
1.81      www      8464: # -------------------------------------------------------------- Modify student
1.80      www      8465: 
1.81      www      8466: sub modifystudent {
                   8467:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8468:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8469:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8470:     if (!$cid) {
1.620     albertel 8471: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8472: 	    return 'not_in_class';
                   8473: 	}
1.80      www      8474:     }
                   8475: # --------------------------------------------------------------- Make the user
1.81      www      8476:     my $reply=&modifyuser
1.209     matthew  8477: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8478:          $desiredhome,$email,$inststatus);
1.80      www      8479:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8480:     # This will cause &modify_student_enrollment to get the uid from the
                   8481:     # students environment
                   8482:     $uid = undef if (!$forceid);
1.455     albertel 8483:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8484: 					$gene,$usec,$end,$start,$type,$locktype,
                   8485:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8486:     return $reply;
                   8487: }
                   8488: 
                   8489: sub modify_student_enrollment {
1.1172.2.23  raeburn  8490:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8491:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8492:     my ($cdom,$cnum,$chome);
                   8493:     if (!$cid) {
1.620     albertel 8494: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8495: 	    return 'not_in_class';
                   8496: 	}
1.620     albertel 8497: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8498: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8499:     } else {
                   8500: 	($cdom,$cnum)=split(/_/,$cid);
                   8501:     }
1.620     albertel 8502:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8503:     if (!$chome) {
1.457     raeburn  8504: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8505:     }
1.455     albertel 8506:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8507:     # Make sure the user exists
1.81      www      8508:     my $uhome=&homeserver($uname,$udom);
                   8509:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8510: 	return 'error: no such user';
                   8511:     }
1.297     matthew  8512:     # Get student data if we were not given enough information
                   8513:     if (!defined($first)  || $first  eq '' || 
                   8514:         !defined($last)   || $last   eq '' || 
                   8515:         !defined($uid)    || $uid    eq '' || 
                   8516:         !defined($middle) || $middle eq '' || 
                   8517:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8518:         # They did not supply us with enough data to enroll the student, so
                   8519:         # we need to pick up more information.
1.297     matthew  8520:         my %tmp = &get('environment',
1.294     matthew  8521:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8522:                        ,$udom,$uname);
                   8523: 
1.800     albertel 8524:         #foreach my $key (keys(%tmp)) {
                   8525:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8526:         #}
1.294     matthew  8527:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8528:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8529:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8530:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8531:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8532:     }
1.556     albertel 8533:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8534:     my $user = "$uname:$udom";
                   8535:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8536:     my $reply=cput('classlist',
1.1148    raeburn  8537: 		   {$user => 
1.1172.2.19  raeburn  8538: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8539: 		   $cdom,$cnum);
1.1148    raeburn  8540:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8541:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8542:     } else { 
1.81      www      8543: 	return 'error: '.$reply;
                   8544:     }
1.297     matthew  8545:     # Add student role to user
1.83      www      8546:     my $uurl='/'.$cid;
1.81      www      8547:     $uurl=~s/\_/\//g;
                   8548:     if ($usec) {
                   8549: 	$uurl.='/'.$usec;
                   8550:     }
1.1148    raeburn  8551:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8552:                              $selfenroll,$context);
                   8553:     if ($result ne 'ok') {
                   8554:         if ($old_entry{$user} ne '') {
                   8555:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8556:         } else {
                   8557:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8558:         }
                   8559:     }
                   8560:     return $result; 
1.21      www      8561: }
                   8562: 
1.556     albertel 8563: sub format_name {
                   8564:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8565:     my $name;
                   8566:     if ($first ne 'lastname') {
                   8567: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8568:     } else {
                   8569: 	if ($lastname=~/\S/) {
                   8570: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8571: 	    $name=~s/\s+,/,/;
                   8572: 	} else {
                   8573: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8574: 	}
                   8575:     }
                   8576:     $name=~s/^\s+//;
                   8577:     $name=~s/\s+$//;
                   8578:     $name=~s/\s+/ /g;
                   8579:     return $name;
                   8580: }
                   8581: 
1.84      www      8582: # ------------------------------------------------- Write to course preferences
                   8583: 
                   8584: sub writecoursepref {
                   8585:     my ($courseid,%prefs)=@_;
                   8586:     $courseid=~s/^\///;
                   8587:     $courseid=~s/\_/\//g;
                   8588:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8589:     my $chome=homeserver($cnum,$cdomain);
                   8590:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8591: 	return 'error: no such course';
                   8592:     }
                   8593:     my $cstring='';
1.800     albertel 8594:     foreach my $pref (keys(%prefs)) {
                   8595: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8596:     }
1.84      www      8597:     $cstring=~s/\&$//;
                   8598:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8599: }
                   8600: 
                   8601: # ---------------------------------------------------------- Make/modify course
                   8602: 
                   8603: sub createcourse {
1.741     raeburn  8604:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8605:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8606:     $url=&declutter($url);
                   8607:     my $cid='';
1.1028    raeburn  8608:     if ($context eq 'requestcourses') {
                   8609:         my $can_create = 0;
                   8610:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8611:         if ($udom eq $ownerdom) {
                   8612:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8613:                                   $context)) {
                   8614:                 $can_create = 1;
                   8615:             }
                   8616:         } else {
                   8617:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8618:                                            $category);
                   8619:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8620:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8621:                 if (@curr > 0) {
                   8622:                     my @options = qw(approval validate autolimit);
                   8623:                     my $optregex = join('|',@options);
                   8624:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8625:                         $can_create = 1;
                   8626:                     }
                   8627:                 }
                   8628:             }
                   8629:         }
                   8630:         if ($can_create) {
                   8631:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8632:                 unless (&allowed('ccc',$udom)) {
                   8633:                     return 'refused'; 
                   8634:                 }
1.1017    raeburn  8635:             }
                   8636:         } else {
                   8637:             return 'refused';
                   8638:         }
1.1028    raeburn  8639:     } elsif (!&allowed('ccc',$udom)) {
                   8640:         return 'refused';
1.84      www      8641:     }
1.1011    raeburn  8642: # --------------------------------------------------------------- Get Unique ID
                   8643:     my $uname;
                   8644:     if ($cnum =~ /^$match_courseid$/) {
                   8645:         my $chome=&homeserver($cnum,$udom,'true');
                   8646:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8647:             $uname = $cnum;
                   8648:         } else {
1.1038    raeburn  8649:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8650:         }
                   8651:     } else {
1.1038    raeburn  8652:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8653:     }
                   8654:     return $uname if ($uname =~ /^error/);
                   8655: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8656:     if (!defined($course_server)) {
                   8657:         if (defined(&domain($udom,'primary'))) {
                   8658:             $course_server = &domain($udom,'primary');
                   8659:         } else {
                   8660:             $course_server = $env{'user.home'}; 
                   8661:         }
                   8662:     }
                   8663:     my %host_servers =
                   8664:         &Apache::lonnet::get_servers($udom,'library');
                   8665:     unless ($host_servers{$course_server}) {
                   8666:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8667:     }
1.84      www      8668: # ------------------------------------------------------------- Make the course
                   8669:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8670:                       $course_server);
1.84      www      8671:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8672:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8673:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8674: 	return 'error: no such course';
                   8675:     }
1.271     www      8676: # ----------------------------------------------------------------- Course made
1.516     raeburn  8677: # log existence
1.1029    raeburn  8678:     my $now = time;
1.918     raeburn  8679:     my $newcourse = {
                   8680:                     $udom.'_'.$uname => {
1.921     raeburn  8681:                                      description => $description,
                   8682:                                      inst_code   => $inst_code,
                   8683:                                      owner       => $course_owner,
                   8684:                                      type        => $crstype,
1.1029    raeburn  8685:                                      creator     => $env{'user.name'}.':'.
                   8686:                                                     $env{'user.domain'},
                   8687:                                      created     => $now,
                   8688:                                      context     => $context,
1.918     raeburn  8689:                                                 },
                   8690:                     };
1.921     raeburn  8691:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8692: # set toplevel url
1.271     www      8693:     my $topurl=$url;
                   8694:     unless ($nonstandard) {
                   8695: # ------------------------------------------ For standard courses, make top url
                   8696:         my $mapurl=&clutter($url);
1.278     www      8697:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8698:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8699: <map>
                   8700: <resource id="1" type="start"></resource>
                   8701: <resource id="2" src="$mapurl"></resource>
                   8702: <resource id="3" type="finish"></resource>
                   8703: <link index="1" from="1" to="2"></link>
                   8704: <link index="2" from="2" to="3"></link>
                   8705: </map>
                   8706: ENDINITMAP
                   8707:         $topurl=&declutter(
1.638     albertel 8708:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8709:                           );
                   8710:     }
                   8711: # ----------------------------------------------------------- Write preferences
1.84      www      8712:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8713:                      ('description'              => $description,
                   8714:                       'url'                      => $topurl,
                   8715:                       'internal.creator'         => $env{'user.name'}.':'.
                   8716:                                                     $env{'user.domain'},
                   8717:                       'internal.created'         => $now,
                   8718:                       'internal.creationcontext' => $context)
                   8719:                     );
1.84      www      8720:     return '/'.$udom.'/'.$uname;
                   8721: }
                   8722: 
1.1011    raeburn  8723: # ------------------------------------------------------------------- Create ID
                   8724: sub generate_coursenum {
1.1038    raeburn  8725:     my ($udom,$crstype) = @_;
1.1011    raeburn  8726:     my $domdesc = &domain($udom);
                   8727:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8728:     my $first;
                   8729:     if ($crstype eq 'Community') {
                   8730:         $first = '0';
                   8731:     } else {
                   8732:         $first = int(1+rand(9)); 
                   8733:     } 
                   8734:     my $uname=$first.
1.1011    raeburn  8735:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8736:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8737:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8738: # ----------------------------------------------- Make sure that does not exist
                   8739:     my $uhome=&homeserver($uname,$udom,'true');
                   8740:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8741:         if ($crstype eq 'Community') {
                   8742:             $first = '0';
                   8743:         } else {
                   8744:             $first = int(1+rand(9));
                   8745:         }
                   8746:         $uname=$first.
1.1011    raeburn  8747:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8748:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8749:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8750:         $uhome=&homeserver($uname,$udom,'true');
                   8751:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8752:             return 'error: unable to generate unique course-ID';
                   8753:         }
                   8754:     }
                   8755:     return $uname;
                   8756: }
                   8757: 
1.813     albertel 8758: sub is_course {
1.1167    droeschl 8759:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8760:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8761: 
                   8762:     return unless $cdom and $cnum;
                   8763: 
                   8764:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8765:         '.');
                   8766: 
1.1172.2.23  raeburn  8767:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8768:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8769: }
                   8770: 
1.1015    raeburn  8771: sub store_userdata {
                   8772:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8773:     my $result;
1.1016    raeburn  8774:     if ($datakey ne '') {
1.1013    raeburn  8775:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8776:             if ($udom eq '' || $uname eq '') {
                   8777:                 $udom = $env{'user.domain'};
                   8778:                 $uname = $env{'user.name'};
                   8779:             }
                   8780:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8781:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8782:                 $result = 'error: no_host';
                   8783:             } else {
                   8784:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8785:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8786: 
                   8787:                 my $namevalue='';
                   8788:                 foreach my $key (keys(%{$storehash})) {
                   8789:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8790:                 }
                   8791:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  8792:                 unless ($namespace eq 'courserequests') {
                   8793:                     $datakey = &escape($datakey);
                   8794:                 }
1.1105    raeburn  8795:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8796:                                   $namevalue,$uhome);
1.1013    raeburn  8797:             }
                   8798:         } else {
                   8799:             $result = 'error: data to store was not a hash reference'; 
                   8800:         }
                   8801:     } else {
                   8802:         $result= 'error: invalid requestkey'; 
                   8803:     }
                   8804:     return $result;
                   8805: }
                   8806: 
1.21      www      8807: # ---------------------------------------------------------- Assign Custom Role
                   8808: 
                   8809: sub assigncustomrole {
1.957     raeburn  8810:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8811:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8812:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8813: }
                   8814: 
                   8815: # ----------------------------------------------------------------- Revoke Role
                   8816: 
                   8817: sub revokerole {
1.957     raeburn  8818:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8819:     my $now=time;
1.965     raeburn  8820:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8821: }
                   8822: 
                   8823: # ---------------------------------------------------------- Revoke Custom Role
                   8824: 
                   8825: sub revokecustomrole {
1.957     raeburn  8826:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8827:     my $now=time;
1.357     www      8828:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8829:            $deleteflag,$selfenroll,$context);
1.17      www      8830: }
                   8831: 
1.533     banghart 8832: # ------------------------------------------------------------ Disk usage
1.535     albertel 8833: sub diskusage {
1.955     raeburn  8834:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8835:     $directorypath =~ s/\/$//;
                   8836:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8837:                        .&escape($getpropath).':'.&escape($uname).':'
                   8838:                        .&escape($udom),homeserver($uname,$udom));
                   8839:     if ($listing eq 'unknown_cmd') {
                   8840:         if ($getpropath) {
                   8841:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8842:         }
                   8843:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8844:     }
1.514     albertel 8845:     return $listing;
1.512     banghart 8846: }
                   8847: 
1.566     banghart 8848: sub is_locked {
1.1096    raeburn  8849:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8850:     my @check;
                   8851:     my $is_locked;
1.1093    raeburn  8852:     push (@check,$file_name);
1.613     albertel 8853:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8854: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8855:     my ($tmp)=keys(%locked);
                   8856:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8857:     
1.566     banghart 8858:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8859:         $is_locked = 'false';
                   8860:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8861:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8862:                $is_locked = 'true';
1.1096    raeburn  8863:                if (ref($which) eq 'ARRAY') {
                   8864:                    push(@{$which},$entry);
                   8865:                } else {
                   8866:                    last;
                   8867:                }
1.745     raeburn  8868:            }
                   8869:        }
1.566     banghart 8870:     } else {
                   8871:         $is_locked = 'false';
                   8872:     }
1.1093    raeburn  8873:     return $is_locked;
1.566     banghart 8874: }
                   8875: 
1.759     albertel 8876: sub declutter_portfile {
                   8877:     my ($file) = @_;
1.833     albertel 8878:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8879:     return $file;
                   8880: }
                   8881: 
1.559     banghart 8882: # ------------------------------------------------------------- Mark as Read Only
                   8883: 
                   8884: sub mark_as_readonly {
                   8885:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8886:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8887:     my ($tmp)=keys(%current_permissions);
                   8888:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8889:     foreach my $file (@{$files}) {
1.759     albertel 8890: 	$file = &declutter_portfile($file);
1.561     banghart 8891:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8892:     }
1.613     albertel 8893:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8894:     return;
                   8895: }
                   8896: 
1.572     banghart 8897: # ------------------------------------------------------------Save Selected Files
                   8898: 
                   8899: sub save_selected_files {
                   8900:     my ($user, $path, @files) = @_;
                   8901:     my $filename = $user."savedfiles";
1.573     banghart 8902:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8903:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8904:     foreach my $file (@files) {
1.620     albertel 8905:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8906:     }
                   8907:     foreach my $file (@other_files) {
1.574     banghart 8908:         print (OUT $file."\n");
1.572     banghart 8909:     }
1.574     banghart 8910:     close (OUT);
1.572     banghart 8911:     return 'ok';
                   8912: }
                   8913: 
1.574     banghart 8914: sub clear_selected_files {
                   8915:     my ($user) = @_;
                   8916:     my $filename = $user."savedfiles";
1.1117    foxr     8917:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8918:     print (OUT undef);
                   8919:     close (OUT);
                   8920:     return ("ok");    
                   8921: }
                   8922: 
1.572     banghart 8923: sub files_in_path {
                   8924:     my ($user, $path) = @_;
                   8925:     my $filename = $user."savedfiles";
                   8926:     my %return_files;
1.1117    foxr     8927:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8928:     while (my $line_in = <IN>) {
1.574     banghart 8929:         chomp ($line_in);
                   8930:         my @paths_and_file = split (m!/!, $line_in);
                   8931:         my $file_part = pop (@paths_and_file);
                   8932:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8933:         $path_part.='/';
                   8934:         my $path_and_file = $path_part.$file_part;
                   8935:         if ($path_part eq $path) {
                   8936:             $return_files{$file_part}= 'selected';
                   8937:         }
                   8938:     }
1.574     banghart 8939:     close (IN);
                   8940:     return (\%return_files);
1.572     banghart 8941: }
                   8942: 
                   8943: # called in portfolio select mode, to show files selected NOT in current directory
                   8944: sub files_not_in_path {
                   8945:     my ($user, $path) = @_;
                   8946:     my $filename = $user."savedfiles";
                   8947:     my @return_files;
                   8948:     my $path_part;
1.1117    foxr     8949:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8950:     while (my $line = <IN>) {
1.572     banghart 8951:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8952:         my @paths_and_file = split(m|/|, $line);
                   8953:         my $file_part = pop(@paths_and_file);
                   8954:         chomp($file_part);
                   8955:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8956:         $path_part .= '/';
                   8957:         my $path_and_file = $path_part.$file_part;
                   8958:         if ($path_part ne $path) {
1.800     albertel 8959:             push(@return_files, ($path_and_file));
1.572     banghart 8960:         }
                   8961:     }
1.800     albertel 8962:     close(OUT);
1.574     banghart 8963:     return (@return_files);
1.572     banghart 8964: }
                   8965: 
1.745     raeburn  8966: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8967: 
1.745     raeburn  8968: sub get_portfile_permissions {
                   8969:     my ($domain,$user) = @_;
1.613     albertel 8970:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8971:     my ($tmp)=keys(%current_permissions);
                   8972:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8973:     return \%current_permissions;
                   8974: }
                   8975: 
                   8976: #---------------------------------------------Get portfolio file access controls
                   8977: 
1.749     raeburn  8978: sub get_access_controls {
1.745     raeburn  8979:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8980:     my %access;
                   8981:     my $real_file = $file;
                   8982:     $file =~ s/\.meta$//;
1.745     raeburn  8983:     if (defined($file)) {
1.749     raeburn  8984:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8985:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8986:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8987:             }
                   8988:         }
1.745     raeburn  8989:     } else {
1.749     raeburn  8990:         foreach my $key (keys(%{$current_permissions})) {
                   8991:             if ($key =~ /\0accesscontrol$/) {
                   8992:                 if (defined($group)) {
                   8993:                     if ($key !~ m-^\Q$group\E/-) {
                   8994:                         next;
                   8995:                     }
                   8996:                 }
                   8997:                 my ($fullpath) = split(/\0/,$key);
                   8998:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8999:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9000:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9001:                     }
                   9002:                 }
                   9003:             }
                   9004:         }
                   9005:     }
                   9006:     return %access;
                   9007: }
                   9008: 
                   9009: sub modify_access_controls {
                   9010:     my ($file_name,$changes,$domain,$user)=@_;
                   9011:     my ($outcome,$deloutcome);
                   9012:     my %store_permissions;
                   9013:     my %new_values;
                   9014:     my %new_control;
                   9015:     my %translation;
                   9016:     my @deletions = ();
                   9017:     my $now = time;
                   9018:     if (exists($$changes{'activate'})) {
                   9019:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9020:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9021:             my $numnew = scalar(@newitems);
                   9022:             for (my $i=0; $i<$numnew; $i++) {
                   9023:                 my $newkey = $newitems[$i];
                   9024:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9025:                 if ($newkey =~ /^\d+:/) { 
                   9026:                     $newkey =~ s/^(\d+)/$newid/;
                   9027:                     $translation{$1} = $newid;
                   9028:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9029:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9030:                     $translation{$1} = $newid;
                   9031:                 }
1.749     raeburn  9032:                 $new_values{$file_name."\0".$newkey} = 
                   9033:                                           $$changes{'activate'}{$newitems[$i]};
                   9034:                 $new_control{$newkey} = $now;
                   9035:             }
                   9036:         }
                   9037:     }
                   9038:     my %todelete;
                   9039:     my %changed_items;
                   9040:     foreach my $action ('delete','update') {
                   9041:         if (exists($$changes{$action})) {
                   9042:             if (ref($$changes{$action}) eq 'HASH') {
                   9043:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9044:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9045:                     if ($action eq 'delete') { 
                   9046:                         $todelete{$itemnum} = 1;
                   9047:                     } else {
                   9048:                         $changed_items{$itemnum} = $key;
                   9049:                     }
                   9050:                 }
1.745     raeburn  9051:             }
                   9052:         }
1.749     raeburn  9053:     }
                   9054:     # get lock on access controls for file.
                   9055:     my $lockhash = {
                   9056:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9057:                                                        ':'.$env{'user.domain'},
                   9058:                    }; 
                   9059:     my $tries = 0;
                   9060:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9061:    
                   9062:     while (($gotlock ne 'ok') && $tries <3) {
                   9063:         $tries ++;
                   9064:         sleep 1;
                   9065:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9066:     }
                   9067:     if ($gotlock eq 'ok') {
                   9068:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9069:         my ($tmp)=keys(%curr_permissions);
                   9070:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9071:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9072:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9073:             if (ref($curr_controls) eq 'HASH') {
                   9074:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9075:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9076:                     if (defined($todelete{$itemnum})) {
                   9077:                         push(@deletions,$file_name."\0".$control_item);
                   9078:                     } else {
                   9079:                         if (defined($changed_items{$itemnum})) {
                   9080:                             $new_control{$changed_items{$itemnum}} = $now;
                   9081:                             push(@deletions,$file_name."\0".$control_item);
                   9082:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9083:                         } else {
                   9084:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9085:                         }
                   9086:                     }
1.745     raeburn  9087:                 }
                   9088:             }
                   9089:         }
1.970     raeburn  9090:         my ($group);
                   9091:         if (&is_course($domain,$user)) {
                   9092:             ($group,my $file) = split(/\//,$file_name,2);
                   9093:         }
1.749     raeburn  9094:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9095:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9096:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9097:         #  remove lock
                   9098:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9099:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9100:         my $sqlresult =
1.970     raeburn  9101:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9102:                                     $group);
1.749     raeburn  9103:     } else {
                   9104:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9105:     }
1.749     raeburn  9106:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9107: }
                   9108: 
1.827     raeburn  9109: sub make_public_indefinitely {
                   9110:     my ($requrl) = @_;
                   9111:     my $now = time;
                   9112:     my $action = 'activate';
                   9113:     my $aclnum = 0;
                   9114:     if (&is_portfolio_url($requrl)) {
                   9115:         my (undef,$udom,$unum,$file_name,$group) =
                   9116:             &parse_portfolio_url($requrl);
                   9117:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9118:         my %access_controls = &get_access_controls($current_perms,
                   9119:                                                    $group,$file_name);
                   9120:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9121:             my ($num,$scope,$end,$start) = 
                   9122:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9123:             if ($scope eq 'public') {
                   9124:                 if ($start <= $now && $end == 0) {
                   9125:                     $action = 'none';
                   9126:                 } else {
                   9127:                     $action = 'update';
                   9128:                     $aclnum = $num;
                   9129:                 }
                   9130:                 last;
                   9131:             }
                   9132:         }
                   9133:         if ($action eq 'none') {
                   9134:              return 'ok';
                   9135:         } else {
                   9136:             my %changes;
                   9137:             my $newend = 0;
                   9138:             my $newstart = $now;
                   9139:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9140:             $changes{$action}{$newkey} = {
                   9141:                 type => 'public',
                   9142:                 time => {
                   9143:                     start => $newstart,
                   9144:                     end   => $newend,
                   9145:                 },
                   9146:             };
                   9147:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9148:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9149:             return $outcome;
                   9150:         }
                   9151:     } else {
                   9152:         return 'invalid';
                   9153:     }
                   9154: }
                   9155: 
1.745     raeburn  9156: #------------------------------------------------------Get Marked as Read Only
                   9157: 
                   9158: sub get_marked_as_readonly {
                   9159:     my ($domain,$user,$what,$group) = @_;
                   9160:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9161:     my @readonly_files;
1.629     banghart 9162:     my $cmp1=$what;
                   9163:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9164:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9165:         if (defined($group)) {
                   9166:             if ($file_name !~ m-^\Q$group\E/-) {
                   9167:                 next;
                   9168:             }
                   9169:         }
1.561     banghart 9170:         if (ref($value) eq "ARRAY"){
                   9171:             foreach my $stored_what (@{$value}) {
1.629     banghart 9172:                 my $cmp2=$stored_what;
1.759     albertel 9173:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9174:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9175:                 }
1.629     banghart 9176:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9177:                     push(@readonly_files, $file_name);
1.745     raeburn  9178:                     last;
1.563     banghart 9179:                 } elsif (!defined($what)) {
                   9180:                     push(@readonly_files, $file_name);
1.745     raeburn  9181:                     last;
1.561     banghart 9182:                 }
                   9183:             }
1.745     raeburn  9184:         }
1.561     banghart 9185:     }
                   9186:     return @readonly_files;
                   9187: }
1.577     banghart 9188: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9189: 
1.577     banghart 9190: sub get_marked_as_readonly_hash {
1.745     raeburn  9191:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9192:     my %readonly_files;
1.745     raeburn  9193:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9194:         if (defined($group)) {
                   9195:             if ($file_name !~ m-^\Q$group\E/-) {
                   9196:                 next;
                   9197:             }
                   9198:         }
1.577     banghart 9199:         if (ref($value) eq "ARRAY"){
                   9200:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9201:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9202:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9203:                         if ($lock_descriptor eq 'graded') {
                   9204:                             $readonly_files{$file_name} = 'graded';
                   9205:                         } elsif ($lock_descriptor eq 'handback') {
                   9206:                             $readonly_files{$file_name} = 'handback';
                   9207:                         } else {
                   9208:                             if (!exists($readonly_files{$file_name})) {
                   9209:                                 $readonly_files{$file_name} = 'locked';
                   9210:                             }
                   9211:                         }
1.745     raeburn  9212:                     }
1.750     banghart 9213:                 } 
1.577     banghart 9214:             }
                   9215:         } 
                   9216:     }
                   9217:     return %readonly_files;
                   9218: }
1.559     banghart 9219: # ------------------------------------------------------------ Unmark as Read Only
                   9220: 
                   9221: sub unmark_as_readonly {
1.629     banghart 9222:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9223:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9224:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9225:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9226:     my $symb_crs = $what;
                   9227:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9228:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9229:     my ($tmp)=keys(%current_permissions);
                   9230:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9231:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9232:     foreach my $file (@readonly_files) {
1.759     albertel 9233: 	my $clean_file = &declutter_portfile($file);
                   9234: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9235: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9236:         my @new_locks;
                   9237:         my @del_keys;
                   9238:         if (ref($current_locks) eq "ARRAY"){
                   9239:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9240:                 my $compare=$locker;
1.749     raeburn  9241:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9242:                     $compare=join('',@{$locker});
1.746     raeburn  9243:                     if ($compare ne $symb_crs) {
                   9244:                         push(@new_locks, $locker);
                   9245:                     }
1.563     banghart 9246:                 }
                   9247:             }
1.650     albertel 9248:             if (scalar(@new_locks) > 0) {
1.563     banghart 9249:                 $current_permissions{$file} = \@new_locks;
                   9250:             } else {
                   9251:                 push(@del_keys, $file);
1.613     albertel 9252:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9253:                 delete($current_permissions{$file});
1.563     banghart 9254:             }
                   9255:         }
1.561     banghart 9256:     }
1.613     albertel 9257:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9258:     return;
                   9259: }
1.512     banghart 9260: 
1.17      www      9261: # ------------------------------------------------------------ Directory lister
                   9262: 
                   9263: sub dirlist {
1.955     raeburn  9264:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9265:     $uri=~s/^\///;
                   9266:     $uri=~s/\/$//;
1.253     stredwic 9267:     my ($udom, $uname);
1.955     raeburn  9268:     if ($getuserdir) {
1.253     stredwic 9269:         $udom = $userdomain;
                   9270:         $uname = $username;
1.955     raeburn  9271:     } else {
                   9272:         (undef,$udom,$uname)=split(/\//,$uri);
                   9273:         if(defined($userdomain)) {
                   9274:             $udom = $userdomain;
                   9275:         }
                   9276:         if(defined($username)) {
                   9277:             $uname = $username;
                   9278:         }
1.253     stredwic 9279:     }
1.955     raeburn  9280:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9281: 
1.955     raeburn  9282:     $dirRoot = $perlvar{'lonDocRoot'};
                   9283:     if (defined($getpropath)) {
                   9284:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9285:         $dirRoot =~ s/\/$//;
1.955     raeburn  9286:     } elsif (defined($getuserdir)) {
                   9287:         my $subdir=$uname.'__';
                   9288:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9289:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9290:                    ."/$udom/$subdir/$uname";
                   9291:     } elsif (defined($alternateRoot)) {
                   9292:         $dirRoot = $alternateRoot;
1.751     banghart 9293:     }
1.253     stredwic 9294: 
                   9295:     if($udom) {
                   9296:         if($uname) {
1.1135    raeburn  9297:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9298:             if ($uhome eq 'no_host') {
                   9299:                 return ([],'no_host');
                   9300:             }
1.955     raeburn  9301:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9302:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9303:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9304:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9305:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9306:             } else {
                   9307:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9308:             }
1.605     matthew  9309:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9310:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9311:                 @listing_results = split(/:/,$listing);
                   9312:             } else {
                   9313:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9314:             }
1.1135    raeburn  9315:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9316:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9317:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9318:                 return ([],$listing);
                   9319:             } else {
                   9320:                 return (\@listing_results);
1.1135    raeburn  9321:             }
1.955     raeburn  9322:         } elsif(!$alternateRoot) {
1.1136    raeburn  9323:             my (%allusers,%listerror);
1.841     albertel 9324: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9325:  	    foreach my $tryserver (keys(%servers)) {
                   9326:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9327:                                   &escape($udom),$tryserver);
                   9328:                 if ($listing eq 'unknown_cmd') {
                   9329: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9330: 				      $udom, $tryserver);
                   9331:                 } else {
                   9332:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9333:                 }
1.841     albertel 9334: 		if ($listing eq 'unknown_cmd') {
                   9335: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9336: 				      $udom, $tryserver);
                   9337: 		    @listing_results = split(/:/,$listing);
                   9338: 		} else {
                   9339: 		    @listing_results =
                   9340: 			map { &unescape($_); } split(/:/,$listing);
                   9341: 		}
1.1136    raeburn  9342:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9343:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9344:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9345:                     $listerror{$tryserver} = $listing;
                   9346:                 } else {
1.841     albertel 9347: 		    foreach my $line (@listing_results) {
                   9348: 			my ($entry) = split(/&/,$line,2);
                   9349: 			$allusers{$entry} = 1;
                   9350: 		    }
                   9351: 		}
1.253     stredwic 9352:             }
1.1136    raeburn  9353:             my @alluserslist=();
1.800     albertel 9354:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9355:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9356:             }
1.1136    raeburn  9357:             return (\@alluserslist);
1.253     stredwic 9358:         } else {
1.1136    raeburn  9359:             return ([],'missing username');
1.253     stredwic 9360:         }
1.955     raeburn  9361:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9362:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9363:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9364:         return (\@all_domains);
1.955     raeburn  9365:     } else {
1.1136    raeburn  9366:         return ([],'missing domain');
1.275     stredwic 9367:     }
                   9368: }
                   9369: 
                   9370: # --------------------------------------------- GetFileTimestamp
                   9371: # This function utilizes dirlist and returns the date stamp for
                   9372: # when it was last modified.  It will also return an error of -1
                   9373: # if an error occurs
                   9374: 
                   9375: sub GetFileTimestamp {
1.955     raeburn  9376:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9377:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9378:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9379:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9380:                                     undef,$getuserdir);
                   9381:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9382:         return -1;
                   9383:     }
                   9384:     if (ref($fileref) eq 'ARRAY') {
                   9385:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9386:         # @stats contains first the filename, then the stat output
                   9387:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9388:     } else {
                   9389:         return -1;
1.253     stredwic 9390:     }
1.26      www      9391: }
                   9392: 
1.712     albertel 9393: sub stat_file {
                   9394:     my ($uri) = @_;
1.787     albertel 9395:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9396: 
1.955     raeburn  9397:     my ($udom,$uname,$file);
1.712     albertel 9398:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9399: 	($udom,$uname,$file) =
1.811     albertel 9400: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9401: 	$file = 'userfiles/'.$file;
                   9402:     }
                   9403:     if ($uri =~ m-^/res/-) {
                   9404: 	($udom,$uname) = 
1.807     albertel 9405: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9406: 	$file = $uri;
                   9407:     }
                   9408: 
                   9409:     if (!$udom || !$uname || !$file) {
                   9410: 	# unable to handle the uri
                   9411: 	return ();
                   9412:     }
1.956     raeburn  9413:     my $getpropath;
                   9414:     if ($file =~ /^userfiles\//) {
                   9415:         $getpropath = 1;
                   9416:     }
1.1136    raeburn  9417:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9418:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9419:         return ();
                   9420:     } else {
                   9421:         if (ref($listref) eq 'ARRAY') {
                   9422:             my @stats = split('&',$listref->[0]);
                   9423: 	    shift(@stats); #filename is first
                   9424: 	    return @stats;
                   9425:         }
1.712     albertel 9426:     }
                   9427:     return ();
                   9428: }
                   9429: 
1.26      www      9430: # -------------------------------------------------------- Value of a Condition
                   9431: 
1.713     albertel 9432: # gets the value of a specific preevaluated condition
                   9433: #    stored in the string  $env{user.state.<cid>}
                   9434: # or looks up a condition reference in the bighash and if if hasn't
                   9435: # already been evaluated recurses into docondval to get the value of
                   9436: # the condition, then memoizing it to 
                   9437: #   $env{user.state.<cid>.<condition>}
1.40      www      9438: sub directcondval {
                   9439:     my $number=shift;
1.620     albertel 9440:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9441: 	&Apache::lonuserstate::evalstate();
                   9442:     }
1.713     albertel 9443:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9444: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9445:     } elsif ($number =~ /^_/) {
                   9446: 	my $sub_condition;
                   9447: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9448: 		&GDBM_READER(),0640)) {
                   9449: 	    $sub_condition=$bighash{'conditions'.$number};
                   9450: 	    untie(%bighash);
                   9451: 	}
                   9452: 	my $value = &docondval($sub_condition);
1.949     raeburn  9453: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9454: 	return $value;
                   9455:     }
1.620     albertel 9456:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9457:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9458:     } else {
                   9459:        return 2;
                   9460:     }
                   9461: }
                   9462: 
1.713     albertel 9463: # get the collection of conditions for this resource
1.26      www      9464: sub condval {
                   9465:     my $condidx=shift;
1.54      www      9466:     my $allpathcond='';
1.713     albertel 9467:     foreach my $cond (split(/\|/,$condidx)) {
                   9468: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9469: 	    $allpathcond.=
                   9470: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9471: 	}
1.191     harris41 9472:     }
1.54      www      9473:     $allpathcond=~s/\|$//;
1.713     albertel 9474:     return &docondval($allpathcond);
                   9475: }
                   9476: 
                   9477: #evaluates an expression of conditions
                   9478: sub docondval {
                   9479:     my ($allpathcond) = @_;
                   9480:     my $result=0;
                   9481:     if ($env{'request.course.id'}
                   9482: 	&& defined($allpathcond)) {
                   9483: 	my $operand='|';
                   9484: 	my @stack;
                   9485: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9486: 	    if ($chunk eq '(') {
                   9487: 		push @stack,($operand,$result);
                   9488: 	    } elsif ($chunk eq ')') {
                   9489: 		my $before=pop @stack;
                   9490: 		if (pop @stack eq '&') {
                   9491: 		    $result=$result>$before?$before:$result;
                   9492: 		} else {
                   9493: 		    $result=$result>$before?$result:$before;
                   9494: 		}
                   9495: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9496: 		$operand=$chunk;
                   9497: 	    } else {
                   9498: 		my $new=directcondval($chunk);
                   9499: 		if ($operand eq '&') {
                   9500: 		    $result=$result>$new?$new:$result;
                   9501: 		} else {
                   9502: 		    $result=$result>$new?$result:$new;
                   9503: 		}
                   9504: 	    }
                   9505: 	}
1.26      www      9506:     }
                   9507:     return $result;
1.421     albertel 9508: }
                   9509: 
                   9510: # ---------------------------------------------------- Devalidate courseresdata
                   9511: 
                   9512: sub devalidatecourseresdata {
                   9513:     my ($coursenum,$coursedomain)=@_;
                   9514:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9515:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9516: }
                   9517: 
1.763     www      9518: 
1.200     www      9519: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9520: #
                   9521: #  Parameters:
                   9522: #      $coursenum    - Number of the course.
                   9523: #      $coursedomain - Domain at which the course was created.
                   9524: #  Returns:
                   9525: #     A hash of the course parameters along (I think) with timestamps
                   9526: #     and version info.
1.877     foxr     9527: 
1.624     albertel 9528: sub get_courseresdata {
                   9529:     my ($coursenum,$coursedomain)=@_;
1.200     www      9530:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9531:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9532:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9533:     my %dumpreply;
1.417     albertel 9534:     unless (defined($cached)) {
1.624     albertel 9535: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9536: 	$result=\%dumpreply;
1.251     albertel 9537: 	my ($tmp) = keys(%dumpreply);
                   9538: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9539: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9540: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9541: 	    return $tmp;
1.416     albertel 9542: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9543: 	    $result=undef;
1.599     albertel 9544: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9545: 	}
                   9546:     }
1.624     albertel 9547:     return $result;
                   9548: }
                   9549: 
1.633     albertel 9550: sub devalidateuserresdata {
                   9551:     my ($uname,$udom)=@_;
                   9552:     my $hashid="$udom:$uname";
                   9553:     &devalidate_cache_new('userres',$hashid);
                   9554: }
                   9555: 
1.624     albertel 9556: sub get_userresdata {
                   9557:     my ($uname,$udom)=@_;
                   9558:     #most student don\'t have any data set, check if there is some data
                   9559:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9560: 
                   9561:     my $hashid="$udom:$uname";
                   9562:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9563:     if (!defined($cached)) {
                   9564: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9565: 	$result=\%resourcedata;
                   9566: 	&do_cache_new('userres',$hashid,$result,600);
                   9567:     }
                   9568:     my ($tmp)=keys(%$result);
                   9569:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9570: 	return $result;
                   9571:     }
                   9572:     #error 2 occurs when the .db doesn't exist
                   9573:     if ($tmp!~/error: 2 /) {
1.672     albertel 9574: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9575: 		 " Trying to get resource data for ".
                   9576: 		 $uname." at ".$udom.": ".
                   9577: 		 $tmp."</font>");
                   9578:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9579: 	#&EXT_cache_set($udom,$uname);
                   9580: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9581: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9582:     }
                   9583:     return $tmp;
                   9584: }
1.879     foxr     9585: #----------------------------------------------- resdata - return resource data
                   9586: #  Purpose:
                   9587: #    Return resource data for either users or for a course.
                   9588: #  Parameters:
                   9589: #     $name      - Course/user name.
                   9590: #     $domain    - Name of the domain the user/course is registered on.
                   9591: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9592: #     @which     - Array of names of resources desired.
                   9593: #  Returns:
                   9594: #     The value of the first reasource in @which that is found in the
                   9595: #     resource hash.
                   9596: #  Exceptional Conditions:
                   9597: #     If the $type passed in is not valid (not the string 'course' or 
                   9598: #     'user', an undefined  reference is returned.
                   9599: #     If none of the resources are found, an undef is returned
1.624     albertel 9600: sub resdata {
                   9601:     my ($name,$domain,$type,@which)=@_;
                   9602:     my $result;
                   9603:     if ($type eq 'course') {
                   9604: 	$result=&get_courseresdata($name,$domain);
                   9605:     } elsif ($type eq 'user') {
                   9606: 	$result=&get_userresdata($name,$domain);
                   9607:     }
                   9608:     if (!ref($result)) { return $result; }    
1.251     albertel 9609:     foreach my $item (@which) {
1.927     albertel 9610: 	if (defined($result->{$item->[0]})) {
                   9611: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9612: 	}
1.250     albertel 9613:     }
1.291     albertel 9614:     return undef;
1.200     www      9615: }
                   9616: 
1.379     matthew  9617: #
                   9618: # EXT resource caching routines
                   9619: #
                   9620: 
                   9621: sub clear_EXT_cache_status {
1.383     albertel 9622:     &delenv('cache.EXT.');
1.379     matthew  9623: }
                   9624: 
                   9625: sub EXT_cache_status {
                   9626:     my ($target_domain,$target_user) = @_;
1.383     albertel 9627:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9628:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9629:         # We know already the user has no data
                   9630:         return 1;
                   9631:     } else {
                   9632:         return 0;
                   9633:     }
                   9634: }
                   9635: 
                   9636: sub EXT_cache_set {
                   9637:     my ($target_domain,$target_user) = @_;
1.383     albertel 9638:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9639:     #&appenv({$cachename => time});
1.379     matthew  9640: }
                   9641: 
1.28      www      9642: # --------------------------------------------------------- Value of a Variable
1.58      www      9643: sub EXT {
1.715     albertel 9644: 
1.1172.2.28  raeburn  9645:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9646:     unless ($varname) { return ''; }
1.218     albertel 9647:     #get real user name/domain, courseid and symb
                   9648:     my $courseid;
1.359     albertel 9649:     my $publicuser;
1.427     www      9650:     if ($symbparm) {
                   9651: 	$symbparm=&get_symb_from_alias($symbparm);
                   9652:     }
1.218     albertel 9653:     if (!($uname && $udom)) {
1.790     albertel 9654:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9655:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9656:     } else {
1.620     albertel 9657: 	$courseid=$env{'request.course.id'};
1.218     albertel 9658:     }
1.48      www      9659:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9660:     my $rest;
1.320     albertel 9661:     if (defined($therest[0])) {
1.48      www      9662:        $rest=join('.',@therest);
                   9663:     } else {
                   9664:        $rest='';
                   9665:     }
1.320     albertel 9666: 
1.57      www      9667:     my $qualifierrest=$qualifier;
                   9668:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9669:     my $spacequalifierrest=$space;
                   9670:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9671:     if ($realm eq 'user') {
1.48      www      9672: # --------------------------------------------------------------- user.resource
                   9673: 	if ($space eq 'resource') {
1.651     albertel 9674: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9675: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9676: 		 &&
1.744     albertel 9677: 		 ($symbparm eq &symbread()) ) {	
                   9678: 		# if we are in the middle of processing the resource the
                   9679: 		# get the value we are planning on committing
                   9680:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9681:                     return $Apache::lonhomework::results{$qualifierrest};
                   9682:                 } else {
                   9683:                     return $Apache::lonhomework::history{$qualifierrest};
                   9684:                 }
1.335     albertel 9685: 	    } else {
1.359     albertel 9686: 		my %restored;
1.620     albertel 9687: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9688: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9689: 		} else {
                   9690: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9691: 		}
1.335     albertel 9692: 		return $restored{$qualifierrest};
                   9693: 	    }
1.48      www      9694: # ----------------------------------------------------------------- user.access
                   9695:         } elsif ($space eq 'access') {
1.218     albertel 9696: 	    # FIXME - not supporting calls for a specific user
1.48      www      9697:             return &allowed($qualifier,$rest);
                   9698: # ------------------------------------------ user.preferences, user.environment
                   9699:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9700: 	    if (($uname eq $env{'user.name'}) &&
                   9701: 		($udom eq $env{'user.domain'})) {
                   9702: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9703: 	    } else {
1.359     albertel 9704: 		my %returnhash;
                   9705: 		if (!$publicuser) {
                   9706: 		    %returnhash=&userenvironment($udom,$uname,
                   9707: 						 $qualifierrest);
                   9708: 		}
1.218     albertel 9709: 		return $returnhash{$qualifierrest};
                   9710: 	    }
1.48      www      9711: # ----------------------------------------------------------------- user.course
                   9712:         } elsif ($space eq 'course') {
1.218     albertel 9713: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9714:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9715: # ------------------------------------------------------------------- user.role
                   9716:         } elsif ($space eq 'role') {
1.218     albertel 9717: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9718:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9719:             if ($qualifier eq 'value') {
                   9720: 		return $role;
                   9721:             } elsif ($qualifier eq 'extent') {
                   9722:                 return $where;
                   9723:             }
                   9724: # ----------------------------------------------------------------- user.domain
                   9725:         } elsif ($space eq 'domain') {
1.218     albertel 9726:             return $udom;
1.48      www      9727: # ------------------------------------------------------------------- user.name
                   9728:         } elsif ($space eq 'name') {
1.218     albertel 9729:             return $uname;
1.48      www      9730: # ---------------------------------------------------- Any other user namespace
1.29      www      9731:         } else {
1.359     albertel 9732: 	    my %reply;
                   9733: 	    if (!$publicuser) {
                   9734: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9735: 	    }
                   9736: 	    return $reply{$qualifierrest};
1.48      www      9737:         }
1.236     www      9738:     } elsif ($realm eq 'query') {
                   9739: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9740:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9741: 						[$spacequalifierrest]);
1.620     albertel 9742: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9743:    } elsif ($realm eq 'request') {
1.48      www      9744: # ------------------------------------------------------------- request.browser
                   9745:         if ($space eq 'browser') {
1.1145    bisitz   9746:             return $env{'browser.'.$qualifier};
1.57      www      9747: # ------------------------------------------------------------ request.filename
                   9748:         } else {
1.620     albertel 9749:             return $env{'request.'.$spacequalifierrest};
1.29      www      9750:         }
1.28      www      9751:     } elsif ($realm eq 'course') {
1.48      www      9752: # ---------------------------------------------------------- course.description
1.620     albertel 9753:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9754:     } elsif ($realm eq 'resource') {
1.165     www      9755: 
1.620     albertel 9756: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9757: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9758: 	}
1.693     albertel 9759: 
1.1172.2.30! raeburn  9760:         if ($qualifier eq '') {
        !          9761: 	    if ($space eq 'title') {
        !          9762: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
        !          9763: 	        return &gettitle($symbparm);
        !          9764: 	    }
1.693     albertel 9765: 	
1.1172.2.30! raeburn  9766: 	    if ($space eq 'map') {
        !          9767: 	        my ($map) = &decode_symb($symbparm);
        !          9768: 	        return &symbread($map);
        !          9769: 	    }
        !          9770:             if ($space eq 'maptitle') {
        !          9771:                 my ($map) = &decode_symb($symbparm);
        !          9772:                 return &gettitle($map);
        !          9773:             }
        !          9774: 	    if ($space eq 'filename') {
        !          9775: 	        if ($symbparm) {
        !          9776: 		    return &clutter((&decode_symb($symbparm))[2]);
        !          9777: 	        }
        !          9778: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9779: 	    }
1.1172.2.30! raeburn  9780: 
        !          9781:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
        !          9782:                 if ($space eq 'visibleparts') {
        !          9783:                     my $navmap = Apache::lonnavmaps::navmap->new();
        !          9784:                     my $item;
        !          9785:                     if (ref($navmap)) {
        !          9786:                         my $res = $navmap->getBySymb($symbparm);
        !          9787:                         my $parts = $res->parts();
        !          9788:                         if (ref($parts) eq 'ARRAY') {
        !          9789:                             $item = join(',',@{$parts});
        !          9790:                         }
        !          9791:                         undef($navmap);
        !          9792:                     }
        !          9793:                     return $item;
        !          9794:                 }
        !          9795:             }
        !          9796:         }
1.693     albertel 9797: 
                   9798: 	my ($section, $group, @groups);
1.593     albertel 9799: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  9800:         if (($courseid eq '') && ($cid)) {
                   9801:             $courseid = $cid;
                   9802:         }
                   9803: 	if (($symbparm && $courseid) && 
                   9804: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      9805: 
1.218     albertel 9806: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9807: 
1.60      www      9808: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9809: 	    my $symbp=$symbparm;
1.735     albertel 9810: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9811: 
                   9812: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9813: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9814: 
1.620     albertel 9815: 	    if (($env{'user.name'} eq $uname) &&
                   9816: 		($env{'user.domain'} eq $udom)) {
                   9817: 		$section=$env{'request.course.sec'};
1.733     raeburn  9818:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9819:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9820: 	    } else {
1.539     albertel 9821: 		if (! defined($usection)) {
1.551     albertel 9822: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9823: 		} else {
                   9824: 		    $section = $usection;
                   9825: 		}
1.733     raeburn  9826:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9827: 	    }
                   9828: 
                   9829: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9830: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9831: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9832: 
1.593     albertel 9833: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9834: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9835: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9836: 
1.60      www      9837: # ----------------------------------------------------------- first, check user
1.624     albertel 9838: 
                   9839: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9840: 				       ([$courselevelr,'resource'],
                   9841: 					[$courselevelm,'map'     ],
                   9842: 					[$courselevel, 'course'  ]));
1.931     albertel 9843: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9844: 
1.594     albertel 9845: # ------------------------------------------------ second, check some of course
1.684     raeburn  9846:             my $coursereply;
1.691     raeburn  9847:             if (@groups > 0) {
                   9848:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9849:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9850:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9851:             }
1.96      www      9852: 
1.684     raeburn  9853: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9854: 				  $env{'course.'.$courseid.'.domain'},
                   9855: 				  'course',
                   9856: 				  ([$seclevelr,   'resource'],
                   9857: 				   [$seclevelm,   'map'     ],
                   9858: 				   [$seclevel,    'course'  ],
                   9859: 				   [$courselevelr,'resource']));
                   9860: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9861: 
1.60      www      9862: # ------------------------------------------------------ third, check map parms
1.218     albertel 9863: 	    my %parmhash=();
                   9864: 	    my $thisparm='';
                   9865: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9866: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9867: 		    &GDBM_READER(),0640)) {
1.218     albertel 9868: 		$thisparm=$parmhash{$symbparm};
                   9869: 		untie(%parmhash);
                   9870: 	    }
1.927     albertel 9871: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9872: 	}
1.594     albertel 9873: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9874: 
1.218     albertel 9875: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9876: 	my $filename;
                   9877: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9878: 	if ($symbparm) {
1.409     www      9879: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9880: 	} else {
1.620     albertel 9881: 	    $filename=$env{'request.filename'};
1.282     albertel 9882: 	}
                   9883: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9884: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9885: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9886: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9887: 
1.927     albertel 9888: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9889: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9890: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9891: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9892: 				     $env{'course.'.$courseid.'.domain'},
                   9893: 				     'course',
1.927     albertel 9894: 				     ([$courselevelm,'map'   ],
                   9895: 				      [$courselevel, 'course']));
                   9896: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9897: 	}
1.145     www      9898: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9899: 	unless ($space eq '0') {
1.336     albertel 9900: 	    my @parts=split(/_/,$space);
                   9901: 	    my $id=pop(@parts);
                   9902: 	    my $part=join('_',@parts);
                   9903: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9904: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9905: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9906: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9907: 	}
1.395     albertel 9908: 	if ($recurse) { return undef; }
                   9909: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9910: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9911: # ---------------------------------------------------- Any other user namespace
                   9912:     } elsif ($realm eq 'environment') {
                   9913: # ----------------------------------------------------------------- environment
1.620     albertel 9914: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9915: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9916: 	} else {
1.770     albertel 9917: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9918: 		return '';
                   9919: 	    }
1.219     albertel 9920: 	    my %returnhash=&userenvironment($udom,$uname,
                   9921: 					    $spacequalifierrest);
                   9922: 	    return $returnhash{$spacequalifierrest};
                   9923: 	}
1.28      www      9924:     } elsif ($realm eq 'system') {
1.48      www      9925: # ----------------------------------------------------------------- system.time
                   9926: 	if ($space eq 'time') {
                   9927: 	    return time;
                   9928:         }
1.696     albertel 9929:     } elsif ($realm eq 'server') {
                   9930: # ----------------------------------------------------------------- system.time
                   9931: 	if ($space eq 'name') {
                   9932: 	    return $ENV{'SERVER_NAME'};
                   9933:         }
1.28      www      9934:     }
1.48      www      9935:     return '';
1.61      www      9936: }
                   9937: 
1.927     albertel 9938: sub get_reply {
                   9939:     my ($reply_value) = @_;
1.940     raeburn  9940:     if (ref($reply_value) eq 'ARRAY') {
                   9941:         if (wantarray) {
                   9942: 	    return @$reply_value;
                   9943:         }
                   9944:         return $reply_value->[0];
                   9945:     } else {
                   9946:         return $reply_value;
1.927     albertel 9947:     }
                   9948: }
                   9949: 
1.691     raeburn  9950: sub check_group_parms {
                   9951:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9952:     my @groupitems = ();
                   9953:     my $resultitem;
1.927     albertel 9954:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9955:     foreach my $group (@{$groups}) {
                   9956:         foreach my $level (@levels) {
1.927     albertel 9957:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9958:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9959:         }
                   9960:     }
                   9961:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9962:                             $env{'course.'.$courseid.'.domain'},
                   9963:                                      'course',@groupitems);
                   9964:     return $coursereply;
                   9965: }
                   9966: 
                   9967: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9968:     my ($courseid,@groups) = @_;
                   9969:     @groups = sort(@groups);
1.691     raeburn  9970:     return @groups;
                   9971: }
                   9972: 
1.395     albertel 9973: sub packages_tab_default {
                   9974:     my ($uri,$varname)=@_;
                   9975:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9976: 
                   9977:     my (@extension,@specifics,$do_default);
                   9978:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9979: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9980: 	if ($pack_type eq 'default') {
                   9981: 	    $do_default=1;
                   9982: 	} elsif ($pack_type eq 'extension') {
                   9983: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9984: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9985: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9986: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9987: 	}
                   9988:     }
                   9989:     # first look for a package that matches the requested part id
                   9990:     foreach my $package (@specifics) {
                   9991: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9992: 	next if ($pack_part ne $part);
                   9993: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9994: 	    return $packagetab{"$pack_type&$name&default"};
                   9995: 	}
                   9996:     }
                   9997:     # look for any possible matching non extension_ package
                   9998:     foreach my $package (@specifics) {
                   9999: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10000: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10001: 	    return $packagetab{"$pack_type&$name&default"};
                   10002: 	}
1.585     albertel 10003: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10004: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10005: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10006: 	}
                   10007:     }
1.738     albertel 10008:     # look for any posible extension_ match
                   10009:     foreach my $package (@extension) {
                   10010: 	my ($package,$pack_type)=@{$package};
                   10011: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10012: 	    return $packagetab{"$pack_type&$name&default"};
                   10013: 	}
                   10014: 	if (defined($packagetab{$package."&$name&default"})) {
                   10015: 	    return $packagetab{$package."&$name&default"};
                   10016: 	}
                   10017:     }
                   10018:     # look for a global default setting
                   10019:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10020: 	return $packagetab{"default&$name&default"};
                   10021:     }
1.395     albertel 10022:     return undef;
                   10023: }
                   10024: 
1.334     albertel 10025: sub add_prefix_and_part {
                   10026:     my ($prefix,$part)=@_;
                   10027:     my $keyroot;
                   10028:     if (defined($prefix) && $prefix !~ /^__/) {
                   10029: 	# prefix that has a part already
                   10030: 	$keyroot=$prefix;
                   10031:     } elsif (defined($prefix)) {
                   10032: 	# prefix that is missing a part
                   10033: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10034:     } else {
                   10035: 	# no prefix at all
                   10036: 	if (defined($part)) { $keyroot='_'.$part; }
                   10037:     }
                   10038:     return $keyroot;
                   10039: }
                   10040: 
1.71      www      10041: # ---------------------------------------------------------------- Get metadata
                   10042: 
1.599     albertel 10043: my %metaentry;
1.1070    www      10044: my %importedpartids;
1.71      www      10045: sub metadata {
1.176     www      10046:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10047:     $uri=&declutter($uri);
1.288     albertel 10048:     # if it is a non metadata possible uri return quickly
1.529     albertel 10049:     if (($uri eq '') || 
                   10050: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10051: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10052:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10053: 	return undef;
                   10054:     }
1.1140    www      10055:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10056: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10057: 	return undef;
1.288     albertel 10058:     }
1.73      www      10059:     my $filename=$uri;
                   10060:     $uri=~s/\.meta$//;
1.172     www      10061: #
                   10062: # Is the metadata already cached?
1.177     www      10063: # Look at timestamp of caching
1.172     www      10064: # Everything is cached by the main uri, libraries are never directly cached
                   10065: #
1.428     albertel 10066:     if (!defined($liburi)) {
1.599     albertel 10067: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10068: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10069:     }
                   10070:     {
1.1069    www      10071: # Imported parts would go here
1.1070    www      10072:         my %importedids=();
                   10073:         my @origfileimportpartids=();
1.1069    www      10074:         my $importedparts=0;
1.172     www      10075: #
                   10076: # Is this a recursive call for a library?
                   10077: #
1.599     albertel 10078: #	if (! exists($metacache{$uri})) {
                   10079: #	    $metacache{$uri}={};
                   10080: #	}
1.924     albertel 10081: 	my $cachetime = 60*60;
1.171     www      10082:         if ($liburi) {
                   10083: 	    $liburi=&declutter($liburi);
                   10084:             $filename=$liburi;
1.401     bowersj2 10085:         } else {
1.599     albertel 10086: 	    &devalidate_cache_new('meta',$uri);
                   10087: 	    undef(%metaentry);
1.401     bowersj2 10088: 	}
1.140     www      10089:         my %metathesekeys=();
1.73      www      10090:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10091: 	my $metastring;
1.1140    www      10092: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10093: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10094: 	    $metastring = 
1.929     albertel 10095: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10096: 					  ('grade_target' => 'meta'));
                   10097: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10098: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10099:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10100: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10101: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10102: 	    $metastring=&getfile($file);
1.489     albertel 10103: 	}
1.208     albertel 10104:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10105:         my $token;
1.140     www      10106:         undef %metathesekeys;
1.71      www      10107:         while ($token=$parser->get_token) {
1.339     albertel 10108: 	    if ($token->[0] eq 'S') {
                   10109: 		if (defined($token->[2]->{'package'})) {
1.172     www      10110: #
                   10111: # This is a package - get package info
                   10112: #
1.339     albertel 10113: 		    my $package=$token->[2]->{'package'};
                   10114: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10115: 		    if (defined($token->[2]->{'id'})) { 
                   10116: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10117: 		    }
1.599     albertel 10118: 		    if ($metaentry{':packages'}) {
                   10119: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10120: 		    } else {
1.599     albertel 10121: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10122: 		    }
1.736     albertel 10123: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10124: 			my $part=$keyroot;
                   10125: 			$part=~s/^\_//;
1.736     albertel 10126: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10127: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10128: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10129: 			    # ignore package.tab specified default values
                   10130:                             # here &package_tab_default() will fetch those
                   10131: 			    if ($subp eq 'default') { next; }
1.736     albertel 10132: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10133: 			    my $unikey;
                   10134: 			    if ($pack =~ /_0$/) {
                   10135: 				$unikey='parameter_0_'.$name;
                   10136: 				$part=0;
                   10137: 			    } else {
                   10138: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10139: 			    }
1.339     albertel 10140: 			    if ($subp eq 'display') {
                   10141: 				$value.=' [Part: '.$part.']';
                   10142: 			    }
1.599     albertel 10143: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10144: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10145: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10146: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10147: 			    }
1.599     albertel 10148: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10149: 				$metaentry{':'.$unikey}=
                   10150: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10151: 			    }
1.339     albertel 10152: 			}
                   10153: 		    }
                   10154: 		} else {
1.172     www      10155: #
                   10156: # This is not a package - some other kind of start tag
1.339     albertel 10157: #
                   10158: 		    my $entry=$token->[1];
1.1068    www      10159: 		    my $unikey='';
1.175     www      10160: 
1.339     albertel 10161: 		    if ($entry eq 'import') {
1.175     www      10162: #
                   10163: # Importing a library here
1.339     albertel 10164: #
1.1067    www      10165:                         my $location=$parser->get_text('/import');
                   10166:                         my $dir=$filename;
                   10167:                         $dir=~s|[^/]*$||;
                   10168:                         $location=&filelocation($dir,$location);
1.1069    www      10169:                        
1.1068    www      10170:                         my $importmode=$token->[2]->{'importmode'};
                   10171:                         if ($importmode eq 'problem') {
1.1069    www      10172: # Import as problem/response
1.1068    www      10173:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10174:                         } elsif ($importmode eq 'part') {
                   10175: # Import as part(s)
1.1069    www      10176:                            $importedparts=1;
                   10177: # We need to get the original file and the imported file to get the part order correct
                   10178: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10179: # Load and inspect original file
1.1070    www      10180:                            if ($#origfileimportpartids<0) {
                   10181:                               undef(%importedpartids);
                   10182:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10183:                               my $origfile=&getfile($origfilelocation);
                   10184:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10185:                            }
                   10186: 
1.1069    www      10187: # Load and inspect imported file
                   10188:                            my $impfile=&getfile($location);
                   10189:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10190:                            if ($#impfilepartids>=0) {
                   10191: # This problem had parts
1.1070    www      10192:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10193:                            } else {
                   10194: # Importing by turning a single problem into a problem part
                   10195: # It gets the import-tags ID as part-ID
                   10196:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10197:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10198:                            }
1.1068    www      10199:                         } else {
                   10200: # Normal import
                   10201:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10202:                            if (defined($token->[2]->{'id'})) {
                   10203:                               $unikey.='_'.$token->[2]->{'id'};
                   10204:                            }
1.1067    www      10205:                         }
                   10206: 
1.339     albertel 10207: 			if ($depthcount<20) {
1.736     albertel 10208: 			    my $metadata = 
                   10209: 				&metadata($uri,'keys', $location,$unikey,
                   10210: 					  $depthcount+1);
                   10211: 			    foreach my $meta (split(',',$metadata)) {
                   10212: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10213: 				$metathesekeys{$meta}=1;
1.339     albertel 10214: 			    }
1.1068    www      10215: 			
                   10216:                         }
1.1067    www      10217: 		    } else {
                   10218: #
                   10219: # Not importing, some other kind of non-package, non-library start tag
                   10220: # 
                   10221:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10222:                         if (defined($token->[2]->{'id'})) {
                   10223:                             $unikey.='_'.$token->[2]->{'id'};
                   10224:                         }
1.339     albertel 10225: 			if (defined($token->[2]->{'name'})) { 
                   10226: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10227: 			}
                   10228: 			$metathesekeys{$unikey}=1;
1.736     albertel 10229: 			foreach my $param (@{$token->[3]}) {
                   10230: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10231: 				$token->[2]->{$param};
1.339     albertel 10232: 			}
                   10233: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10234: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10235: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10236: 		 # only ws inside the tag, and not in default, so use default
                   10237: 		 # as value
1.599     albertel 10238: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10239: 			} elsif ( $internaltext =~ /\S/ ) {
                   10240: 		  # something interesting inside the tag
                   10241: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10242: 			} else {
1.908     albertel 10243: 		  # no interesting values, don't set a default
1.339     albertel 10244: 			}
1.172     www      10245: # end of not-a-package not-a-library import
1.339     albertel 10246: 		    }
1.172     www      10247: # end of not-a-package start tag
1.339     albertel 10248: 		}
1.172     www      10249: # the next is the end of "start tag"
1.339     albertel 10250: 	    }
                   10251: 	}
1.483     albertel 10252: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10253: 	$extension = lc($extension);
                   10254: 	if ($extension eq 'htm') { $extension='html'; }
                   10255: 
1.737     albertel 10256: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10257: 	    #no specific packages #how's our extension
                   10258: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10259: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10260: 					 \%metathesekeys);
                   10261: 	}
1.883     albertel 10262: 
                   10263: 	if (!exists($metaentry{':packages'})
                   10264: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10265: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10266: 		#no specific packages well let's get default then
                   10267: 		if ($key!~/^default&/) { next; }
1.488     albertel 10268: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10269: 					     \%metathesekeys);
                   10270: 	    }
                   10271: 	}
1.338     www      10272: # are there custom rights to evaluate
1.599     albertel 10273: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10274: 
1.338     www      10275:     #
                   10276:     # Importing a rights file here
1.339     albertel 10277:     #
                   10278: 	    unless ($depthcount) {
1.599     albertel 10279: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10280: 		my $dir=$filename;
                   10281: 		$dir=~s|[^/]*$||;
                   10282: 		$location=&filelocation($dir,$location);
1.736     albertel 10283: 		my $rights_metadata =
                   10284: 		    &metadata($uri,'keys',$location,'_rights',
                   10285: 			      $depthcount+1);
                   10286: 		foreach my $rights (split(',',$rights_metadata)) {
                   10287: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10288: 		    $metathesekeys{$rights}=1;
1.339     albertel 10289: 		}
                   10290: 	    }
                   10291: 	}
1.737     albertel 10292: 	# uniqifiy package listing
                   10293: 	my %seen;
                   10294: 	my @uniq_packages =
                   10295: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10296: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10297: 
1.1070    www      10298:         if ($importedparts) {
                   10299: # We had imported parts and need to rebuild partorder
                   10300:            $metaentry{':partorder'}='';
                   10301:            $metathesekeys{'partorder'}=1;
                   10302:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10303:                if ($origfileimportpartids[$index] eq 'part') {
                   10304: # original part, part of the problem
                   10305:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10306:                } else {
                   10307: # we have imported parts at this position
                   10308:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10309:                }
                   10310:            }
                   10311:            $metaentry{':partorder'}=~s/^\,//;
                   10312:         }
                   10313: 
1.737     albertel 10314: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10315: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10316: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10317: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10318: # this is the end of "was not already recently cached
1.71      www      10319:     }
1.599     albertel 10320:     return $metaentry{':'.$what};
1.261     albertel 10321: }
                   10322: 
1.488     albertel 10323: sub metadata_create_package_def {
1.483     albertel 10324:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10325:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10326:     if ($subp eq 'default') { next; }
                   10327:     
1.599     albertel 10328:     if (defined($metaentry{':packages'})) {
                   10329: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10330:     } else {
1.599     albertel 10331: 	$metaentry{':packages'}=$package;
1.483     albertel 10332:     }
                   10333:     my $value=$packagetab{$key};
                   10334:     my $unikey;
                   10335:     $unikey='parameter_0_'.$name;
1.599     albertel 10336:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10337:     $$metathesekeys{$unikey}=1;
1.599     albertel 10338:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10339: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10340:     }
1.599     albertel 10341:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10342: 	$metaentry{':'.$unikey}=
                   10343: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10344:     }
                   10345: }
                   10346: 
1.261     albertel 10347: sub metadata_generate_part0 {
                   10348:     my ($metadata,$metacache,$uri) = @_;
                   10349:     my %allnames;
1.737     albertel 10350:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10351: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10352: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10353: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10354: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10355: 	    $allnames{$name}=$part;
                   10356: 	  }
                   10357: 	}
                   10358:     }
                   10359:     foreach my $name (keys(%allnames)) {
                   10360:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10361:       my $key=":parameter_0_$name";
1.261     albertel 10362:       $$metacache{"$key.part"}='0';
                   10363:       $$metacache{"$key.name"}=$name;
1.428     albertel 10364:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10365: 					   $allnames{$name}.'_'.$name.
                   10366: 					   '.type'};
1.428     albertel 10367:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10368: 			     '.display'};
1.644     www      10369:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10370:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10371:       $$metacache{"$key.display"}=$olddis;
                   10372:     }
1.71      www      10373: }
                   10374: 
1.764     albertel 10375: # ------------------------------------------------------ Devalidate title cache
                   10376: 
                   10377: sub devalidate_title_cache {
                   10378:     my ($url)=@_;
                   10379:     if (!$env{'request.course.id'}) { return; }
                   10380:     my $symb=&symbread($url);
                   10381:     if (!$symb) { return; }
                   10382:     my $key=$env{'request.course.id'}."\0".$symb;
                   10383:     &devalidate_cache_new('title',$key);
                   10384: }
                   10385: 
1.1014    droeschl 10386: # ------------------------------------------------- Get the title of a course
                   10387: 
                   10388: sub current_course_title {
                   10389:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10390: }
1.301     www      10391: # ------------------------------------------------- Get the title of a resource
                   10392: 
                   10393: sub gettitle {
                   10394:     my $urlsymb=shift;
                   10395:     my $symb=&symbread($urlsymb);
1.534     albertel 10396:     if ($symb) {
1.620     albertel 10397: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10398: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10399: 	if (defined($cached)) { 
                   10400: 	    return $result;
                   10401: 	}
1.534     albertel 10402: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10403: 	my $title='';
1.907     albertel 10404: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10405: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10406: 	} else {
                   10407: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10408: 		    &GDBM_READER(),0640)) {
                   10409: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10410: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10411: 		untie(%bighash);
                   10412: 	    }
1.534     albertel 10413: 	}
                   10414: 	$title=~s/\&colon\;/\:/gs;
                   10415: 	if ($title) {
1.1159    www      10416: # Remember both $symb and $title for dynamic metadata
                   10417:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10418:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10419: # Cache this title and then return it
1.599     albertel 10420: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10421: 	}
                   10422: 	$urlsymb=$url;
                   10423:     }
                   10424:     my $title=&metadata($urlsymb,'title');
                   10425:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10426:     return $title;
1.301     www      10427: }
1.613     albertel 10428: 
1.614     albertel 10429: sub get_slot {
                   10430:     my ($which,$cnum,$cdom)=@_;
                   10431:     if (!$cnum || !$cdom) {
1.790     albertel 10432: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10433: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10434: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10435:     }
1.703     albertel 10436:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10437:     my %slotinfo;
                   10438:     if (exists($remembered{$key})) {
                   10439: 	$slotinfo{$which} = $remembered{$key};
                   10440:     } else {
                   10441: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10442: 	&Apache::lonhomework::showhash(%slotinfo);
                   10443: 	my ($tmp)=keys(%slotinfo);
                   10444: 	if ($tmp=~/^error:/) { return (); }
                   10445: 	$remembered{$key} = $slotinfo{$which};
                   10446:     }
1.616     albertel 10447:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10448: 	return %{$slotinfo{$which}};
                   10449:     }
                   10450:     return $slotinfo{$which};
1.614     albertel 10451: }
1.1150    raeburn  10452: 
                   10453: sub get_reservable_slots {
                   10454:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10455:     my $now = time;
                   10456:     my $reservable_info;
                   10457:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10458:     if (exists($remembered{$key})) {
                   10459:         $reservable_info = $remembered{$key};
                   10460:     } else {
                   10461:         my %resv;
                   10462:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10463:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10464:         $reservable_info = \%resv;
                   10465:         $remembered{$key} = $reservable_info;
                   10466:     }
                   10467:     return $reservable_info;
                   10468: }
                   10469: 
                   10470: sub get_course_slots {
                   10471:     my ($cnum,$cdom) = @_;
                   10472:     my $hashid=$cnum.':'.$cdom;
                   10473:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10474:     if (defined($cached)) {
                   10475:         if (ref($result) eq 'HASH') {
                   10476:             return %{$result};
                   10477:         }
                   10478:     } else {
                   10479:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10480:         my ($tmp) = keys(%slots);
                   10481:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10482:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10483:             return %slots;
                   10484:         }
                   10485:     }
                   10486:     return;
                   10487: }
                   10488: 
                   10489: sub devalidate_slots_cache {
                   10490:     my ($cnum,$cdom)=@_;
                   10491:     my $hashid=$cnum.':'.$cdom;
                   10492:     &devalidate_cache_new('allslots',$hashid);
                   10493: }
                   10494: 
1.1172.2.8  raeburn  10495: sub get_coursechange {
                   10496:     my ($cdom,$cnum) = @_;
                   10497:     if ($cdom eq '' || $cnum eq '') {
                   10498:         return unless ($env{'request.course.id'});
                   10499:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10500:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10501:     }
                   10502:     my $hashid=$cdom.'_'.$cnum;
                   10503:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10504:     if ((defined($cached)) && ($change ne '')) {
                   10505:         return $change;
                   10506:     } else {
                   10507:         my %crshash;
                   10508:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10509:         if ($crshash{'internal.contentchange'} eq '') {
                   10510:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10511:             if ($change eq '') {
                   10512:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10513:                 $change = $crshash{'internal.created'};
                   10514:             }
                   10515:         } else {
                   10516:             $change = $crshash{'internal.contentchange'};
                   10517:         }
                   10518:         my $cachetime = 600;
                   10519:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10520:     }
                   10521:     return $change;
                   10522: }
                   10523: 
                   10524: sub devalidate_coursechange_cache {
                   10525:     my ($cnum,$cdom)=@_;
                   10526:     my $hashid=$cnum.':'.$cdom;
                   10527:     &devalidate_cache_new('crschange',$hashid);
                   10528: }
                   10529: 
1.31      www      10530: # ------------------------------------------------- Update symbolic store links
                   10531: 
                   10532: sub symblist {
                   10533:     my ($mapname,%newhash)=@_;
1.438     www      10534:     $mapname=&deversion(&declutter($mapname));
1.31      www      10535:     my %hash;
1.620     albertel 10536:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10537:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10538:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10539: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10540: 		next if ($url eq 'last_known'
                   10541: 			 && $env{'form.no_update_last_known'});
                   10542: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10543: 						    $newhash{$url}->[1],
                   10544: 						    $newhash{$url}->[0]);
1.191     harris41 10545:             }
1.31      www      10546:             if (untie(%hash)) {
                   10547: 		return 'ok';
                   10548:             }
                   10549:         }
                   10550:     }
                   10551:     return 'error';
1.212     www      10552: }
                   10553: 
                   10554: # --------------------------------------------------------------- Verify a symb
                   10555: 
                   10556: sub symbverify {
1.1172.2.11  raeburn  10557:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10558:     my $thisfn=$thisurl;
1.439     www      10559:     $thisfn=&declutter($thisfn);
1.215     www      10560: # direct jump to resource in page or to a sequence - will construct own symbs
                   10561:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10562: # check URL part
1.409     www      10563:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10564: 
1.431     www      10565:     unless ($url eq $thisfn) { return 0; }
1.213     www      10566: 
1.216     www      10567:     $symb=&symbclean($symb);
1.510     www      10568:     $thisurl=&deversion($thisurl);
1.439     www      10569:     $thisfn=&deversion($thisfn);
1.213     www      10570: 
                   10571:     my %bighash;
                   10572:     my $okay=0;
1.431     www      10573: 
1.620     albertel 10574:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10575:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10576:         my $noclutter;
1.1032    raeburn  10577:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10578:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10579:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10580:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10581:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10582:                 $noclutter = 1;
                   10583:             }
                   10584:         }
                   10585:         my $ids;
                   10586:         if ($noclutter) {
                   10587:             $ids=$bighash{'ids_'.$thisurl};
                   10588:         } else {
                   10589:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10590:         }
1.1102    raeburn  10591:         unless ($ids) {
1.1172.2.13  raeburn  10592:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10593:             $ids=$bighash{$idkey};
1.216     www      10594:         }
                   10595:         if ($ids) {
                   10596: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10597:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10598:                 $symb =~ s/\?.+$//;
                   10599:             }
1.800     albertel 10600: 	    foreach my $id (split(/\,/,$ids)) {
                   10601: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10602:                if (
                   10603:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10604:    eq $symb) {
1.1172.2.11  raeburn  10605:                    if (ref($encstate)) {
                   10606:                        $$encstate = $bighash{'encrypted_'.$id};
                   10607:                    }
1.1172.2.13  raeburn  10608:                    if (($env{'request.role.adv'}) ||
                   10609:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10610:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10611:                        $okay=1;
                   10612:                        last;
                   10613:                    }
                   10614:                }
                   10615:            }
1.216     www      10616:         }
1.213     www      10617: 	untie(%bighash);
                   10618:     }
                   10619:     return $okay;
1.31      www      10620: }
                   10621: 
1.210     www      10622: # --------------------------------------------------------------- Clean-up symb
                   10623: 
                   10624: sub symbclean {
                   10625:     my $symb=shift;
1.568     albertel 10626:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10627: # remove version from map
                   10628:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10629: 
1.210     www      10630: # remove version from URL
                   10631:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10632: 
1.507     www      10633: # remove wrapper
                   10634: 
1.510     www      10635:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10636:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10637:     return $symb;
1.409     www      10638: }
                   10639: 
                   10640: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10641: 
                   10642: sub encode_symb {
                   10643:     my ($map,$resid,$url)=@_;
                   10644:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10645: }
1.409     www      10646: 
                   10647: sub decode_symb {
1.568     albertel 10648:     my $symb=shift;
                   10649:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10650:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10651:     return (&fixversion($map),$resid,&fixversion($url));
                   10652: }
                   10653: 
                   10654: sub fixversion {
                   10655:     my $fn=shift;
1.609     banghart 10656:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10657:     my %bighash;
                   10658:     my $uri=&clutter($fn);
1.620     albertel 10659:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10660: # is this cached?
1.599     albertel 10661:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10662:     if (defined($cached)) { return $result; }
                   10663: # unfortunately not cached, or expired
1.620     albertel 10664:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10665: 	    &GDBM_READER(),0640)) {
                   10666:  	if ($bighash{'version_'.$uri}) {
                   10667:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10668:  	    unless (($version eq 'mostrecent') || 
                   10669: 		    ($version==&getversion($uri))) {
1.440     www      10670:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10671:  	    }
                   10672:  	}
                   10673:  	untie %bighash;
1.413     www      10674:     }
1.599     albertel 10675:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10676: }
                   10677: 
                   10678: sub deversion {
                   10679:     my $url=shift;
                   10680:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10681:     return $url;
1.210     www      10682: }
                   10683: 
1.31      www      10684: # ------------------------------------------------------ Return symb list entry
                   10685: 
                   10686: sub symbread {
1.249     www      10687:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10688:     my $cache_str;
                   10689:     if ($thisfn ne '') {
                   10690:         $cache_str='request.symbread.cached.'.$thisfn;
                   10691:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10692:             return $env{$cache_str};
                   10693:         }
1.1172.2.13  raeburn  10694:    } else {
1.242     www      10695: # no filename provided? try from environment
1.620     albertel 10696:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10697:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10698:         }
                   10699:         $thisfn=$env{'request.filename'};
1.44      www      10700:     }
1.569     albertel 10701:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10702: # is that filename actually a symb? Verify, clean, and return
                   10703:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10704: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10705: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10706: 	}
1.242     www      10707:     }
1.44      www      10708:     $thisfn=declutter($thisfn);
1.31      www      10709:     my %hash;
1.37      www      10710:     my %bighash;
                   10711:     my $syval='';
1.620     albertel 10712:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10713:         my $targetfn = $thisfn;
1.609     banghart 10714:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10715:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10716:         }
1.687     albertel 10717: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10718: 	    $targetfn=$1;
                   10719: 	}
1.620     albertel 10720:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10721:                       &GDBM_READER(),0640)) {
1.481     raeburn  10722: 	    $syval=$hash{$targetfn};
1.37      www      10723:             untie(%hash);
                   10724:         }
                   10725: # ---------------------------------------------------------- There was an entry
                   10726:         if ($syval) {
1.601     albertel 10727: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10728: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10729: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10730: 		    #return $env{$cache_str}='';
1.601     albertel 10731: 		#}    
                   10732: 		#$syval.=$1;
                   10733: 	    #}
1.37      www      10734:         } else {
                   10735: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10736:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10737:                             &GDBM_READER(),0640)) {
1.37      www      10738: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10739:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10740:               unless ($ids) { 
                   10741:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10742:               }
                   10743:               unless ($ids) {
                   10744: # alias?
                   10745: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10746:               }
1.37      www      10747:               if ($ids) {
                   10748: # ------------------------------------------------------------------- Has ID(s)
                   10749:                  my @possibilities=split(/\,/,$ids);
1.39      www      10750:                  if ($#possibilities==0) {
                   10751: # ----------------------------------------------- There is only one possibility
1.37      www      10752: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10753: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10754: 						    $resid,$thisfn);
1.249     www      10755:                  } elsif (!$donotrecurse) {
1.39      www      10756: # ------------------------------------------ There is more than one possibility
                   10757:                      my $realpossible=0;
1.800     albertel 10758:                      foreach my $id (@possibilities) {
                   10759: 			 my $file=$bighash{'src_'.$id};
1.39      www      10760:                          if (&allowed('bre',$file)) {
1.800     albertel 10761:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10762:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10763: 				$realpossible++;
1.626     albertel 10764:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10765: 						    $resid,$thisfn);
1.39      www      10766:                             }
                   10767: 			 }
1.191     harris41 10768:                      }
1.39      www      10769: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10770:                  } else {
                   10771:                      $syval='';
1.37      www      10772:                  }
                   10773: 	      }
                   10774:               untie(%bighash)
1.481     raeburn  10775:            }
1.31      www      10776:         }
1.62      www      10777:         if ($syval) {
1.620     albertel 10778: 	    return $env{$cache_str}=$syval;
1.62      www      10779:         }
1.31      www      10780:     }
1.949     raeburn  10781:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10782:     return $env{$cache_str}='';
1.31      www      10783: }
                   10784: 
                   10785: # ---------------------------------------------------------- Return random seed
                   10786: 
1.32      www      10787: sub numval {
                   10788:     my $txt=shift;
                   10789:     $txt=~tr/A-J/0-9/;
                   10790:     $txt=~tr/a-j/0-9/;
                   10791:     $txt=~tr/K-T/0-9/;
                   10792:     $txt=~tr/k-t/0-9/;
                   10793:     $txt=~tr/U-Z/0-5/;
                   10794:     $txt=~tr/u-z/0-5/;
                   10795:     $txt=~s/\D//g;
1.564     albertel 10796:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10797:     return int($txt);
1.368     albertel 10798: }
                   10799: 
1.484     albertel 10800: sub numval2 {
                   10801:     my $txt=shift;
                   10802:     $txt=~tr/A-J/0-9/;
                   10803:     $txt=~tr/a-j/0-9/;
                   10804:     $txt=~tr/K-T/0-9/;
                   10805:     $txt=~tr/k-t/0-9/;
                   10806:     $txt=~tr/U-Z/0-5/;
                   10807:     $txt=~tr/u-z/0-5/;
                   10808:     $txt=~s/\D//g;
                   10809:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10810:     my $total;
                   10811:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10812:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10813:     return int($total);
                   10814: }
                   10815: 
1.575     albertel 10816: sub numval3 {
                   10817:     use integer;
                   10818:     my $txt=shift;
                   10819:     $txt=~tr/A-J/0-9/;
                   10820:     $txt=~tr/a-j/0-9/;
                   10821:     $txt=~tr/K-T/0-9/;
                   10822:     $txt=~tr/k-t/0-9/;
                   10823:     $txt=~tr/U-Z/0-5/;
                   10824:     $txt=~tr/u-z/0-5/;
                   10825:     $txt=~s/\D//g;
                   10826:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10827:     my $total;
                   10828:     foreach my $val (@txts) { $total+=$val; }
                   10829:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10830:     return $total;
                   10831: }
                   10832: 
1.675     albertel 10833: sub digest {
                   10834:     my ($data)=@_;
                   10835:     my $digest=&Digest::MD5::md5($data);
                   10836:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10837:     my ($e,$f);
                   10838:     {
                   10839:         use integer;
                   10840:         $e=($a+$b);
                   10841:         $f=($c+$d);
                   10842:         if ($_64bit) {
                   10843:             $e=(($e<<32)>>32);
                   10844:             $f=(($f<<32)>>32);
                   10845:         }
                   10846:     }
                   10847:     if (wantarray) {
                   10848: 	return ($e,$f);
                   10849:     } else {
                   10850: 	my $g;
                   10851: 	{
                   10852: 	    use integer;
                   10853: 	    $g=($e+$f);
                   10854: 	    if ($_64bit) {
                   10855: 		$g=(($g<<32)>>32);
                   10856: 	    }
                   10857: 	}
                   10858: 	return $g;
                   10859:     }
                   10860: }
                   10861: 
1.368     albertel 10862: sub latest_rnd_algorithm_id {
1.675     albertel 10863:     return '64bit5';
1.366     albertel 10864: }
1.32      www      10865: 
1.503     albertel 10866: sub get_rand_alg {
                   10867:     my ($courseid)=@_;
1.790     albertel 10868:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10869:     if ($courseid) {
1.620     albertel 10870: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10871:     }
                   10872:     return &latest_rnd_algorithm_id();
                   10873: }
                   10874: 
1.562     albertel 10875: sub validCODE {
                   10876:     my ($CODE)=@_;
                   10877:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10878:     return 0;
                   10879: }
                   10880: 
1.491     albertel 10881: sub getCODE {
1.620     albertel 10882:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10883:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10884: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10885: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10886: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10887:     }
                   10888:     return undef;
                   10889: }
1.1133    foxr     10890: #
                   10891: #  Determines the random seed for a specific context:
                   10892: #
                   10893: # parameters:
                   10894: #   symb      - in course context the symb for the seed.
                   10895: #   course_id - The course id of the form domain_coursenum.
                   10896: #   domain    - Domain for the user.
                   10897: #   course    - Course for the user.
                   10898: #   cenv      - environment of the course.
                   10899: #
                   10900: # NOTE:
                   10901: #   All parameters are picked out of the environment if missing
                   10902: #   or not defined.
                   10903: #   If a symb cannot be determined the current time is used instead.
                   10904: #
                   10905: #  For a given well defined symb, courside, domain, username,
                   10906: #  and course environment, the seed is reproducible.
                   10907: #
1.31      www      10908: sub rndseed {
1.1133    foxr     10909:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10910:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10911:     if (!defined($symb)) {
1.366     albertel 10912: 	unless ($symb=$wsymb) { return time; }
                   10913:     }
1.1146    foxr     10914:     if (!defined $courseid) { 
                   10915: 	$courseid=$wcourseid; 
                   10916:     }
                   10917:     if (!defined $domain) { $domain=$wdomain; }
                   10918:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10919: 
                   10920:     my $which;
                   10921:     if (defined($cenv->{'rndseed'})) {
                   10922: 	$which = $cenv->{'rndseed'};
                   10923:     } else {
                   10924: 	$which =&get_rand_alg($courseid);
                   10925:     }
1.491     albertel 10926:     if (defined(&getCODE())) {
1.675     albertel 10927: 	if ($which eq '64bit5') {
                   10928: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10929: 	} elsif ($which eq '64bit4') {
1.575     albertel 10930: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10931: 	} else {
                   10932: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10933: 	}
1.675     albertel 10934:     } elsif ($which eq '64bit5') {
                   10935: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10936:     } elsif ($which eq '64bit4') {
                   10937: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10938:     } elsif ($which eq '64bit3') {
                   10939: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10940:     } elsif ($which eq '64bit2') {
                   10941: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10942:     } elsif ($which eq '64bit') {
                   10943: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10944:     }
                   10945:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10946: }
                   10947: 
                   10948: sub rndseed_32bit {
                   10949:     my ($symb,$courseid,$domain,$username)=@_;
                   10950:     {
                   10951: 	use integer;
                   10952: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10953: 	my $symbseed=numval($symb) << 22;
                   10954: 	my $namechck=unpack("%32C*",$username) << 17;
                   10955: 	my $nameseed=numval($username) << 12;
                   10956: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10957: 	my $courseseed=unpack("%32C*",$courseid);
                   10958: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10959: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10960: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10961: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10962: 	return $num;
                   10963:     }
                   10964: }
                   10965: 
                   10966: sub rndseed_64bit {
                   10967:     my ($symb,$courseid,$domain,$username)=@_;
                   10968:     {
                   10969: 	use integer;
                   10970: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10971: 	my $symbseed=numval($symb) << 10;
                   10972: 	my $namechck=unpack("%32S*",$username);
                   10973: 	
                   10974: 	my $nameseed=numval($username) << 21;
                   10975: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10976: 	my $courseseed=unpack("%32S*",$courseid);
                   10977: 	
                   10978: 	my $num1=$symbchck+$symbseed+$namechck;
                   10979: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10980: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10981: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10982: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10983: 	return "$num1,$num2";
1.155     albertel 10984:     }
1.366     albertel 10985: }
                   10986: 
1.443     albertel 10987: sub rndseed_64bit2 {
                   10988:     my ($symb,$courseid,$domain,$username)=@_;
                   10989:     {
                   10990: 	use integer;
                   10991: 	# strings need to be an even # of cahracters long, it it is odd the
                   10992:         # last characters gets thrown away
                   10993: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10994: 	my $symbseed=numval($symb) << 10;
                   10995: 	my $namechck=unpack("%32S*",$username.' ');
                   10996: 	
                   10997: 	my $nameseed=numval($username) << 21;
1.501     albertel 10998: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10999: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11000: 	
                   11001: 	my $num1=$symbchck+$symbseed+$namechck;
                   11002: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11003: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11004: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11005: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11006: 	return "$num1,$num2";
                   11007:     }
                   11008: }
                   11009: 
                   11010: sub rndseed_64bit3 {
                   11011:     my ($symb,$courseid,$domain,$username)=@_;
                   11012:     {
                   11013: 	use integer;
                   11014: 	# strings need to be an even # of cahracters long, it it is odd the
                   11015:         # last characters gets thrown away
                   11016: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11017: 	my $symbseed=numval2($symb) << 10;
                   11018: 	my $namechck=unpack("%32S*",$username.' ');
                   11019: 	
                   11020: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11021: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11022: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11023: 	
                   11024: 	my $num1=$symbchck+$symbseed+$namechck;
                   11025: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11026: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11027: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11028: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11029: 	
1.503     albertel 11030: 	return "$num1:$num2";
1.443     albertel 11031:     }
                   11032: }
                   11033: 
1.575     albertel 11034: sub rndseed_64bit4 {
                   11035:     my ($symb,$courseid,$domain,$username)=@_;
                   11036:     {
                   11037: 	use integer;
                   11038: 	# strings need to be an even # of cahracters long, it it is odd the
                   11039:         # last characters gets thrown away
                   11040: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11041: 	my $symbseed=numval3($symb) << 10;
                   11042: 	my $namechck=unpack("%32S*",$username.' ');
                   11043: 	
                   11044: 	my $nameseed=numval3($username) << 21;
                   11045: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11046: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11047: 	
                   11048: 	my $num1=$symbchck+$symbseed+$namechck;
                   11049: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11050: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11051: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11052: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11053: 	
1.575     albertel 11054: 	return "$num1:$num2";
                   11055:     }
                   11056: }
                   11057: 
1.675     albertel 11058: sub rndseed_64bit5 {
                   11059:     my ($symb,$courseid,$domain,$username)=@_;
                   11060:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11061:     return "$num1:$num2";
                   11062: }
                   11063: 
1.366     albertel 11064: sub rndseed_CODE_64bit {
                   11065:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11066:     {
1.366     albertel 11067: 	use integer;
1.443     albertel 11068: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11069: 	my $symbseed=numval2($symb);
1.491     albertel 11070: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11071: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11072: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11073: 	my $num1=$symbseed+$CODEchck;
                   11074: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11075: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11076: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11077: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11078: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11079: 	return "$num1:$num2";
1.366     albertel 11080:     }
                   11081: }
                   11082: 
1.575     albertel 11083: sub rndseed_CODE_64bit4 {
                   11084:     my ($symb,$courseid,$domain,$username)=@_;
                   11085:     {
                   11086: 	use integer;
                   11087: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11088: 	my $symbseed=numval3($symb);
                   11089: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11090: 	my $CODEseed=numval3(&getCODE());
                   11091: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11092: 	my $num1=$symbseed+$CODEchck;
                   11093: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11094: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11095: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11096: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11097: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11098: 	return "$num1:$num2";
                   11099:     }
                   11100: }
                   11101: 
1.675     albertel 11102: sub rndseed_CODE_64bit5 {
                   11103:     my ($symb,$courseid,$domain,$username)=@_;
                   11104:     my $code = &getCODE();
                   11105:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11106:     return "$num1:$num2";
                   11107: }
                   11108: 
1.366     albertel 11109: sub setup_random_from_rndseed {
                   11110:     my ($rndseed)=@_;
1.503     albertel 11111:     if ($rndseed =~/([,:])/) {
                   11112: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11113: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11114:     } else {
                   11115: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11116:     }
1.36      albertel 11117: }
                   11118: 
1.474     albertel 11119: sub latest_receipt_algorithm_id {
1.835     albertel 11120:     return 'receipt3';
1.474     albertel 11121: }
                   11122: 
1.480     www      11123: sub recunique {
                   11124:     my $fucourseid=shift;
                   11125:     my $unique;
1.835     albertel 11126:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11127: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11128: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11129:     } else {
                   11130: 	$unique=$perlvar{'lonReceipt'};
                   11131:     }
                   11132:     return unpack("%32C*",$unique);
                   11133: }
                   11134: 
                   11135: sub recprefix {
                   11136:     my $fucourseid=shift;
                   11137:     my $prefix;
1.835     albertel 11138:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11139: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11140: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11141:     } else {
                   11142: 	$prefix=$perlvar{'lonHostID'};
                   11143:     }
                   11144:     return unpack("%32C*",$prefix);
                   11145: }
                   11146: 
1.76      www      11147: sub ireceipt {
1.474     albertel 11148:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11149: 
                   11150:     my $return =&recprefix($fucourseid).'-';
                   11151: 
                   11152:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11153: 	$env{'request.state'} eq 'construct') {
                   11154: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11155: 	return $return;
                   11156:     }
                   11157: 
1.76      www      11158:     my $cuname=unpack("%32C*",$funame);
                   11159:     my $cudom=unpack("%32C*",$fudom);
                   11160:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11161:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11162:     my $cunique=&recunique($fucourseid);
1.474     albertel 11163:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11164:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11165: 
1.790     albertel 11166: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11167: 			       
                   11168: 	$return.= ($cunique%$cuname+
                   11169: 		   $cunique%$cudom+
                   11170: 		   $cusymb%$cuname+
                   11171: 		   $cusymb%$cudom+
                   11172: 		   $cucourseid%$cuname+
                   11173: 		   $cucourseid%$cudom+
                   11174: 		   $cpart%$cuname+
                   11175: 		   $cpart%$cudom);
                   11176:     } else {
                   11177: 	$return.= ($cunique%$cuname+
                   11178: 		   $cunique%$cudom+
                   11179: 		   $cusymb%$cuname+
                   11180: 		   $cusymb%$cudom+
                   11181: 		   $cucourseid%$cuname+
                   11182: 		   $cucourseid%$cudom);
                   11183:     }
                   11184:     return $return;
1.76      www      11185: }
                   11186: 
                   11187: sub receipt {
1.474     albertel 11188:     my ($part)=@_;
1.790     albertel 11189:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11190:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11191: }
1.260     ng       11192: 
1.790     albertel 11193: sub whichuser {
                   11194:     my ($passedsymb)=@_;
                   11195:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11196:     if (defined($env{'form.grade_symb'})) {
                   11197: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11198: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11199: 	if (!$allowed &&
                   11200: 	    exists($env{'request.course.sec'}) &&
                   11201: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11202: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11203: 			      '/'.$env{'request.course.sec'});
                   11204: 	}
                   11205: 	if ($allowed) {
                   11206: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11207: 	    $courseid=$tmp_courseid;
                   11208: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11209: 	    ($name)=&get_env_multiple('form.grade_username');
                   11210: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11211: 	}
                   11212:     }
                   11213:     if (!$passedsymb) {
                   11214: 	$symb=&symbread();
                   11215:     } else {
                   11216: 	$symb=$passedsymb;
                   11217:     }
                   11218:     $courseid=$env{'request.course.id'};
                   11219:     $domain=$env{'user.domain'};
                   11220:     $name=$env{'user.name'};
                   11221:     if ($name eq 'public' && $domain eq 'public') {
                   11222: 	if (!defined($env{'form.username'})) {
                   11223: 	    $env{'form.username'}.=time.rand(10000000);
                   11224: 	}
                   11225: 	$name.=$env{'form.username'};
                   11226:     }
                   11227:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11228: 
                   11229: }
                   11230: 
1.36      albertel 11231: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11232: # returns either the contents of the file or 
                   11233: # -1 if the file doesn't exist
1.481     raeburn  11234: #
                   11235: # if the target is a file that was uploaded via DOCS, 
                   11236: # a check will be made to see if a current copy exists on the local server,
                   11237: # if it does this will be served, otherwise a copy will be retrieved from
                   11238: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11239: # the local server.   
1.472     albertel 11240: 
1.36      albertel 11241: sub getfile {
1.538     albertel 11242:     my ($file) = @_;
1.609     banghart 11243:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11244:     &repcopy($file);
                   11245:     return &readfile($file);
                   11246: }
                   11247: 
                   11248: sub repcopy_userfile {
                   11249:     my ($file)=@_;
1.1142    raeburn  11250:     my $londocroot = $perlvar{'lonDocRoot'};
                   11251:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11252:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11253:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11254: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11255:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11256:     if (-e "$file") {
1.828     www      11257: # we already have a local copy, check it out
1.538     albertel 11258: 	my @fileinfo = stat($file);
1.828     www      11259: 	my $rtncode;
                   11260: 	my $info;
1.538     albertel 11261: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11262: 	if ($lwpresp ne 'ok') {
1.828     www      11263: # there is no such file anymore, even though we had a local copy
1.482     albertel 11264: 	    if ($rtncode eq '404') {
1.538     albertel 11265: 		unlink($file);
1.482     albertel 11266: 	    }
                   11267: 	    return -1;
                   11268: 	}
                   11269: 	if ($info < $fileinfo[9]) {
1.828     www      11270: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11271: 	    return 'ok';
1.828     www      11272: 	} else {
                   11273: # the file is outdated, get rid of it
                   11274: 	    unlink($file);
1.482     albertel 11275: 	}
1.828     www      11276:     }
                   11277: # one way or the other, at this point, we don't have the file
                   11278: # construct the correct path for the file
                   11279:     my @parts = ($cdom,$cnum); 
                   11280:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11281: 	push @parts, split(/\//,$1);
                   11282:     }
                   11283:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11284:     foreach my $part (@parts) {
                   11285: 	$path .= '/'.$part;
                   11286: 	if (!-e $path) {
                   11287: 	    mkdir($path,0770);
1.482     albertel 11288: 	}
                   11289:     }
1.828     www      11290: # now the path exists for sure
                   11291: # get a user agent
                   11292:     my $ua=new LWP::UserAgent;
                   11293:     my $transferfile=$file.'.in.transfer';
                   11294: # FIXME: this should flock
                   11295:     if (-e $transferfile) { return 'ok'; }
                   11296:     my $request;
                   11297:     $uri=~s/^\///;
1.980     raeburn  11298:     my $homeserver = &homeserver($cnum,$cdom);
                   11299:     my $protocol = $protocol{$homeserver};
                   11300:     $protocol = 'http' if ($protocol ne 'https');
                   11301:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11302:     my $response=$ua->request($request,$transferfile);
                   11303: # did it work?
                   11304:     if ($response->is_error()) {
                   11305: 	unlink($transferfile);
                   11306: 	&logthis("Userfile repcopy failed for $uri");
                   11307: 	return -1;
                   11308:     }
                   11309: # worked, rename the transfer file
                   11310:     rename($transferfile,$file);
1.607     raeburn  11311:     return 'ok';
1.481     raeburn  11312: }
                   11313: 
1.517     albertel 11314: sub tokenwrapper {
                   11315:     my $uri=shift;
1.980     raeburn  11316:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11317:     $uri=~s|^/||;
1.620     albertel 11318:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11319:     my $token=$1;
1.552     albertel 11320:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11321:     if ($udom && $uname && $file) {
                   11322: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11323:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11324:         my $homeserver = &homeserver($uname,$udom);
                   11325:         my $protocol = $protocol{$homeserver};
                   11326:         $protocol = 'http' if ($protocol ne 'https');
                   11327:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11328:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11329:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11330:     } else {
                   11331:         return '/adm/notfound.html';
                   11332:     }
                   11333: }
                   11334: 
1.828     www      11335: # call with reqtype HEAD: get last modification time
                   11336: # call with reqtype GET: get the file contents
                   11337: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11338: #
1.481     raeburn  11339: sub getuploaded {
                   11340:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11341:     $uri=~s/^\///;
1.980     raeburn  11342:     my $homeserver = &homeserver($cnum,$cdom);
                   11343:     my $protocol = $protocol{$homeserver};
                   11344:     $protocol = 'http' if ($protocol ne 'https');
                   11345:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11346:     my $ua=new LWP::UserAgent;
                   11347:     my $request=new HTTP::Request($reqtype,$uri);
                   11348:     my $response=$ua->request($request);
                   11349:     $$rtncode = $response->code;
1.482     albertel 11350:     if (! $response->is_success()) {
                   11351: 	return 'failed';
                   11352:     }      
                   11353:     if ($reqtype eq 'HEAD') {
1.486     www      11354: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11355:     } elsif ($reqtype eq 'GET') {
                   11356: 	$$info = $response->content;
1.472     albertel 11357:     }
1.482     albertel 11358:     return 'ok';
1.36      albertel 11359: }
                   11360: 
1.481     raeburn  11361: sub readfile {
                   11362:     my $file = shift;
                   11363:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11364:     my $fh;
                   11365:     open($fh,"<$file");
                   11366:     my $a='';
1.800     albertel 11367:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11368:     return $a;
                   11369: }
                   11370: 
1.36      albertel 11371: sub filelocation {
1.590     banghart 11372:     my ($dir,$file) = @_;
                   11373:     my $location;
                   11374:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11375: 
                   11376:     if ($file =~ m-^/adm/-) {
                   11377: 	$file=~s-^/adm/wrapper/-/-;
                   11378: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11379:     }
1.882     albertel 11380: 
1.1139    www      11381:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11382:         $location = $file;
1.609     banghart 11383:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11384:         my ($udom,$uname,$filename)=
1.811     albertel 11385:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11386:         my $home=&homeserver($uname,$udom);
                   11387:         my $is_me=0;
                   11388:         my @ids=&current_machine_ids();
                   11389:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11390:         if ($is_me) {
1.1117    foxr     11391:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11392:         } else {
                   11393:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11394:   	      $udom.'/'.$uname.'/'.$filename;
                   11395:         }
1.882     albertel 11396:     } elsif ($file =~ m-^/adm/-) {
                   11397: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11398:     } else {
                   11399:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11400:         $file=~s:^/(res|priv)/:/:;
                   11401:         my $space=$1;
1.590     banghart 11402:         if ( !( $file =~ m:^/:) ) {
                   11403:             $location = $dir. '/'.$file;
                   11404:         } else {
1.1142    raeburn  11405:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11406:         }
1.59      albertel 11407:     }
1.590     banghart 11408:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11409:     while ($location=~m{/\.\./}) {
                   11410: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11411: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11412: 	} else {
                   11413: 	    $location=~ s{/\.\./}{/}g;
                   11414: 	}
                   11415:     } #remove dir/..
1.590     banghart 11416:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11417:     return $location;
1.46      www      11418: }
1.36      albertel 11419: 
1.46      www      11420: sub hreflocation {
                   11421:     my ($dir,$file)=@_;
1.980     raeburn  11422:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11423: 	$file=filelocation($dir,$file);
1.700     albertel 11424:     } elsif ($file=~m-^/adm/-) {
                   11425: 	$file=~s-^/adm/wrapper/-/-;
                   11426: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11427:     }
                   11428:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11429: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11430:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11431: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11432: 	        {/uploaded/$1/$2/}x;
1.46      www      11433:     }
1.913     albertel 11434:     if ($file=~ m{^/userfiles/}) {
                   11435: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11436:     }
1.462     albertel 11437:     return $file;
1.465     albertel 11438: }
                   11439: 
1.1139    www      11440: 
                   11441: 
                   11442: 
                   11443: 
1.465     albertel 11444: sub current_machine_domains {
1.853     albertel 11445:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11446: }
                   11447: 
                   11448: sub machine_domains {
                   11449:     my ($hostname) = @_;
1.465     albertel 11450:     my @domains;
1.838     albertel 11451:     my %hostname = &all_hostnames();
1.465     albertel 11452:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11453: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11454: 	if ($hostname eq $name) {
1.844     albertel 11455: 	    push(@domains,&host_domain($id));
1.465     albertel 11456: 	}
                   11457:     }
                   11458:     return @domains;
                   11459: }
                   11460: 
                   11461: sub current_machine_ids {
1.853     albertel 11462:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11463: }
                   11464: 
                   11465: sub machine_ids {
                   11466:     my ($hostname) = @_;
                   11467:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11468:     my @ids;
1.888     albertel 11469:     my %name_to_host = &all_names();
1.889     albertel 11470:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11471: 	return @{ $name_to_host{$hostname} };
                   11472:     }
                   11473:     return;
1.31      www      11474: }
                   11475: 
1.824     raeburn  11476: sub additional_machine_domains {
                   11477:     my @domains;
                   11478:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11479:     while( my $line = <$fh>) {
                   11480:         $line =~ s/\s//g;
                   11481:         push(@domains,$line);
                   11482:     }
                   11483:     return @domains;
                   11484: }
                   11485: 
                   11486: sub default_login_domain {
                   11487:     my $domain = $perlvar{'lonDefDomain'};
                   11488:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11489:     foreach my $posdom (&current_machine_domains(),
                   11490:                         &additional_machine_domains()) {
                   11491:         if (lc($posdom) eq lc($testdomain)) {
                   11492:             $domain=$posdom;
                   11493:             last;
                   11494:         }
                   11495:     }
                   11496:     return $domain;
                   11497: }
                   11498: 
1.31      www      11499: # ------------------------------------------------------------- Declutters URLs
                   11500: 
                   11501: sub declutter {
                   11502:     my $thisfn=shift;
1.569     albertel 11503:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11504:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11505:     $thisfn=~s/^\///;
1.697     albertel 11506:     $thisfn=~s|^adm/wrapper/||;
                   11507:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11508:     $thisfn=~s/^res\///;
1.1172    bisitz   11509:     $thisfn=~s/^priv\///;
1.1032    raeburn  11510:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11511:         $thisfn=~s/\?.+$//;
                   11512:     }
1.268     www      11513:     return $thisfn;
                   11514: }
                   11515: 
                   11516: # ------------------------------------------------------------- Clutter up URLs
                   11517: 
                   11518: sub clutter {
                   11519:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11520:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11521: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11522:        $thisfn='/res'.$thisfn; 
                   11523:     }
1.1031    raeburn  11524:     if ($thisfn !~m|^/adm|) {
                   11525: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11526: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11527: 	} else {
                   11528: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11529: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11530: 	    if ($embstyle eq 'ssi'
                   11531: 		|| ($embstyle eq 'hdn')
                   11532: 		|| ($embstyle eq 'rat')
                   11533: 		|| ($embstyle eq 'prv')
                   11534: 		|| ($embstyle eq 'ign')) {
                   11535: 		#do nothing with these
                   11536: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11537: 		|| ($embstyle eq 'emb')
                   11538: 		|| ($embstyle eq 'wrp')) {
                   11539: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11540: 	    } elsif ($embstyle eq 'unk'
                   11541: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11542: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11543: 	    } else {
1.718     www      11544: #		&logthis("Got a blank emb style");
1.695     albertel 11545: 	    }
1.694     albertel 11546: 	}
                   11547:     }
1.31      www      11548:     return $thisfn;
1.12      www      11549: }
                   11550: 
1.787     albertel 11551: sub clutter_with_no_wrapper {
                   11552:     my $uri = &clutter(shift);
                   11553:     if ($uri =~ m-^/adm/-) {
                   11554: 	$uri =~ s-^/adm/wrapper/-/-;
                   11555: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11556:     }
                   11557:     return $uri;
                   11558: }
                   11559: 
1.557     albertel 11560: sub freeze_escape {
                   11561:     my ($value)=@_;
                   11562:     if (ref($value)) {
                   11563: 	$value=&nfreeze($value);
                   11564: 	return '__FROZEN__'.&escape($value);
                   11565:     }
                   11566:     return &escape($value);
                   11567: }
                   11568: 
1.11      www      11569: 
1.557     albertel 11570: sub thaw_unescape {
                   11571:     my ($value)=@_;
                   11572:     if ($value =~ /^__FROZEN__/) {
                   11573: 	substr($value,0,10,undef);
                   11574: 	$value=&unescape($value);
                   11575: 	return &thaw($value);
                   11576:     }
                   11577:     return &unescape($value);
                   11578: }
                   11579: 
1.436     albertel 11580: sub correct_line_ends {
                   11581:     my ($result)=@_;
                   11582:     $$result =~s/\r\n/\n/mg;
                   11583:     $$result =~s/\r/\n/mg;
1.415     albertel 11584: }
1.1       albertel 11585: # ================================================================ Main Program
                   11586: 
1.184     www      11587: sub goodbye {
1.204     albertel 11588:    &logthis("Starting Shut down");
1.443     albertel 11589: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11590:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11591: #converted
1.599     albertel 11592: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11593:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11594: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11595: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11596: #1.1 only
1.870     albertel 11597: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11598: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11599: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11600: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11601:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11602:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11603:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11604:    &flushcourselogs();
                   11605:    &logthis("Shutting down");
                   11606: }
                   11607: 
1.852     albertel 11608: sub get_dns {
1.1172.2.17  raeburn  11609:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11610:     if (!$ignore_cache) {
                   11611: 	my ($content,$cached)=
                   11612: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11613: 	if ($cached) {
1.1172.2.17  raeburn  11614: 	    &$func($content,$hashref);
1.869     albertel 11615: 	    return;
                   11616: 	}
                   11617:     }
                   11618: 
                   11619:     my %alldns;
1.852     albertel 11620:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11621:     foreach my $dns (<$config>) {
                   11622: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11623:         my $line = $1;
                   11624:         my ($host,$protocol) = split(/:/,$line);
                   11625:         if ($protocol ne 'https') {
                   11626:             $protocol = 'http';
                   11627:         }
                   11628: 	$alldns{$host} = $protocol;
1.869     albertel 11629:     }
                   11630:     while (%alldns) {
                   11631: 	my ($dns) = keys(%alldns);
1.852     albertel 11632: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11633:         $ua->timeout(30);
1.979     raeburn  11634: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11635: 	my $response=$ua->request($request);
1.979     raeburn  11636:         delete($alldns{$dns});
1.852     albertel 11637: 	next if ($response->is_error());
                   11638: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11639:         unless ($nocache) {
1.1172.2.23  raeburn  11640: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11641:         }
                   11642: 	&$func(\@content,$hashref);
1.869     albertel 11643: 	return;
1.852     albertel 11644:     }
                   11645:     close($config);
1.871     albertel 11646:     my $which = (split('/',$url))[3];
                   11647:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11648:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11649:     my @content = <$config>;
1.1172.2.17  raeburn  11650:     &$func(\@content,$hashref);
                   11651:     return;
                   11652: }
                   11653: 
                   11654: # ------------------------------------------------------Get DNS checksums file
                   11655: sub parse_dns_checksums_tab {
                   11656:     my ($lines,$hashref) = @_;
                   11657:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11658:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11659:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11660:     my (%chksum,%revnum);
                   11661:     if (ref($lines) eq 'ARRAY') {
                   11662:         chomp(@{$lines});
                   11663:         my $versions = shift(@{$lines});
                   11664:         my %supported;
                   11665:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11666:             my $releaseslist = $1;
                   11667:             if ($releaseslist =~ /,/) {
                   11668:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11669:             } elsif ($releaseslist) {
                   11670:                 $supported{$releaseslist} = 1;
                   11671:             }
                   11672:         }
                   11673:         if ($supported{$release}) {
                   11674:             my $matchthis = 0;
                   11675:             foreach my $line (@{$lines}) {
                   11676:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11677:                     if ($matchthis) {
                   11678:                         last;
                   11679:                     } elsif ($1 eq $release) {
                   11680:                         $matchthis = 1;
                   11681:                     }
                   11682:                 } elsif ($matchthis) {
                   11683:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11684:                     $chksum{$file} = $shasum;
                   11685:                     $revnum{$file} = $version;
                   11686:                 }
                   11687:             }
                   11688:             if (ref($hashref) eq 'HASH') {
                   11689:                 %{$hashref} = (
                   11690:                                 sums     => \%chksum,
                   11691:                                 versions => \%revnum,
                   11692:                               );
                   11693:             }
                   11694:         }
                   11695:     }
1.869     albertel 11696:     return;
1.852     albertel 11697: }
1.1172.2.17  raeburn  11698: 
                   11699: sub fetch_dns_checksums {
                   11700:     my %checksums;
                   11701:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11702:              \%checksums);
                   11703:     return \%checksums;
                   11704: }
                   11705: 
1.327     albertel 11706: # ------------------------------------------------------------ Read domain file
                   11707: {
1.852     albertel 11708:     my $loaded;
1.846     albertel 11709:     my %domain;
                   11710: 
1.852     albertel 11711:     sub parse_domain_tab {
                   11712: 	my ($lines) = @_;
                   11713: 	foreach my $line (@$lines) {
                   11714: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11715: 
1.846     albertel 11716: 	    chomp($line);
1.852     albertel 11717: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11718: 	    my %this_domain;
                   11719: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11720: 			       'lang_def', 'city', 'longi', 'lati',
                   11721: 			       'primary') {
                   11722: 		$this_domain{$field} = shift(@elements);
                   11723: 	    }
                   11724: 	    $domain{$name} = \%this_domain;
1.852     albertel 11725: 	}
                   11726:     }
1.864     albertel 11727: 
                   11728:     sub reset_domain_info {
                   11729: 	undef($loaded);
                   11730: 	undef(%domain);
                   11731:     }
                   11732: 
1.852     albertel 11733:     sub load_domain_tab {
1.869     albertel 11734: 	my ($ignore_cache) = @_;
                   11735: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11736: 	my $fh;
                   11737: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11738: 	    my @lines = <$fh>;
                   11739: 	    &parse_domain_tab(\@lines);
1.448     albertel 11740: 	}
1.852     albertel 11741: 	close($fh);
                   11742: 	$loaded = 1;
1.327     albertel 11743:     }
1.846     albertel 11744: 
                   11745:     sub domain {
1.852     albertel 11746: 	&load_domain_tab() if (!$loaded);
                   11747: 
1.846     albertel 11748: 	my ($name,$what) = @_;
                   11749: 	return if ( !exists($domain{$name}) );
                   11750: 
                   11751: 	if (!$what) {
                   11752: 	    return $domain{$name}{'description'};
                   11753: 	}
                   11754: 	return $domain{$name}{$what};
                   11755:     }
1.974     raeburn  11756: 
                   11757:     sub domain_info {
                   11758:         &load_domain_tab() if (!$loaded);
                   11759:         return %domain;
                   11760:     }
                   11761: 
1.327     albertel 11762: }
                   11763: 
                   11764: 
1.1       albertel 11765: # ------------------------------------------------------------- Read hosts file
                   11766: {
1.838     albertel 11767:     my %hostname;
1.844     albertel 11768:     my %hostdom;
1.845     albertel 11769:     my %libserv;
1.852     albertel 11770:     my $loaded;
1.888     albertel 11771:     my %name_to_host;
1.1074    raeburn  11772:     my %internetdom;
1.1107    raeburn  11773:     my %LC_dns_serv;
1.852     albertel 11774: 
                   11775:     sub parse_hosts_tab {
                   11776: 	my ($file) = @_;
                   11777: 	foreach my $configline (@$file) {
                   11778: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11779:             chomp($configline);
                   11780: 	    if ($configline =~ /^\^/) {
                   11781:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11782:                     $LC_dns_serv{$1} = 1;
                   11783:                 }
                   11784:                 next;
                   11785:             }
1.1074    raeburn  11786: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11787: 	    $name=~s/\s//g;
                   11788: 	    if ($id && $domain && $role && $name) {
                   11789: 		$hostname{$id}=$name;
1.888     albertel 11790: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11791: 		$hostdom{$id}=$domain;
                   11792: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11793:                 if (defined($protocol)) {
                   11794:                     if ($protocol eq 'https') {
                   11795:                         $protocol{$id} = $protocol;
                   11796:                     } else {
                   11797:                         $protocol{$id} = 'http'; 
                   11798:                     }
1.968     raeburn  11799:                 } else {
1.969     raeburn  11800:                     $protocol{$id} = 'http';
1.968     raeburn  11801:                 }
1.1074    raeburn  11802:                 if (defined($intdom)) {
                   11803:                     $internetdom{$id} = $intdom;
                   11804:                 }
1.852     albertel 11805: 	    }
                   11806: 	}
                   11807:     }
1.864     albertel 11808:     
                   11809:     sub reset_hosts_info {
1.897     albertel 11810: 	&purge_remembered();
1.864     albertel 11811: 	&reset_domain_info();
                   11812: 	&reset_hosts_ip_info();
1.892     albertel 11813: 	undef(%name_to_host);
1.864     albertel 11814: 	undef(%hostname);
                   11815: 	undef(%hostdom);
                   11816: 	undef(%libserv);
                   11817: 	undef($loaded);
                   11818:     }
1.1       albertel 11819: 
1.852     albertel 11820:     sub load_hosts_tab {
1.869     albertel 11821: 	my ($ignore_cache) = @_;
                   11822: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11823: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11824: 	my @config = <$config>;
                   11825: 	&parse_hosts_tab(\@config);
                   11826: 	close($config);
                   11827: 	$loaded=1;
1.1       albertel 11828:     }
1.852     albertel 11829: 
1.838     albertel 11830:     sub hostname {
1.852     albertel 11831: 	&load_hosts_tab() if (!$loaded);
                   11832: 
1.838     albertel 11833: 	my ($lonid) = @_;
                   11834: 	return $hostname{$lonid};
                   11835:     }
1.845     albertel 11836: 
1.838     albertel 11837:     sub all_hostnames {
1.852     albertel 11838: 	&load_hosts_tab() if (!$loaded);
                   11839: 
1.838     albertel 11840: 	return %hostname;
                   11841:     }
1.845     albertel 11842: 
1.888     albertel 11843:     sub all_names {
                   11844: 	&load_hosts_tab() if (!$loaded);
                   11845: 
                   11846: 	return %name_to_host;
                   11847:     }
                   11848: 
1.974     raeburn  11849:     sub all_host_domain {
                   11850:         &load_hosts_tab() if (!$loaded);
                   11851:         return %hostdom;
                   11852:     }
                   11853: 
1.845     albertel 11854:     sub is_library {
1.852     albertel 11855: 	&load_hosts_tab() if (!$loaded);
                   11856: 
1.845     albertel 11857: 	return exists($libserv{$_[0]});
                   11858:     }
                   11859: 
                   11860:     sub all_library {
1.852     albertel 11861: 	&load_hosts_tab() if (!$loaded);
                   11862: 
1.845     albertel 11863: 	return %libserv;
                   11864:     }
                   11865: 
1.1062    droeschl 11866:     sub unique_library {
                   11867: 	#2x reverse removes all hostnames that appear more than once
                   11868:         my %unique = reverse &all_library();
                   11869:         return reverse %unique;
                   11870:     }
                   11871: 
1.841     albertel 11872:     sub get_servers {
1.852     albertel 11873: 	&load_hosts_tab() if (!$loaded);
                   11874: 
1.841     albertel 11875: 	my ($domain,$type) = @_;
                   11876: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11877: 	                                          : %hostname;
                   11878: 	my %result;
1.842     albertel 11879: 	if (ref($domain) eq 'ARRAY') {
                   11880: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11881: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11882: 		    $result{$host} = $hostname;
                   11883: 		}
                   11884: 	    }
                   11885: 	} else {
                   11886: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11887: 		if ($hostdom{$host} eq $domain) {
                   11888: 		    $result{$host} = $hostname;
                   11889: 		}
1.841     albertel 11890: 	    }
                   11891: 	}
                   11892: 	return %result;
                   11893:     }
1.845     albertel 11894: 
1.1062    droeschl 11895:     sub get_unique_servers {
                   11896:         my %unique = reverse &get_servers(@_);
                   11897: 	return reverse %unique;
                   11898:     }
                   11899: 
1.844     albertel 11900:     sub host_domain {
1.852     albertel 11901: 	&load_hosts_tab() if (!$loaded);
                   11902: 
1.844     albertel 11903: 	my ($lonid) = @_;
                   11904: 	return $hostdom{$lonid};
                   11905:     }
                   11906: 
1.841     albertel 11907:     sub all_domains {
1.852     albertel 11908: 	&load_hosts_tab() if (!$loaded);
                   11909: 
1.841     albertel 11910: 	my %seen;
                   11911: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11912: 	return @uniq;
                   11913:     }
1.1074    raeburn  11914: 
                   11915:     sub internet_dom {
                   11916:         &load_hosts_tab() if (!$loaded);
                   11917: 
                   11918:         my ($lonid) = @_;
                   11919:         return $internetdom{$lonid};
                   11920:     }
1.1107    raeburn  11921: 
                   11922:     sub is_LC_dns {
                   11923:         &load_hosts_tab() if (!$loaded);
                   11924: 
                   11925:         my ($hostname) = @_;
                   11926:         return exists($LC_dns_serv{$hostname});
                   11927:     }
                   11928: 
1.1       albertel 11929: }
                   11930: 
1.847     albertel 11931: { 
                   11932:     my %iphost;
1.856     albertel 11933:     my %name_to_ip;
                   11934:     my %lonid_to_ip;
1.869     albertel 11935: 
1.847     albertel 11936:     sub get_hosts_from_ip {
                   11937: 	my ($ip) = @_;
                   11938: 	my %iphosts = &get_iphost();
                   11939: 	if (ref($iphosts{$ip})) {
                   11940: 	    return @{$iphosts{$ip}};
                   11941: 	}
                   11942: 	return;
1.839     albertel 11943:     }
1.864     albertel 11944:     
                   11945:     sub reset_hosts_ip_info {
                   11946: 	undef(%iphost);
                   11947: 	undef(%name_to_ip);
                   11948: 	undef(%lonid_to_ip);
                   11949:     }
1.856     albertel 11950: 
                   11951:     sub get_host_ip {
                   11952: 	my ($lonid) = @_;
                   11953: 	if (exists($lonid_to_ip{$lonid})) {
                   11954: 	    return $lonid_to_ip{$lonid};
                   11955: 	}
                   11956: 	my $name=&hostname($lonid);
                   11957:    	my $ip = gethostbyname($name);
                   11958: 	return if (!$ip || length($ip) ne 4);
                   11959: 	$ip=inet_ntoa($ip);
                   11960: 	$name_to_ip{$name}   = $ip;
                   11961: 	$lonid_to_ip{$lonid} = $ip;
                   11962: 	return $ip;
                   11963:     }
1.847     albertel 11964:     
                   11965:     sub get_iphost {
1.869     albertel 11966: 	my ($ignore_cache) = @_;
1.894     albertel 11967: 
1.869     albertel 11968: 	if (!$ignore_cache) {
                   11969: 	    if (%iphost) {
                   11970: 		return %iphost;
                   11971: 	    }
                   11972: 	    my ($ip_info,$cached)=
                   11973: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11974: 	    if ($cached) {
                   11975: 		%iphost      = %{$ip_info->[0]};
                   11976: 		%name_to_ip  = %{$ip_info->[1]};
                   11977: 		%lonid_to_ip = %{$ip_info->[2]};
                   11978: 		return %iphost;
                   11979: 	    }
                   11980: 	}
1.894     albertel 11981: 
                   11982: 	# get yesterday's info for fallback
                   11983: 	my %old_name_to_ip;
                   11984: 	my ($ip_info,$cached)=
                   11985: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11986: 	if ($cached) {
                   11987: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11988: 	}
                   11989: 
1.888     albertel 11990: 	my %name_to_host = &all_names();
                   11991: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11992: 	    my $ip;
                   11993: 	    if (!exists($name_to_ip{$name})) {
                   11994: 		$ip = gethostbyname($name);
                   11995: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11996: 		    if (defined($old_name_to_ip{$name})) {
                   11997: 			$ip = $old_name_to_ip{$name};
                   11998: 			&logthis("Can't find $name defaulting to old $ip");
                   11999: 		    } else {
                   12000: 			&logthis("Name $name no IP found");
                   12001: 			next;
                   12002: 		    }
                   12003: 		} else {
                   12004: 		    $ip=inet_ntoa($ip);
1.847     albertel 12005: 		}
                   12006: 		$name_to_ip{$name} = $ip;
                   12007: 	    } else {
                   12008: 		$ip = $name_to_ip{$name};
1.653     albertel 12009: 	    }
1.888     albertel 12010: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12011: 		$lonid_to_ip{$id} = $ip;
                   12012: 	    }
                   12013: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12014: 	}
1.1172.2.23  raeburn  12015: 	&do_cache_new('iphost','iphost',
                   12016: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12017: 		      48*60*60);
1.869     albertel 12018: 
1.847     albertel 12019: 	return %iphost;
1.598     albertel 12020:     }
                   12021: 
1.992     raeburn  12022:     #
                   12023:     #  Given a DNS returns the loncapa host name for that DNS 
                   12024:     # 
                   12025:     sub host_from_dns {
                   12026:         my ($dns) = @_;
                   12027:         my @hosts;
                   12028:         my $ip;
                   12029: 
1.993     raeburn  12030:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12031:             $ip = $name_to_ip{$dns};
                   12032:         }
                   12033:         if (!$ip) {
                   12034:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12035:             if (length($ip) == 4) { 
                   12036: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12037:             }
                   12038:         }
                   12039:         if ($ip) {
                   12040: 	    @hosts = get_hosts_from_ip($ip);
                   12041: 	    return $hosts[0];
                   12042:         }
                   12043:         return undef;
1.986     foxr     12044:     }
1.992     raeburn  12045: 
1.1074    raeburn  12046:     sub get_internet_names {
                   12047:         my ($lonid) = @_;
                   12048:         return if ($lonid eq '');
                   12049:         my ($idnref,$cached)=
                   12050:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12051:         if ($cached) {
                   12052:             return $idnref;
                   12053:         }
                   12054:         my $ip = &get_host_ip($lonid);
                   12055:         my @hosts = &get_hosts_from_ip($ip);
                   12056:         my %iphost = &get_iphost();
                   12057:         my (@idns,%seen);
                   12058:         foreach my $id (@hosts) {
                   12059:             my $dom = &host_domain($id);
                   12060:             my $prim_id = &domain($dom,'primary');
                   12061:             my $prim_ip = &get_host_ip($prim_id);
                   12062:             next if ($seen{$prim_ip});
                   12063:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12064:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12065:                     my $intdom = &internet_dom($id);
                   12066:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12067:                         push(@idns,$intdom);
                   12068:                     }
                   12069:                 }
                   12070:             }
                   12071:             $seen{$prim_ip} = 1;
                   12072:         }
1.1172.2.23  raeburn  12073:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12074:     }
                   12075: 
1.986     foxr     12076: }
                   12077: 
1.1079    raeburn  12078: sub all_loncaparevs {
                   12079:     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);
                   12080: }
                   12081: 
1.1172.2.27  raeburn  12082: # ------------------------------------------------------- Read loncaparev table
                   12083: {
                   12084:     sub load_loncaparevs {
                   12085:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12086:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12087:                 while (my $configline=<$config>) {
                   12088:                     chomp($configline);
                   12089:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12090:                     $loncaparevs{$hostid}=$loncaparev;
                   12091:                 }
                   12092:                 close($config);
                   12093:             }
                   12094:         }
                   12095:     }
                   12096: }
                   12097: 
                   12098: # ----------------------------------------------------- Read serverhostID table
                   12099: {
                   12100:     sub load_serverhomeIDs {
                   12101:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12102:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12103:                 while (my $configline=<$config>) {
                   12104:                     chomp($configline);
                   12105:                     my ($name,$id)=split(/:/,$configline);
                   12106:                     $serverhomeIDs{$name}=$id;
                   12107:                 }
                   12108:                 close($config);
                   12109:             }
                   12110:         }
                   12111:     }
                   12112: }
                   12113: 
                   12114: 
1.862     albertel 12115: BEGIN {
                   12116: 
                   12117: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12118:     unless ($readit) {
                   12119: {
                   12120:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12121:     %perlvar = (%perlvar,%{$configvars});
                   12122: }
                   12123: 
                   12124: 
1.1       albertel 12125: # ------------------------------------------------------ Read spare server file
                   12126: {
1.448     albertel 12127:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12128: 
                   12129:     while (my $configline=<$config>) {
                   12130:        chomp($configline);
1.284     matthew  12131:        if ($configline) {
1.784     albertel 12132: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12133: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12134: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12135:        }
                   12136:     }
1.448     albertel 12137:     close($config);
1.1       albertel 12138: }
1.11      www      12139: # ------------------------------------------------------------ Read permissions
                   12140: {
1.448     albertel 12141:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12142: 
                   12143:     while (my $configline=<$config>) {
1.448     albertel 12144: 	chomp($configline);
                   12145: 	if ($configline) {
                   12146: 	    my ($role,$perm)=split(/ /,$configline);
                   12147: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12148: 	}
1.11      www      12149:     }
1.448     albertel 12150:     close($config);
1.11      www      12151: }
                   12152: 
                   12153: # -------------------------------------------- Read plain texts for permissions
                   12154: {
1.448     albertel 12155:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12156: 
                   12157:     while (my $configline=<$config>) {
1.448     albertel 12158: 	chomp($configline);
                   12159: 	if ($configline) {
1.742     raeburn  12160: 	    my ($short,@plain)=split(/:/,$configline);
                   12161:             %{$prp{$short}} = ();
                   12162: 	    if (@plain > 0) {
                   12163:                 $prp{$short}{'std'} = $plain[0];
                   12164:                 for (my $i=1; $i<@plain; $i++) {
                   12165:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12166:                 }
                   12167:             }
1.448     albertel 12168: 	}
1.135     www      12169:     }
1.448     albertel 12170:     close($config);
1.135     www      12171: }
                   12172: 
                   12173: # ---------------------------------------------------------- Read package table
                   12174: {
1.448     albertel 12175:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12176: 
                   12177:     while (my $configline=<$config>) {
1.483     albertel 12178: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12179: 	chomp($configline);
                   12180: 	my ($short,$plain)=split(/:/,$configline);
                   12181: 	my ($pack,$name)=split(/\&/,$short);
                   12182: 	if ($plain ne '') {
                   12183: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12184: 	    $packagetab{$short}=$plain; 
                   12185: 	}
1.11      www      12186:     }
1.448     albertel 12187:     close($config);
1.329     matthew  12188: }
                   12189: 
1.1172.2.27  raeburn  12190: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12191: 
1.1172.2.27  raeburn  12192: &load_loncaparevs();
                   12193: 
                   12194: # ------------------------------------------------------- Read serverhostID table
                   12195: 
                   12196: &load_serverhomeIDs();
1.1074    raeburn  12197: 
1.1172.2.27  raeburn  12198: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12199: {
                   12200:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12201:     if (-e $file) {
                   12202:         my $parser = HTML::LCParser->new($file);
                   12203:         while (my $token = $parser->get_token()) {
                   12204:             if ($token->[0] eq 'S') {
                   12205:                 my $item = $token->[1];
                   12206:                 my $name = $token->[2]{'name'};
                   12207:                 my $value = $token->[2]{'value'};
                   12208:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12209:                     my $release = $parser->get_text();
                   12210:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12211:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12212:                 }
                   12213:             }
                   12214:         }
                   12215:     }
1.1073    raeburn  12216: }
                   12217: 
1.1138    raeburn  12218: # ---------------------------------------------------------- Read managers table
                   12219: {
                   12220:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12221:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12222:             while (my $configline=<$config>) {
                   12223:                 chomp($configline);
                   12224:                 next if ($configline =~ /^\#/);
                   12225:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12226:                     $managerstab{$configline} = 1;
                   12227:                 }
                   12228:             }
                   12229:             close($config);
                   12230:         }
                   12231:     }
                   12232: }
                   12233: 
1.329     matthew  12234: # ------------- set up temporary directory
                   12235: {
1.1117    foxr     12236:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12237: 
1.11      www      12238: }
                   12239: 
1.794     albertel 12240: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12241: 				'compress_threshold'=> 20_000,
                   12242:  			        });
1.185     www      12243: 
1.281     www      12244: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12245: $dumpcount=0;
1.958     www      12246: $locknum=0;
1.22      www      12247: 
1.163     harris41 12248: &logtouch();
1.672     albertel 12249: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12250: $readit=1;
1.564     albertel 12251:     {
                   12252: 	use integer;
                   12253: 	my $test=(2**32)+1;
1.568     albertel 12254: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12255: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12256:     }
1.1172.2.18  raeburn  12257: 
                   12258:     {
                   12259:         eval {
                   12260:             ($apache) =
                   12261:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12262:         };
                   12263:         if ($@) {
                   12264:            $apache = 1.3;
                   12265:         }
                   12266:     }
                   12267: 
1.195     www      12268: }
1.1       albertel 12269: }
1.179     www      12270: 
1.1       albertel 12271: 1;
1.191     harris41 12272: __END__
                   12273: 
1.243     albertel 12274: =pod
                   12275: 
1.191     harris41 12276: =head1 NAME
                   12277: 
1.243     albertel 12278: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12279: 
                   12280: =head1 SYNOPSIS
                   12281: 
1.243     albertel 12282: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12283: 
                   12284:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12285: 
1.243     albertel 12286: Common parameters:
                   12287: 
                   12288: =over 4
                   12289: 
                   12290: =item *
                   12291: 
                   12292: $uname : an internal username (if $cname expecting a course Id specifically)
                   12293: 
                   12294: =item *
                   12295: 
                   12296: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12297: 
                   12298: =item *
                   12299: 
                   12300: $symb : a resource instance identifier
                   12301: 
                   12302: =item *
                   12303: 
                   12304: $namespace : the name of a .db file that contains the data needed or
                   12305: being set.
                   12306: 
                   12307: =back
                   12308: 
1.394     bowersj2 12309: =head1 OVERVIEW
1.191     harris41 12310: 
1.394     bowersj2 12311: lonnet provides subroutines which interact with the
                   12312: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12313: about classes, users, and resources.
1.243     albertel 12314: 
                   12315: For many of these objects you can also use this to store data about
                   12316: them or modify them in various ways.
1.191     harris41 12317: 
1.394     bowersj2 12318: =head2 Symbs
1.191     harris41 12319: 
1.394     bowersj2 12320: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12321: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12322: map, the resource number of the resource in the map, and the URL of
                   12323: the resource itself. The latter is somewhat redundant, but might help
                   12324: if maps change.
                   12325: 
                   12326: An example is
                   12327: 
                   12328:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12329: 
                   12330: The respective map entry is
                   12331: 
                   12332:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12333:   title="Problem 2">
                   12334:  </resource>
                   12335: 
                   12336: Symbs are used by the random number generator, as well as to store and
                   12337: restore data specific to a certain instance of for example a problem.
                   12338: 
                   12339: =head2 Storing And Retrieving Data
                   12340: 
                   12341: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12342: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12343: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12344: is is the non-critical message twin of cstore. These functions are for
                   12345: handlers to store a perl hash to a user's permanent data space in an
                   12346: easy manner, and to retrieve it again on another call. It is expected
                   12347: that a handler would use this once at the beginning to retrieve data,
                   12348: and then again once at the end to send only the new data back.
                   12349: 
                   12350: The data is stored in the user's data directory on the user's
                   12351: homeserver under the ID of the course.
                   12352: 
                   12353: The hash that is returned by restore will have all of the previous
                   12354: value for all of the elements of the hash.
                   12355: 
                   12356: Example:
                   12357: 
                   12358:  #creating a hash
                   12359:  my %hash;
                   12360:  $hash{'foo'}='bar';
                   12361: 
                   12362:  #storing it
                   12363:  &Apache::lonnet::cstore(\%hash);
                   12364: 
                   12365:  #changing a value
                   12366:  $hash{'foo'}='notbar';
                   12367: 
                   12368:  #adding a new value
                   12369:  $hash{'bar'}='foo';
                   12370:  &Apache::lonnet::cstore(\%hash);
                   12371: 
                   12372:  #retrieving the hash
                   12373:  my %history=&Apache::lonnet::restore();
                   12374: 
                   12375:  #print the hash
                   12376:  foreach my $key (sort(keys(%history))) {
                   12377:    print("\%history{$key} = $history{$key}");
                   12378:  }
                   12379: 
                   12380: Will print out:
1.191     harris41 12381: 
1.394     bowersj2 12382:  %history{1:foo} = bar
                   12383:  %history{1:keys} = foo:timestamp
                   12384:  %history{1:timestamp} = 990455579
                   12385:  %history{2:bar} = foo
                   12386:  %history{2:foo} = notbar
                   12387:  %history{2:keys} = foo:bar:timestamp
                   12388:  %history{2:timestamp} = 990455580
                   12389:  %history{bar} = foo
                   12390:  %history{foo} = notbar
                   12391:  %history{timestamp} = 990455580
                   12392:  %history{version} = 2
                   12393: 
                   12394: Note that the special hash entries C<keys>, C<version> and
                   12395: C<timestamp> were added to the hash. C<version> will be equal to the
                   12396: total number of versions of the data that have been stored. The
                   12397: C<timestamp> attribute will be the UNIX time the hash was
                   12398: stored. C<keys> is available in every historical section to list which
                   12399: keys were added or changed at a specific historical revision of a
                   12400: hash.
                   12401: 
                   12402: B<Warning>: do not store the hash that restore returns directly. This
                   12403: will cause a mess since it will restore the historical keys as if the
                   12404: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12405: 
1.394     bowersj2 12406: Calling convention:
1.191     harris41 12407: 
1.1172.2.27  raeburn  12408:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12409:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12410: 
1.394     bowersj2 12411: For more detailed information, see lonnet specific documentation.
1.191     harris41 12412: 
1.394     bowersj2 12413: =head1 RETURN MESSAGES
1.191     harris41 12414: 
1.394     bowersj2 12415: =over 4
1.191     harris41 12416: 
1.394     bowersj2 12417: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12418: 
1.394     bowersj2 12419: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12420: when the connection is brought back up
1.191     harris41 12421: 
1.394     bowersj2 12422: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12423: for later delivery
1.191     harris41 12424: 
1.967     bisitz   12425: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12426: 
1.394     bowersj2 12427: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12428: that was requested
1.191     harris41 12429: 
1.243     albertel 12430: =back
1.191     harris41 12431: 
1.243     albertel 12432: =head1 PUBLIC SUBROUTINES
1.191     harris41 12433: 
1.243     albertel 12434: =head2 Session Environment Functions
1.191     harris41 12435: 
1.243     albertel 12436: =over 4
1.191     harris41 12437: 
1.394     bowersj2 12438: =item * 
                   12439: X<appenv()>
1.949     raeburn  12440: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12441: the user envirnoment file, and will be restored for each access this
1.620     albertel 12442: user makes during this session, also modifies the %env for the current
1.949     raeburn  12443: process. Optional rolesarrayref - if defined contains a reference to an array
                   12444: of roles which are exempt from the restriction on modifying user.role entries 
                   12445: in the user's environment.db and in %env.    
1.191     harris41 12446: 
                   12447: =item *
1.394     bowersj2 12448: X<delenv()>
1.987     raeburn  12449: B<delenv($delthis,$regexp)>: removes all items from the session
                   12450: environment file that begin with $delthis. If the 
                   12451: optional second arg - $regexp - is true, $delthis is treated as a 
                   12452: regular expression, otherwise \Q$delthis\E is used. 
                   12453: The values are also deleted from the current processes %env.
1.191     harris41 12454: 
1.795     albertel 12455: =item * get_env_multiple($name) 
                   12456: 
                   12457: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12458: values may be defined and end up as an array ref.
                   12459: 
                   12460: returns an array of values
                   12461: 
1.243     albertel 12462: =back
                   12463: 
                   12464: =head2 User Information
1.191     harris41 12465: 
1.243     albertel 12466: =over 4
1.191     harris41 12467: 
                   12468: =item *
1.394     bowersj2 12469: X<queryauthenticate()>
                   12470: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12471: authentication scheme
                   12472: 
                   12473: =item *
1.394     bowersj2 12474: X<authenticate()>
1.1073    raeburn  12475: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12476: authenticate user from domain's lib servers (first use the current
                   12477: one). C<$upass> should be the users password.
1.1073    raeburn  12478: $checkdefauth is optional (value is 1 if a check should be made to
                   12479:    authenticate user using default authentication method, and allow
                   12480:    account creation if username does not have account in the domain).
                   12481: $clientcancheckhost is optional (value is 1 if checking whether the
                   12482:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12483: 
                   12484: =item *
1.394     bowersj2 12485: X<homeserver()>
                   12486: B<homeserver($uname,$udom)>: find the server which has
                   12487: the user's directory and files (there must be only one), this caches
                   12488: the answer, and also caches if there is a borken connection.
1.191     harris41 12489: 
                   12490: =item *
1.394     bowersj2 12491: X<idget()>
                   12492: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12493: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12494: username, and only 1 username per ID in a specific domain) (returns
                   12495: hash: id=>name,id=>name)
1.191     harris41 12496: 
                   12497: =item *
1.394     bowersj2 12498: X<idrget()>
                   12499: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12500: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12501: 
                   12502: =item *
1.394     bowersj2 12503: X<idput()>
                   12504: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12505: 
                   12506: =item *
1.394     bowersj2 12507: X<rolesinit()>
1.1169    droeschl 12508: B<rolesinit($udom,$username)>: get user privileges.
                   12509: returns user role, first access and timer interval hashes
1.243     albertel 12510: 
                   12511: =item *
1.1171    droeschl 12512: X<privileged()>
                   12513: B<privileged($username,$domain)>: returns a true if user has a
                   12514: privileged and active role (i.e. su or dc), false otherwise.
                   12515: 
                   12516: =item *
1.551     albertel 12517: X<getsection()>
                   12518: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12519: course $cname, return section name/number or '' for "not in course"
                   12520: and '-1' for "no section"
                   12521: 
                   12522: =item *
1.394     bowersj2 12523: X<userenvironment()>
                   12524: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12525: passed in @what from the requested user's environment, returns a hash
                   12526: 
1.858     raeburn  12527: =item * 
                   12528: X<userlog_query()>
1.859     albertel 12529: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12530: activity.log file. %filters defines filters applied when parsing the
                   12531: log file. These can be start or end timestamps, or the type of action
                   12532: - log to look for Login or Logout events, check for Checkin or
                   12533: Checkout, role for role selection. The response is in the form
                   12534: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12535: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12536: 
1.243     albertel 12537: =back
                   12538: 
                   12539: =head2 User Roles
                   12540: 
                   12541: =over 4
                   12542: 
                   12543: =item *
                   12544: 
1.810     raeburn  12545: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12546:  F: full access
                   12547:  U,I,K: authentication modes (cxx only)
                   12548:  '': forbidden
                   12549:  1: user needs to choose course
                   12550:  2: browse allowed
1.766     albertel 12551:  A: passphrase authentication needed
1.243     albertel 12552: 
                   12553: =item *
                   12554: 
1.1172.2.13  raeburn  12555: constructaccess($url,$setpriv) : check for access to construction space URL
                   12556: 
                   12557: See if the owner domain and name in the URL match those in the
                   12558: expected environment.  If so, return three element list
                   12559: ($ownername,$ownerdomain,$ownerhome).
                   12560: 
                   12561: Otherwise return the null string.
                   12562: 
                   12563: If second argument 'setpriv' is true, it assigns the privileges,
                   12564: and returns the same three element list, unless the owner has
                   12565: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12566: in which case the null string is returned.
                   12567: 
                   12568: =item *
                   12569: 
1.243     albertel 12570: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12571: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12572: and course level
                   12573: 
                   12574: =item *
                   12575: 
1.988     raeburn  12576: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12577: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12578: $type is Course (default) or Community.
1.988     raeburn  12579: If $forcedefault evaluates to true, text returned will be default 
                   12580: text for $type. Otherwise, if this is a course, the text returned 
                   12581: will be a custom name for the role (if defined in the course's 
                   12582: environment).  If no custom name is defined the default is returned.
                   12583:    
1.832     raeburn  12584: =item *
                   12585: 
1.1172.2.23  raeburn  12586: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12587: All arguments are optional. Returns a hash of a roles, either for
                   12588: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12589: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12590: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12591: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12592: For each key, value is set to colon-separated start and end times for
                   12593: the role.  If no username and domain are specified, will default to
1.934     raeburn  12594: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12595: of role statuses (active, future or previous), roles 
                   12596: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12597: to restrict the list of roles reported. If no array ref is 
                   12598: provided for types, will default to return only active roles.
1.834     albertel 12599: 
1.1172.2.13  raeburn  12600: =item *
                   12601: 
                   12602: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12603: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12604: 
                   12605: Additional optional arguments are: $type (if role checking is to be restricted
                   12606: to certain user status types -- previous (expired roles), active (currently
                   12607: available roles) or future (roles available in the future), and
                   12608: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12609: have active Domain Coordinator role in course's domain or in additional
                   12610: domains (specified in 'Domains to check for privileged users' in course
                   12611: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12612: 
                   12613: =item *
                   12614: 
                   12615: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12616: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12617: $possdomains and $possroles are optional array refs -- to domains to check and
                   12618: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12619: users' roles.db to check for a dc or su role in any domain. This can be
                   12620: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12621: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12622: this then allows &privileged_by_domain() to be used, which caches the identity
                   12623: of privileged users, eliminating the need for repeated calls to &dump().
                   12624: 
                   12625: =item *
                   12626: 
                   12627: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12628: where the outer hash keys are domains specified in the $possdomains array ref,
                   12629: next inner hash keys are privileged roles specified in the $roles array ref,
                   12630: and the innermost hash contains key = value pairs for username:domain = end:start
                   12631: for active or future "privileged" users with that role in that domain. To avoid
                   12632: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12633: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12634: 
1.243     albertel 12635: =back
                   12636: 
                   12637: =head2 User Modification
                   12638: 
                   12639: =over 4
                   12640: 
                   12641: =item *
                   12642: 
1.957     raeburn  12643: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12644: user for the level given by URL.  Optional start and end dates (leave empty
                   12645: string or zero for "no date")
1.191     harris41 12646: 
                   12647: =item *
                   12648: 
1.243     albertel 12649: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12650: change a users, password, possible return values are: ok,
                   12651: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12652: refused
1.191     harris41 12653: 
                   12654: =item *
                   12655: 
1.243     albertel 12656: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12657: 
                   12658: =item *
                   12659: 
1.1058    raeburn  12660: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12661:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12662: 
                   12663: will update user information (firstname,middlename,lastname,generation,
                   12664: permanentemail), and if forceid is true, student/employee ID also.
                   12665: A user's institutional affiliation(s) can also be updated.
                   12666: User information fields will not be overwritten with empty entries 
                   12667: unless the field is included in the $candelete array reference.
                   12668: This array is included when a single user is modified via "Manage Users",
                   12669: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12670: 
                   12671: =item *
                   12672: 
1.286     matthew  12673: modifystudent
                   12674: 
1.957     raeburn  12675: modify a student's enrollment and identification information.
1.286     matthew  12676: The course id is resolved based on the current users environment.  
                   12677: This means the envoking user must be a course coordinator or otherwise
                   12678: associated with a course.
                   12679: 
1.297     matthew  12680: This call is essentially a wrapper for lonnet::modifyuser and
                   12681: lonnet::modify_student_enrollment
1.286     matthew  12682: 
                   12683: Inputs: 
                   12684: 
                   12685: =over 4
                   12686: 
1.957     raeburn  12687: =item B<$udom> Student's loncapa domain
1.286     matthew  12688: 
1.957     raeburn  12689: =item B<$uname> Student's loncapa login name
1.286     matthew  12690: 
1.964     bisitz   12691: =item B<$uid> Student/Employee ID
1.286     matthew  12692: 
1.957     raeburn  12693: =item B<$umode> Student's authentication mode
1.286     matthew  12694: 
1.957     raeburn  12695: =item B<$upass> Student's password
1.286     matthew  12696: 
1.957     raeburn  12697: =item B<$first> Student's first name
1.286     matthew  12698: 
1.957     raeburn  12699: =item B<$middle> Student's middle name
1.286     matthew  12700: 
1.957     raeburn  12701: =item B<$last> Student's last name
1.286     matthew  12702: 
1.957     raeburn  12703: =item B<$gene> Student's generation
1.286     matthew  12704: 
1.957     raeburn  12705: =item B<$usec> Student's section in course
1.286     matthew  12706: 
                   12707: =item B<$end> Unix time of the roles expiration
                   12708: 
                   12709: =item B<$start> Unix time of the roles start date
                   12710: 
                   12711: =item B<$forceid> If defined, allow $uid to be changed
                   12712: 
                   12713: =item B<$desiredhome> server to use as home server for student
                   12714: 
1.957     raeburn  12715: =item B<$email> Student's permanent e-mail address
                   12716: 
                   12717: =item B<$type> Type of enrollment (auto or manual)
                   12718: 
1.963     raeburn  12719: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12720: 
                   12721: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12722: 
1.963     raeburn  12723: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12724: 
1.963     raeburn  12725: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12726: 
1.1172.2.19  raeburn  12727: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12728: 
                   12729: =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  12730: 
1.286     matthew  12731: =back
1.297     matthew  12732: 
                   12733: =item *
                   12734: 
                   12735: modify_student_enrollment
                   12736: 
                   12737: Change a students enrollment status in a class.  The environment variable
                   12738: 'role.request.course' must be defined for this function to proceed.
                   12739: 
                   12740: Inputs:
                   12741: 
                   12742: =over 4
                   12743: 
                   12744: =item $udom, students domain
                   12745: 
                   12746: =item $uname, students name
                   12747: 
                   12748: =item $uid, students user id
                   12749: 
                   12750: =item $first, students first name
                   12751: 
                   12752: =item $middle
                   12753: 
                   12754: =item $last
                   12755: 
                   12756: =item $gene
                   12757: 
                   12758: =item $usec
                   12759: 
                   12760: =item $end
                   12761: 
                   12762: =item $start
                   12763: 
1.957     raeburn  12764: =item $type
                   12765: 
                   12766: =item $locktype
                   12767: 
                   12768: =item $cid
                   12769: 
                   12770: =item $selfenroll
                   12771: 
                   12772: =item $context
                   12773: 
1.1172.2.19  raeburn  12774: =item $credits, number of credits student will earn from this class
                   12775: 
1.297     matthew  12776: =back
                   12777: 
1.191     harris41 12778: 
                   12779: =item *
                   12780: 
1.243     albertel 12781: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12782: custom role; give a custom role to a user for the level given by URL.  Specify
                   12783: name and domain of role author, and role name
1.191     harris41 12784: 
                   12785: =item *
                   12786: 
1.243     albertel 12787: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12788: 
                   12789: =item *
                   12790: 
1.243     albertel 12791: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12792: 
                   12793: =back
                   12794: 
                   12795: =head2 Course Infomation
                   12796: 
                   12797: =over 4
1.191     harris41 12798: 
                   12799: =item *
                   12800: 
1.1118    foxr     12801: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12802: specified course id, including all environment settings for the
                   12803: course, the description of the course will be in the hash under the
                   12804: key 'description'
1.191     harris41 12805: 
1.1118    foxr     12806: $options is an optional parameter that if supplied is a hash reference that controls
                   12807: what how this function works.  It has the following key/values:
                   12808: 
                   12809: =over 4
                   12810: 
                   12811: =item freshen_cache
                   12812: 
                   12813: If defined, and the environment cache for the course is valid, it is 
                   12814: returned in the returned hash.
                   12815: 
                   12816: =item one_time
                   12817: 
                   12818: If defined, the last cache time is set to _now_
                   12819: 
                   12820: =item user
                   12821: 
                   12822: If defined, the supplied username is used instead of the current user.
                   12823: 
                   12824: 
                   12825: =back
                   12826: 
1.191     harris41 12827: =item *
                   12828: 
1.624     albertel 12829: resdata($name,$domain,$type,@which) : request for current parameter
                   12830: setting for a specific $type, where $type is either 'course' or 'user',
                   12831: @what should be a list of parameters to ask about. This routine caches
                   12832: answers for 5 minutes.
1.243     albertel 12833: 
1.877     foxr     12834: =item *
                   12835: 
                   12836: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12837: data base, returning a hash that is keyed by the resource name and has
                   12838: values that are the resource value.  I believe that the timestamps and
                   12839: versions are also returned.
                   12840: 
1.243     albertel 12841: =back
                   12842: 
                   12843: =head2 Course Modification
                   12844: 
                   12845: =over 4
1.191     harris41 12846: 
                   12847: =item *
                   12848: 
1.243     albertel 12849: writecoursepref($courseid,%prefs) : write preferences (environment
                   12850: database) for a course
1.191     harris41 12851: 
                   12852: =item *
                   12853: 
1.1011    raeburn  12854: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12855: 
                   12856: =item *
                   12857: 
1.1038    raeburn  12858: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12859: 
1.1167    droeschl 12860: =item *
                   12861: 
                   12862: is_course($courseid), is_course($cdom, $cnum)
                   12863: 
                   12864: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12865: two component version $cdom, $cnum. It checks if the specified course exists.
                   12866: 
                   12867: Returns:
                   12868:     undef if the course doesn't exist, otherwise
                   12869:     in scalar context the combined courseid.
                   12870:     in list context the two components of the course identifier, domain and 
                   12871:     courseid.    
                   12872: 
1.243     albertel 12873: =back
                   12874: 
                   12875: =head2 Resource Subroutines
                   12876: 
                   12877: =over 4
1.191     harris41 12878: 
                   12879: =item *
                   12880: 
1.243     albertel 12881: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12882: 
                   12883: =item *
                   12884: 
1.243     albertel 12885: repcopy($filename) : subscribes to the requested file, and attempts to
                   12886: replicate from the owning library server, Might return
1.607     raeburn  12887: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12888: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12889: resource. Expects the local filesystem pathname
                   12890: (/home/httpd/html/res/....)
                   12891: 
                   12892: =back
                   12893: 
                   12894: =head2 Resource Information
                   12895: 
                   12896: =over 4
1.191     harris41 12897: 
                   12898: =item *
                   12899: 
1.1172.2.28  raeburn  12900: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   12901: and returns the value of a variety of different possible values,
                   12902: $varname should be a request string, and the other parameters can be
                   12903: used to specify who and what one is asking about. Ordinarily, $cid 
                   12904: does not need to be specified, as it is retrived from 
                   12905: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   12906: within lonuserstate::loadmap() when initializing a course, before
                   12907: $env{'request.course.id'} has been set, so it needs to be provided
                   12908: in that one case.
1.243     albertel 12909: 
                   12910: Possible values for $varname are environment.lastname (or other item
                   12911: from the envirnment hash), user.name (or someother aspect about the
                   12912: user), resource.0.maxtries (or some other part and parameter of a
                   12913: resource)
1.204     albertel 12914: 
                   12915: =item *
                   12916: 
1.243     albertel 12917: directcondval($number) : get current value of a condition; reads from a state
                   12918: string
1.204     albertel 12919: 
                   12920: =item *
                   12921: 
1.243     albertel 12922: condval($condidx) : value of condition index based on state
1.204     albertel 12923: 
                   12924: =item *
                   12925: 
1.243     albertel 12926: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12927: resource's metadata, $what should be either a specific key, or either
                   12928: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12929: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12930: 
                   12931: this function automatically caches all requests
1.191     harris41 12932: 
                   12933: =item *
                   12934: 
1.243     albertel 12935: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12936: network of library servers; returns file handle of where SQL and regex results
                   12937: will be stored for query
1.191     harris41 12938: 
                   12939: =item *
                   12940: 
1.243     albertel 12941: symbread($filename) : return symbolic list entry (filename argument optional);
                   12942: returns the data handle
1.191     harris41 12943: 
                   12944: =item *
                   12945: 
1.1172.2.17  raeburn  12946: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12947: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12948: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12949: on failure, user must be in a course, as it assumes the existence of
                   12950: the course initial hash, and uses $env('request.course.id'}.  The third
                   12951: arg is an optional reference to a scalar.  If this arg is passed in the
                   12952: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12953: encrypted; otherwise it will be null.
1.243     albertel 12954: 
1.191     harris41 12955: =item *
                   12956: 
1.243     albertel 12957: symbclean($symb) : removes versions numbers from a symb, returns the
                   12958: cleaned symb
1.191     harris41 12959: 
                   12960: =item *
                   12961: 
1.243     albertel 12962: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12963: course map, user must be in a course for it to work.
1.191     harris41 12964: 
                   12965: =item *
                   12966: 
1.243     albertel 12967: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12968: 
                   12969: =item *
                   12970: 
1.243     albertel 12971: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12972: a random seed, all arguments are optional, if they aren't sent it uses the
                   12973: environment to derive them. Note: if symb isn't sent and it can't get one
                   12974: from &symbread it will use the current time as its return value
1.191     harris41 12975: 
                   12976: =item *
                   12977: 
1.243     albertel 12978: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12979: unfakeable, receipt
1.191     harris41 12980: 
                   12981: =item *
                   12982: 
1.620     albertel 12983: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12984: 
                   12985: =item *
                   12986: 
1.243     albertel 12987: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12988: 
                   12989: =item *
                   12990: 
1.243     albertel 12991: 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 12992: 
                   12993: =item *
                   12994: 
1.243     albertel 12995: 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 12996: 
                   12997: =item *
                   12998: 
1.243     albertel 12999: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13000: 
                   13001: =item *
                   13002: 
1.243     albertel 13003: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13004: forcing spreadsheet to reevaluate the resource scores next time.
                   13005: 
1.1172.2.13  raeburn  13006: =item *
                   13007: 
                   13008: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13009: when viewing in course context.
                   13010: 
                   13011:  input: six args -- filename (decluttered), course number, course domain,
                   13012:                     url, symb (if registered) and group (if this is a
                   13013:                     group item -- e.g., bulletin board, group page etc.).
                   13014: 
                   13015:  output: array of five scalars --
                   13016:          $cfile -- url for file editing if editable on current server
                   13017:          $home -- homeserver of resource (i.e., for author if published,
                   13018:                                           or course if uploaded.).
                   13019:          $switchserver --  1 if server switch will be needed.
                   13020:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13021:          $forceview -- 1 if icon/link should be to go to view mode
                   13022: 
                   13023: =item *
                   13024: 
                   13025: is_course_upload($file,$cnum,$cdom)
                   13026: 
                   13027: Used in course context to determine if current file was uploaded to
                   13028: the course (i.e., would be found in /userfiles/docs on the course's
                   13029: homeserver.
                   13030: 
                   13031:   input: 3 args -- filename (decluttered), course number and course domain.
                   13032:   output: boolean -- 1 if file was uploaded.
                   13033: 
1.243     albertel 13034: =back
                   13035: 
                   13036: =head2 Storing/Retreiving Data
                   13037: 
                   13038: =over 4
1.191     harris41 13039: 
                   13040: =item *
                   13041: 
1.243     albertel 13042: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13043: for this url; hashref needs to be given and should be a \%hashname; the
                   13044: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13045: be derived from the env
1.191     harris41 13046: 
                   13047: =item *
                   13048: 
1.243     albertel 13049: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13050: uses critical subroutine
1.191     harris41 13051: 
                   13052: =item *
                   13053: 
1.243     albertel 13054: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13055: all args are optional
1.191     harris41 13056: 
                   13057: =item *
                   13058: 
1.717     albertel 13059: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13060: dumps the complete (or key matching regexp) namespace into a hash
                   13061: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13062: normally &store()ed into
                   13063: 
                   13064: $range should be either an integer '100' (give me the first 100
                   13065:                                            matching records)
                   13066:               or be  two integers sperated by a - with no spaces
                   13067:                  '30-50' (give me the 30th through the 50th matching
                   13068:                           records)
                   13069: 
                   13070: 
                   13071: =item *
                   13072: 
                   13073: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13074: replaces a &store() version of data with a replacement set of data
                   13075: for a particular resource in a namespace passed in the $storehash hash 
                   13076: reference
                   13077: 
                   13078: =item *
                   13079: 
1.243     albertel 13080: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13081: works very similar to store/cstore, but all data is stored in a
                   13082: temporary location and can be reset using tmpreset, $storehash should
                   13083: be a hash reference, returns nothing on success
1.191     harris41 13084: 
                   13085: =item *
                   13086: 
1.243     albertel 13087: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13088: similar to restore, but all data is stored in a temporary location and
                   13089: can be reset using tmpreset. Returns a hash of values on success,
                   13090: error string otherwise.
1.191     harris41 13091: 
                   13092: =item *
                   13093: 
1.243     albertel 13094: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13095: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13096: 
                   13097: =item *
                   13098: 
1.243     albertel 13099: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13100: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13101: 
                   13102: =item *
                   13103: 
1.243     albertel 13104: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13105: namesp ($udom and $uname are optional)
1.191     harris41 13106: 
                   13107: =item *
                   13108: 
1.702     albertel 13109: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13110: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13111: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13112: 
1.702     albertel 13113: $range should be either an integer '100' (give me the first 100
                   13114:                                            matching records)
                   13115:               or be  two integers sperated by a - with no spaces
                   13116:                  '30-50' (give me the 30th through the 50th matching
                   13117:                           records)
1.449     matthew  13118: =item *
                   13119: 
                   13120: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13121: $store can be a scalar, an array reference, or if the amount to be 
                   13122: incremented is > 1, a hash reference.
                   13123: 
                   13124: ($udom and $uname are optional)
1.191     harris41 13125: 
                   13126: =item *
                   13127: 
1.243     albertel 13128: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13129: ($udom and $uname are optional)
1.191     harris41 13130: 
                   13131: =item *
                   13132: 
1.243     albertel 13133: cput($namespace,$storehash,$udom,$uname) : critical put
                   13134: ($udom and $uname are optional)
1.191     harris41 13135: 
                   13136: =item *
                   13137: 
1.748     albertel 13138: newput($namespace,$storehash,$udom,$uname) :
                   13139: 
                   13140: Attempts to store the items in the $storehash, but only if they don't
                   13141: currently exist, if this succeeds you can be certain that you have 
                   13142: successfully created a new key value pair in the $namespace db.
                   13143: 
                   13144: 
                   13145: Args:
                   13146:  $namespace: name of database to store values to
                   13147:  $storehash: hashref to store to the db
                   13148:  $udom: (optional) domain of user containing the db
                   13149:  $uname: (optional) name of user caontaining the db
                   13150: 
                   13151: Returns:
                   13152:  'ok' -> succeeded in storing all keys of $storehash
                   13153:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13154:                         least <key> already existed in the db (other
                   13155:                         requested keys may also already exist)
1.967     bisitz   13156:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13157:  'con_lost' -> unable to contact request server
                   13158:  'refused' -> action was not allowed by remote machine
                   13159: 
                   13160: 
                   13161: =item *
                   13162: 
1.243     albertel 13163: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13164: reference filled in from namesp (encrypts the return communication)
                   13165: ($udom and $uname are optional)
1.191     harris41 13166: 
                   13167: =item *
                   13168: 
1.243     albertel 13169: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13170: critical subroutine
                   13171: 
1.806     raeburn  13172: =item *
                   13173: 
1.860     raeburn  13174: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13175: array reference filled in from namespace found in domain level on either
                   13176: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13177: 
                   13178: =item *
                   13179: 
1.860     raeburn  13180: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13181: domain level either on specified domain server ($uhome) or primary domain 
                   13182: server ($udom and $uhome are optional)
1.806     raeburn  13183: 
1.943     raeburn  13184: =item * 
                   13185: 
                   13186: get_domain_defaults($target_domain) : returns hash with defaults for
                   13187: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13188: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13189: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13190: Values are retrieved from cache (if current), or from domain's configuration.db
                   13191: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13192: or lonTabs/domain.tab. 
                   13193: 
                   13194: %domdefaults = &get_auth_defaults($target_domain);
                   13195: 
1.243     albertel 13196: =back
                   13197: 
                   13198: =head2 Network Status Functions
                   13199: 
                   13200: =over 4
1.191     harris41 13201: 
                   13202: =item *
                   13203: 
1.1137    raeburn  13204: dirlist() : return directory list based on URI (first arg).
                   13205: 
                   13206: Inputs: 1 required, 5 optional.
                   13207: 
                   13208: =over
                   13209: 
                   13210: =item 
                   13211: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13212: 
                   13213: =item
                   13214: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13215: 
                   13216: =item
                   13217: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13218: 
                   13219: =item
                   13220: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13221: 
                   13222: =item
                   13223: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13224: 
                   13225: =item 
                   13226: $alternateRoot - path to prepend in place of path from $uri.
                   13227: 
                   13228: =back
                   13229: 
                   13230: Returns: Array of up to two items.
                   13231: 
                   13232: =over
                   13233: 
                   13234: a reference to an array of files/subdirectories
                   13235: 
                   13236: =over
                   13237: 
                   13238: Each element in the array of files/subdirectories is a & separated list of
                   13239: item name and the result of running stat on the item.  If dirlist was requested
                   13240: for a file instead of a directory, the item name will be ''. For a directory 
                   13241: listing, if the item is a metadata file, the element will end &N&M 
                   13242: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13243: default copyright set (1).  
                   13244: 
                   13245: =back
                   13246: 
                   13247: a scalar containing error condition (if encountered).
                   13248: 
                   13249: =over
                   13250: 
                   13251: =item 
                   13252: no_host (no homeserver identified for $username:$domain).
                   13253: 
                   13254: =item 
                   13255: no_such_host (server contacted for listing not identified as valid host).
                   13256: 
                   13257: =item 
                   13258: con_lost (connection to remote server failed).
                   13259: 
                   13260: =item 
                   13261: refused (invalid $username:$domain received on lond side).
                   13262: 
                   13263: =item 
                   13264: no_such_dir (directory at specified path on lond side does not exist). 
                   13265: 
                   13266: =item 
                   13267: empty (directory at specified path on lond side is empty).
                   13268: 
                   13269: =over
                   13270: 
                   13271: This is currently not encountered because the &ls3, &ls2, 
                   13272: &ls (_handler) routines on the lond side do not filter out
                   13273: . and .. from a directory listing. 
                   13274: 
                   13275: =back
                   13276: 
                   13277: =back
                   13278: 
                   13279: =back
1.191     harris41 13280: 
                   13281: =item *
                   13282: 
1.243     albertel 13283: spareserver() : find server with least workload from spare.tab
                   13284: 
1.986     foxr     13285: 
                   13286: =item *
                   13287: 
                   13288: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13289: if there is no corresponding loncapa host.
                   13290: 
1.243     albertel 13291: =back
                   13292: 
1.986     foxr     13293: 
1.243     albertel 13294: =head2 Apache Request
                   13295: 
                   13296: =over 4
1.191     harris41 13297: 
                   13298: =item *
                   13299: 
1.243     albertel 13300: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13301: localhost, posts hash
                   13302: 
                   13303: =back
                   13304: 
                   13305: =head2 Data to String to Data
                   13306: 
                   13307: =over 4
1.191     harris41 13308: 
                   13309: =item *
                   13310: 
1.243     albertel 13311: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13312: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13313: 
                   13314: =item *
                   13315: 
1.243     albertel 13316: hashref2str($hashref) : convert a hashref into a string complete with
                   13317: escaping and '=' and '&' separators, supports elements that are
                   13318: arrayrefs and hashrefs
1.191     harris41 13319: 
                   13320: =item *
                   13321: 
1.243     albertel 13322: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13323: with escaping and '&' separators, supports elements that are arrayrefs
                   13324: and hashrefs
1.191     harris41 13325: 
                   13326: =item *
                   13327: 
1.243     albertel 13328: str2hash($string) : convert string to hash using unescaping and
                   13329: splitting on '=' and '&', supports elements that are arrayrefs and
                   13330: hashrefs
1.191     harris41 13331: 
                   13332: =item *
                   13333: 
1.243     albertel 13334: str2array($string) : convert string to hash using unescaping and
                   13335: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13336: 
                   13337: =back
                   13338: 
                   13339: =head2 Logging Routines
                   13340: 
                   13341: 
                   13342: These routines allow one to make log messages in the lonnet.log and
                   13343: lonnet.perm logfiles.
1.191     harris41 13344: 
1.1119    foxr     13345: =over 4
                   13346: 
1.191     harris41 13347: =item *
                   13348: 
1.243     albertel 13349: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13350: 
                   13351: =item *
                   13352: 
1.243     albertel 13353: logthis() : append message to the normal lonnet.log file, it gets
                   13354: preiodically rolled over and deleted.
1.191     harris41 13355: 
                   13356: =item *
                   13357: 
1.243     albertel 13358: logperm() : append a permanent message to lonnet.perm.log, this log
                   13359: file never gets deleted by any automated portion of the system, only
                   13360: messages of critical importance should go in here.
                   13361: 
1.1119    foxr     13362: 
1.243     albertel 13363: =back
                   13364: 
                   13365: =head2 General File Helper Routines
                   13366: 
                   13367: =over 4
1.191     harris41 13368: 
                   13369: =item *
                   13370: 
1.481     raeburn  13371: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13372: (a) files in /uploaded
                   13373:   (i) If a local copy of the file exists - 
                   13374:       compares modification date of local copy with last-modified date for 
                   13375:       definitive version stored on home server for course. If local copy is 
                   13376:       stale, requests a new version from the home server and stores it. 
                   13377:       If the original has been removed from the home server, then local copy 
                   13378:       is unlinked.
                   13379:   (ii) If local copy does not exist -
                   13380:       requests the file from the home server and stores it. 
                   13381:   
                   13382:   If $caller is 'uploadrep':  
                   13383:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13384:     for request for files originally uploaded via DOCS. 
                   13385:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13386:   
                   13387:   Otherwise:
                   13388:      This indicates a call from the content generation phase of the request.
                   13389:      -  returns the entire contents of the file or -1.
                   13390:      
                   13391: (b) files in /res
                   13392:    - returns the entire contents of a file or -1; 
                   13393:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13394: 
1.712     albertel 13395: 
                   13396: =item *
                   13397: 
                   13398: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13399:                   reference
                   13400: 
                   13401: returns either a stat() list of data about the file or an empty list
                   13402: if the file doesn't exist or couldn't find out about it (connection
                   13403: problems or user unknown)
                   13404: 
1.191     harris41 13405: =item *
                   13406: 
1.243     albertel 13407: filelocation($dir,$file) : returns file system location of a file
                   13408: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13409: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13410: and a file of ../bob will become /a/bob)
1.191     harris41 13411: 
                   13412: =item *
                   13413: 
                   13414: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13415: filelocation except for hrefs
                   13416: 
                   13417: =item *
                   13418: 
                   13419: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13420: 
1.243     albertel 13421: =back
                   13422: 
1.608     albertel 13423: =head2 Usererfile file routines (/uploaded*)
                   13424: 
                   13425: =over 4
                   13426: 
                   13427: =item *
                   13428: 
                   13429: userfileupload(): main rotine for putting a file in a user or course's
                   13430:                   filespace, arguments are,
                   13431: 
1.620     albertel 13432:  formname - required - this is the name of the element in $env where the
1.608     albertel 13433:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13434:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13435:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13436:  context - if coursedoc, store the file in the course of the active role
                   13437:              of the current user; 
                   13438:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13439:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13440:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13441:          if undefined, it will be placed in "unknown"
                   13442: 
                   13443:  (This routine calls clean_filename() to remove any dangerous
                   13444:  characters from the filename, and then calls finuserfileupload() to
                   13445:  complete the transaction)
                   13446: 
                   13447:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13448:  and /adm/notfound.html if unsuccessful
                   13449: 
                   13450: =item *
                   13451: 
                   13452: clean_filename(): routine for cleaing a filename up for storage in
                   13453:                  userfile space, argument is:
                   13454: 
                   13455:  filename - proposed filename
                   13456: 
                   13457: returns: the new clean filename
                   13458: 
                   13459: =item *
                   13460: 
1.1090    raeburn  13461: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13462: userspace, probably shouldn't be called directly
                   13463: 
                   13464:   docuname: username or courseid of destination for the file
                   13465:   docudom: domain of user/course of destination for the file
                   13466:   formname: same as for userfileupload()
1.1090    raeburn  13467:   fname: filename (including subdirectories) for the file
                   13468:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13469:   allfiles: reference to hash used to store objects found by parser
                   13470:   codebase: reference to hash used for codebases of java objects found by parser
                   13471:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13472:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13473:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13474:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13475:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13476:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13477:   mimetype: reference to scalar to accommodate mime type determined
                   13478:             from File::MMagic if $parser = parse.
1.608     albertel 13479: 
                   13480:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13481:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13482:  was 'overwrite').
                   13483:  
1.608     albertel 13484: 
                   13485: =item *
                   13486: 
                   13487: renameuserfile(): renames an existing userfile to a new name
                   13488: 
                   13489:   Args:
                   13490:    docuname: username or courseid of destination for the file
                   13491:    docudom: domain of user/course of destination for the file
                   13492:    old: current file name (including any subdirs under userfiles)
                   13493:    new: desired file name (including any subdirs under userfiles)
                   13494: 
                   13495: =item *
                   13496: 
                   13497: mkdiruserfile(): creates a directory is a userfiles dir
                   13498: 
                   13499:   Args:
                   13500:    docuname: username or courseid of destination for the file
                   13501:    docudom: domain of user/course of destination for the file
                   13502:    dir: dir to create (including any subdirs under userfiles)
                   13503: 
                   13504: =item *
                   13505: 
                   13506: removeuserfile(): removes a file that exists in userfiles
                   13507: 
                   13508:   Args:
                   13509:    docuname: username or courseid of destination for the file
                   13510:    docudom: domain of user/course of destination for the file
                   13511:    fname: filname to delete (including any subdirs under userfiles)
                   13512: 
                   13513: =item *
                   13514: 
                   13515: removeuploadedurl(): convience function for removeuserfile()
                   13516: 
                   13517:   Args:
                   13518:    url:  a full /uploaded/... url to delete
                   13519: 
1.747     albertel 13520: =item * 
                   13521: 
                   13522: get_portfile_permissions():
                   13523:   Args:
                   13524:     domain: domain of user or course contain the portfolio files
                   13525:     user: name of user or num of course contain the portfolio files
                   13526:   Returns:
                   13527:     hashref of a dump of the proper file_permissions.db
                   13528:    
                   13529: 
                   13530: =item * 
                   13531: 
                   13532: get_access_controls():
                   13533: 
                   13534: Args:
                   13535:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13536:   group: (optional) the group you want the files associated with
                   13537:   file: (optional) the file you want access info on
                   13538: 
                   13539: Returns:
1.749     raeburn  13540:     a hash (keys are file names) of hashes containing
                   13541:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13542:         values are XML containing access control settings (see below) 
1.747     albertel 13543: 
                   13544: Internal notes:
                   13545: 
1.749     raeburn  13546:  access controls are stored in file_permissions.db as key=value pairs.
                   13547:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13548:         where scope -> public,guest,course,group,domains or users.
                   13549:               end -> UNIX time for end of access (0 -> no end date)
                   13550:               start -> UNIX time for start of access
                   13551: 
                   13552:     value -> XML description of access control
                   13553:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13554:             <start></start>
                   13555:             <end></end>
                   13556: 
                   13557:             <password></password>  for scope type = guest
                   13558: 
                   13559:             <domain></domain>     for scope type = course or group
                   13560:             <number></number>
                   13561:             <roles id="">
                   13562:              <role></role>
                   13563:              <access></access>
                   13564:              <section></section>
                   13565:              <group></group>
                   13566:             </roles>
                   13567: 
                   13568:             <dom></dom>         for scope type = domains
                   13569: 
                   13570:             <users>             for scope type = users
                   13571:              <user>
                   13572:               <uname></uname>
                   13573:               <udom></udom>
                   13574:              </user>
                   13575:             </users>
                   13576:            </scope> 
                   13577:               
                   13578:  Access data is also aggregated for each file in an additional key=value pair:
                   13579:  key -> path to file/file_name\0accesscontrol 
                   13580:  value -> reference to hash
                   13581:           hash contains key = value pairs
                   13582:           where key = uniqueID:scope_end_start
                   13583:                 value = UNIX time record was last updated
                   13584: 
                   13585:           Used to improve speed of look-ups of access controls for each file.  
                   13586:  
                   13587:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13588: 
1.1172.2.13  raeburn  13589: =item *
                   13590: 
1.749     raeburn  13591: modify_access_controls():
                   13592: 
                   13593: Modifies access controls for a portfolio file
                   13594: Args
                   13595: 1. file name
                   13596: 2. reference to hash of required changes,
                   13597: 3. domain
                   13598: 4. username
                   13599:   where domain,username are the domain of the portfolio owner 
                   13600:   (either a user or a course) 
                   13601: 
                   13602: Returns:
                   13603: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13604: 2. result of deletions ('ok' or 'error', with error message).
                   13605: 3. reference to hash of any new or updated access controls.
                   13606: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13607:    key = integer (inbound ID)
1.1172.2.13  raeburn  13608:    value = uniqueID
                   13609: 
                   13610: =item *
                   13611: 
                   13612: get_timebased_id():
                   13613: 
                   13614: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13615: course via the Course Editor (e.g., folders, composite pages,
                   13616: group bulletin boards).
                   13617: 
                   13618: Args: (first three required; six others optional)
                   13619: 
                   13620: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13621:    docssequence, or name of group
                   13622: 
                   13623: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13624:    e.g., num, boardids
                   13625: 
                   13626: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13627:    file will be named nohist_namespace.db
                   13628: 
                   13629: 4. cdom: domain of course; default is current course domain from %env
                   13630: 
                   13631: 5. cnum: course number; default is current course number from %env
                   13632: 
                   13633: 6. idtype: set to concat if an additional digit is to be appended to the
                   13634:    unix timestamp to form the suffix, if the plain timestamp is already
                   13635:    in use.  Default is to not do this, but simply increment the unix
                   13636:    timestamp by 1 until a unique key is obtained.
                   13637: 
                   13638: 7. who: holder of locking key; defaults to user:domain for user.
                   13639: 
                   13640: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13641:    retrying); default is 3.
                   13642: 
                   13643: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13644: 
                   13645: Returns:
                   13646: 
                   13647: 1. suffix obtained (numeric)
                   13648: 
                   13649: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13650: 
                   13651: 3. error: contains (localized) error message if an error occurred.
                   13652: 
1.747     albertel 13653: 
1.608     albertel 13654: =back
                   13655: 
1.243     albertel 13656: =head2 HTTP Helper Routines
                   13657: 
                   13658: =over 4
                   13659: 
1.191     harris41 13660: =item *
                   13661: 
                   13662: escape() : unpack non-word characters into CGI-compatible hex codes
                   13663: 
                   13664: =item *
                   13665: 
                   13666: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13667: 
1.243     albertel 13668: =back
                   13669: 
                   13670: =head1 PRIVATE SUBROUTINES
                   13671: 
                   13672: =head2 Underlying communication routines (Shouldn't call)
                   13673: 
                   13674: =over 4
                   13675: 
                   13676: =item *
                   13677: 
                   13678: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13679: 
                   13680: =item *
                   13681: 
                   13682: reply() : uses subreply to send a message to remote machine, logs all failures
                   13683: 
                   13684: =item *
                   13685: 
                   13686: critical() : passes a critical message to another server; if cannot
                   13687: get through then place message in connection buffer directory and
                   13688: returns con_delayed, if incapable of saving message, returns
                   13689: con_failed
                   13690: 
                   13691: =item *
                   13692: 
                   13693: reconlonc() : tries to reconnect lonc client processes.
                   13694: 
                   13695: =back
                   13696: 
                   13697: =head2 Resource Access Logging
                   13698: 
                   13699: =over 4
                   13700: 
                   13701: =item *
                   13702: 
                   13703: flushcourselogs() : flush (save) buffer logs and access logs
                   13704: 
                   13705: =item *
                   13706: 
                   13707: courselog($what) : save message for course in hash
                   13708: 
                   13709: =item *
                   13710: 
                   13711: courseacclog($what) : save message for course using &courselog().  Perform
                   13712: special processing for specific resource types (problems, exams, quizzes, etc).
                   13713: 
1.191     harris41 13714: =item *
                   13715: 
                   13716: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13717: as a PerlChildExitHandler
1.243     albertel 13718: 
                   13719: =back
                   13720: 
                   13721: =head2 Other
                   13722: 
                   13723: =over 4
                   13724: 
                   13725: =item *
                   13726: 
                   13727: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13728: 
                   13729: =back
                   13730: 
                   13731: =cut
1.877     foxr     13732: 

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