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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.34! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.33 2013/09/01 23:24:05 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:                 }
1.1172.2.31  raeburn  2849:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2850:                 if ($env{'form.forceedit'}) {
                   2851:                     $forceview = 1;
                   2852:                 } else {
                   2853:                     $forceedit = 1;
                   2854:                 }
                   2855:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2856:             }
                   2857:         }
                   2858:         if ($uploaded || $incourse) {
                   2859:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2860:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2861:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2862:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2863:             # Check that the user has permission to edit this resource
                   2864:             my $setpriv = 1;
                   2865:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2866:             if (defined($cfudom)) {
                   2867:                 $home=&homeserver($cfuname,$cfudom);
                   2868:                 $cfile=$file;
                   2869:             }
                   2870:         }
                   2871:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2872:             (($home ne '') && ($home ne 'no_host'))) {
                   2873:             my @ids=&current_machine_ids();
                   2874:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2875:                 $switchserver=1;
                   2876:             }
                   2877:         }
                   2878:     }
                   2879:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2880: }
                   2881: 
                   2882: sub is_course_upload {
                   2883:     my ($file,$cnum,$cdom) = @_;
                   2884:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2885:     $uploadpath =~ s{^\/}{};
                   2886:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2887:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2888:         return 1;
                   2889:     }
                   2890:     return;
                   2891: }
                   2892: 
                   2893: sub in_course {
                   2894:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2895:     if ($hideprivileged) {
                   2896:         my $skipuser;
1.1172.2.23  raeburn  2897:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2898:         my @possdoms = ($cdom);
                   2899:         if ($coursehash{'checkforpriv'}) {
                   2900:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2901:         }
                   2902:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2903:             $skipuser = 1;
                   2904:             if ($coursehash{'nothideprivileged'}) {
                   2905:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2906:                     my $user;
                   2907:                     if ($item =~ /:/) {
                   2908:                         $user = $item;
                   2909:                     } else {
                   2910:                         $user = join(':',split(/[\@]/,$item));
                   2911:                     }
                   2912:                     if ($user eq $uname.':'.$udom) {
                   2913:                         undef($skipuser);
                   2914:                         last;
                   2915:                     }
                   2916:                 }
                   2917:             }
                   2918:             if ($skipuser) {
                   2919:                 return 0;
                   2920:             }
                   2921:         }
                   2922:     }
                   2923:     $type ||= 'any';
                   2924:     if (!defined($cdom) || !defined($cnum)) {
                   2925:         my $cid  = $env{'request.course.id'};
                   2926:         $cdom = $env{'course.'.$cid.'.domain'};
                   2927:         $cnum = $env{'course.'.$cid.'.num'};
                   2928:     }
                   2929:     my $typesref;
                   2930:     if (($type eq 'any') || ($type eq 'all')) {
                   2931:         $typesref = ['active','previous','future'];
                   2932:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2933:         $typesref = [$type];
                   2934:     }
                   2935:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2936:                               $typesref,undef,[$cdom]);
                   2937:     my ($tmp) = keys(%roles);
                   2938:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2939:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2940:     if (@course_roles > 0) {
                   2941:         return 1;
                   2942:     }
                   2943:     return 0;
                   2944: }
                   2945: 
1.478     albertel 2946: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2947: # input: action, courseID, current domain, intended
1.637     raeburn  2948: #        path to file, source of file, instruction to parse file for objects,
                   2949: #        ref to hash for embedded objects,
                   2950: #        ref to hash for codebase of java objects.
1.1095    raeburn  2951: #        reference to scalar to accommodate mime type determined
                   2952: #          from File::MMagic if $parser = parse.
1.637     raeburn  2953: #
1.485     raeburn  2954: # output: url to file (if action was uploaddoc), 
                   2955: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2956: #
1.478     albertel 2957: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2958: # course.
1.477     raeburn  2959: #
1.478     albertel 2960: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2961: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2962: #          course's home server.
1.477     raeburn  2963: #
1.478     albertel 2964: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2965: #          be copied from $source (current location) to 
                   2966: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2967: #         and will then be copied to
                   2968: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2969: #         course's home server.
1.485     raeburn  2970: #
1.481     raeburn  2971: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2972: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2973: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2974: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2975: #         in course's home server.
1.637     raeburn  2976: #
1.477     raeburn  2977: 
                   2978: sub process_coursefile {
1.1095    raeburn  2979:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2980:         $mimetype)=@_;
1.477     raeburn  2981:     my $fetchresult;
1.638     albertel 2982:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2983:     if ($action eq 'propagate') {
1.638     albertel 2984:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2985: 			     $home);
1.481     raeburn  2986:     } else {
1.477     raeburn  2987:         my $fpath = '';
                   2988:         my $fname = $file;
1.478     albertel 2989:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2990:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2991:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2992:         if ($action eq 'copy') {
                   2993:             if ($source eq '') {
                   2994:                 $fetchresult = 'no source file';
                   2995:                 return $fetchresult;
                   2996:             } else {
                   2997:                 my $destination = $filepath.'/'.$fname;
                   2998:                 rename($source,$destination);
                   2999:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3000:                                  $home);
1.481     raeburn  3001:             }
                   3002:         } elsif ($action eq 'uploaddoc') {
                   3003:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3004:             print $fh $env{'form.'.$source};
1.481     raeburn  3005:             close($fh);
1.637     raeburn  3006:             if ($parser eq 'parse') {
1.1024    raeburn  3007:                 my $mm = new File::MMagic;
1.1095    raeburn  3008:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3009:                 if ($type eq 'text/html') {
1.1024    raeburn  3010:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3011:                     unless ($parse_result eq 'ok') {
                   3012:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3013:                     }
1.637     raeburn  3014:                 }
1.1095    raeburn  3015:                 if (ref($mimetype)) {
                   3016:                     $$mimetype = $type;
                   3017:                 } 
1.637     raeburn  3018:             }
1.477     raeburn  3019:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3020:                                  $home);
1.481     raeburn  3021:             if ($fetchresult eq 'ok') {
                   3022:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3023:             } else {
                   3024:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3025:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3026:                 return '/adm/notfound.html';
                   3027:             }
1.477     raeburn  3028:         }
                   3029:     }
1.485     raeburn  3030:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3032:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3033:     }
                   3034:     return $fetchresult;
                   3035: }
                   3036: 
1.637     raeburn  3037: sub build_filepath {
                   3038:     my ($fpath) = @_;
                   3039:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3040:     unless ($fpath eq '') {
                   3041:         my @parts=split('/',$fpath);
                   3042:         foreach my $part (@parts) {
                   3043:             $filepath.= '/'.$part;
                   3044:             if ((-e $filepath)!=1) {
                   3045:                 mkdir($filepath,0777);
                   3046:             }
                   3047:         }
                   3048:     }
                   3049:     return $filepath;
                   3050: }
                   3051: 
                   3052: sub store_edited_file {
1.638     albertel 3053:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3054:     my $file = $primary_url;
                   3055:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3056:     my $fpath = '';
                   3057:     my $fname = $file;
                   3058:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3059:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3060:     my $filepath = &build_filepath($fpath);
                   3061:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3062:     print $fh $content;
                   3063:     close($fh);
1.638     albertel 3064:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3065:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3066: 			  $home);
1.637     raeburn  3067:     if ($$fetchresult eq 'ok') {
                   3068:         return '/uploaded/'.$fpath.'/'.$fname;
                   3069:     } else {
1.638     albertel 3070:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3071: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3072:         return '/adm/notfound.html';
                   3073:     }
                   3074: }
                   3075: 
1.531     albertel 3076: sub clean_filename {
1.831     albertel 3077:     my ($fname,$args)=@_;
1.315     www      3078: # Replace Windows backslashes by forward slashes
1.257     www      3079:     $fname=~s/\\/\//g;
1.831     albertel 3080:     if (!$args->{'keep_path'}) {
                   3081:         # Get rid of everything but the actual filename
                   3082: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3083:     }
1.315     www      3084: # Replace spaces by underscores
                   3085:     $fname=~s/\s+/\_/g;
                   3086: # Replace all other weird characters by nothing
1.831     albertel 3087:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3088: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3089: # numbers
                   3090:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3091:     return $fname;
                   3092: }
1.1051    raeburn  3093: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3094: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3095: # image with the same aspect ratio as the original, but with dimensions which do 
                   3096: # not exceed $resizewidth and $resizeheight.
                   3097:  
1.984     neumanie 3098: sub resizeImage {
1.1051    raeburn  3099:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3100:     my $ima = Image::Magick->new;
                   3101:     my $resized;
                   3102:     if (-e $img_path) {
                   3103:         $ima->Read($img_path);
                   3104:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3105:             my $width = $ima->Get('width');
                   3106:             my $height = $ima->Get('height');
                   3107:             if ($width > $resizewidth) {
                   3108: 	        my $factor = $width/$resizewidth;
                   3109:                 my $newheight = $height/$factor;
                   3110:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3111:                 $resized = 1;
                   3112:             }
                   3113:         }
                   3114:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3115:             my $width = $ima->Get('width');
                   3116:             my $height = $ima->Get('height');
                   3117:             if ($height > $resizeheight) {
                   3118:                 my $factor = $height/$resizeheight;
                   3119:                 my $newwidth = $width/$factor;
                   3120:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3121:                 $resized = 1;
                   3122:             }
                   3123:         }
                   3124:         if ($resized) {
                   3125:             $ima->Write($img_path);
                   3126:         }
                   3127:     }
                   3128:     return;
1.977     amueller 3129: }
                   3130: 
1.608     albertel 3131: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3132: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3133: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3134: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3135: #                                    canceloverwrite, or ''. 
                   3136: #                   if 'coursedoc': upload to the current course
                   3137: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3138: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3139: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3140: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3141: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3142: #        $allfiles - reference to hash for embedded objects
                   3143: #        $codebase - reference to hash for codebase of java objects
                   3144: #        $desuname - username for permanent storage of uploaded file
                   3145: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3146: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3147: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3148: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3149: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3150: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3151: #                    from File::MMagic.
1.858     raeburn  3152: # 
1.686     albertel 3153: # output: url of file in userspace, or error: <message> 
                   3154: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3155: 
1.531     albertel 3156: sub userfileupload {
1.1090    raeburn  3157:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3158:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3159:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3160:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3161:     $fname=&clean_filename($fname);
1.1090    raeburn  3162:     # See if there is anything left
1.257     www      3163:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3164:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3165:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3166:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3167:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3168:         my $now = time;
1.1090    raeburn  3169:         my $filepath;
1.1095    raeburn  3170:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3171:              $filepath = 'tmp/helprequests/'.$now;
                   3172:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3173:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3174:                          '_'.$env{'user.domain'}.'/pending';
                   3175:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3176:             my ($docuname,$docudom);
                   3177:             if ($destudom) {
                   3178:                 $docudom = $destudom;
                   3179:             } else {
                   3180:                 $docudom = $env{'user.domain'};
                   3181:             }
                   3182:             if ($destuname) {
                   3183:                 $docuname = $destuname;
                   3184:             } else {
                   3185:                 $docuname = $env{'user.name'};
                   3186:             }
                   3187:             if (exists($env{'form.group'})) {
                   3188:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3189:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3190:             }
                   3191:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3192:             if ($context eq 'canceloverwrite') {
                   3193:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3194:                 if (-e  $tempfile) {
                   3195:                     my @info = stat($tempfile);
                   3196:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3197:                         unlink($tempfile);
                   3198:                     }
                   3199:                 }
                   3200:                 return;
1.523     raeburn  3201:             }
                   3202:         }
1.1090    raeburn  3203:         # Create the directory if not present
1.741     raeburn  3204:         my @parts=split(/\//,$filepath);
                   3205:         my $fullpath = $perlvar{'lonDaemons'};
                   3206:         for (my $i=0;$i<@parts;$i++) {
                   3207:             $fullpath .= '/'.$parts[$i];
                   3208:             if ((-e $fullpath)!=1) {
                   3209:                 mkdir($fullpath,0777);
                   3210:             }
                   3211:         }
                   3212:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3213:         print $fh $env{'form.'.$formname};
                   3214:         close($fh);
1.1090    raeburn  3215:         if ($context eq 'existingfile') {
                   3216:             my @info = stat($fullpath.'/'.$fname);
                   3217:             return ($fullpath.'/'.$fname,$info[9]);
                   3218:         } else {
                   3219:             return $fullpath.'/'.$fname;
                   3220:         }
1.523     raeburn  3221:     }
1.995     raeburn  3222:     if ($subdir eq 'scantron') {
                   3223:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3224:     } else {
1.995     raeburn  3225:         $fname="$subdir/$fname";
                   3226:     }
1.1090    raeburn  3227:     if ($context eq 'coursedoc') {
1.638     albertel 3228: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3229: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3230:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3231:             return &finishuserfileupload($docuname,$docudom,
                   3232: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3233: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3234:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3235:         } else {
1.1172.2.21  raeburn  3236:             if ($env{'form.folder'}) {
                   3237:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3238:             }
1.638     albertel 3239:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3240: 				       $fname,$formname,$parser,
1.1095    raeburn  3241: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3242:         }
1.719     banghart 3243:     } elsif (defined($destuname)) {
                   3244:         my $docuname=$destuname;
                   3245:         my $docudom=$destudom;
1.860     raeburn  3246: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3247: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3248:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3249:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3250:     } else {
1.638     albertel 3251:         my $docuname=$env{'user.name'};
                   3252:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3253:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3254:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3255:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3256:         }
1.860     raeburn  3257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3258: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3259:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3260:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3261:     }
1.271     www      3262: }
                   3263: 
                   3264: sub finishuserfileupload {
1.860     raeburn  3265:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3266:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3267:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3268:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3269:   
1.860     raeburn  3270:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3271:     $file=$fname;
                   3272:     if ($fname=~m|/|) {
                   3273:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3274: 	$path.=$fnamepath.'/';
                   3275:     }
1.259     www      3276:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3277:     my $count;
                   3278:     for ($count=4;$count<=$#parts;$count++) {
                   3279:         $filepath.="/$parts[$count]";
                   3280:         if ((-e $filepath)!=1) {
                   3281: 	    mkdir($filepath,0777);
                   3282:         }
                   3283:     }
1.984     neumanie 3284: 
1.258     www      3285: # Save the file
                   3286:     {
1.701     albertel 3287: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3288: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3289: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3290: 	    return '/adm/notfound.html';
                   3291: 	}
1.1090    raeburn  3292:         if ($context eq 'overwrite') {
1.1117    foxr     3293:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3294:             my $target = $filepath.'/'.$file;
                   3295:             if (-e $source) {
                   3296:                 my @info = stat($source);
                   3297:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3298:                     unless (&File::Copy::move($source,$target)) {
                   3299:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3300:                         return "Moving from $source failed";
                   3301:                     }
                   3302:                 } else {
                   3303:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3304:                 }
                   3305:             } else {
                   3306:                 return "Temporary file: $source missing";
                   3307:             }
                   3308:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3309: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3310: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3311: 	    return '/adm/notfound.html';
                   3312: 	}
1.570     albertel 3313: 	close(FH);
1.1051    raeburn  3314:         if ($resizewidth && $resizeheight) {
                   3315:             my $mm = new File::MMagic;
                   3316:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3317:             if ($mime_type =~ m{^image/}) {
                   3318: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3319:             }  
1.977     amueller 3320: 	}
1.258     www      3321:     }
1.1152    raeburn  3322:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3323:         if (ref($mimetype)) {
                   3324:             if ($$mimetype eq '') {
                   3325:                 my $mm = new File::MMagic;
                   3326:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3327:                 $$mimetype = $type;
                   3328:             }
                   3329:         }
                   3330:     }
1.637     raeburn  3331:     if ($parser eq 'parse') {
1.1152    raeburn  3332:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3333:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3334:                                                        $allfiles,$codebase);
                   3335:             unless ($parse_result eq 'ok') {
                   3336:                 &logthis('Failed to parse '.$filepath.$file.
                   3337: 	   	         ' for embedded media: '.$parse_result); 
                   3338:             }
1.637     raeburn  3339:         }
                   3340:     }
1.860     raeburn  3341:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3342:         my $input = $filepath.'/'.$file;
                   3343:         my $output = $filepath.'/'.'tn-'.$file;
                   3344:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3345:         system("convert -sample $thumbsize $input $output");
                   3346:         if (-e $filepath.'/'.'tn-'.$file) {
                   3347:             $fetchthumb  = 1; 
                   3348:         }
                   3349:     }
1.858     raeburn  3350:  
1.259     www      3351: # Notify homeserver to grep it
                   3352: #
1.984     neumanie 3353:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3354:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3355:     if ($fetchresult eq 'ok') {
1.860     raeburn  3356:         if ($fetchthumb) {
                   3357:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3358:             if ($thumbresult ne 'ok') {
                   3359:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3360:                          $docuhome.': '.$thumbresult);
                   3361:             }
                   3362:         }
1.259     www      3363: #
1.258     www      3364: # Return the URL to it
1.494     albertel 3365:         return '/uploaded/'.$path.$file;
1.263     www      3366:     } else {
1.494     albertel 3367:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3368: 		 ': '.$fetchresult);
1.263     www      3369:         return '/adm/notfound.html';
1.858     raeburn  3370:     }
1.493     albertel 3371: }
                   3372: 
1.637     raeburn  3373: sub extract_embedded_items {
1.961     raeburn  3374:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3375:     my @state = ();
1.1164    raeburn  3376:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3377:     my %javafiles = (
                   3378:                       codebase => '',
                   3379:                       code => '',
                   3380:                       archive => ''
                   3381:                     );
                   3382:     my %mediafiles = (
                   3383:                       src => '',
                   3384:                       movie => '',
                   3385:                      );
1.648     raeburn  3386:     my $p;
                   3387:     if ($content) {
                   3388:         $p = HTML::LCParser->new($content);
                   3389:     } else {
1.961     raeburn  3390:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3391:     }
1.641     albertel 3392:     while (my $t=$p->get_token()) {
1.640     albertel 3393: 	if ($t->[0] eq 'S') {
                   3394: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3395: 	    push(@state, $tagname);
1.648     raeburn  3396:             if (lc($tagname) eq 'allow') {
                   3397:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3398:             }
1.640     albertel 3399: 	    if (lc($tagname) eq 'img') {
                   3400: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3401: 	    }
1.886     albertel 3402: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3403:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3404: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3405:                 }
1.886     albertel 3406: 	    }
1.645     raeburn  3407:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3408:                 my $src;
1.645     raeburn  3409:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3410:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3411:                 } else {
1.1164    raeburn  3412:                     if ($attr->{'src'} ne '') {
                   3413:                         $src = $attr->{'src'};
                   3414:                         &add_filetype($allfiles,$src,'src');
                   3415:                     }
                   3416:                 }
                   3417:                 my $text = $p->get_trimmed_text();
                   3418:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3419:                     my @swfargs = split(/,/,$1);
                   3420:                     foreach my $item (@swfargs) {
                   3421:                         $item =~ s/["']//g;
                   3422:                         $item =~ s/^\s+//;
                   3423:                         $item =~ s/\s+$//;
                   3424:                     }
                   3425:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3426:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3427:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3428:                         } else {
                   3429:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3430:                         }
                   3431:                     }
1.645     raeburn  3432:                 }
                   3433:             }
                   3434:             if (lc($tagname) eq 'link') {
                   3435:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3436:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3437:                 }
                   3438:             }
1.640     albertel 3439: 	    if (lc($tagname) eq 'object' ||
                   3440: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3441: 		foreach my $item (keys(%javafiles)) {
                   3442: 		    $javafiles{$item} = '';
                   3443: 		}
1.1164    raeburn  3444:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3445:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3446:                 }
1.640     albertel 3447: 	    }
                   3448: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3449: 		my $name = lc($attr->{'name'});
                   3450: 		foreach my $item (keys(%javafiles)) {
                   3451: 		    if ($name eq $item) {
                   3452: 			$javafiles{$item} = $attr->{'value'};
                   3453: 			last;
                   3454: 		    }
                   3455: 		}
1.1164    raeburn  3456:                 my $pathfrom;
1.640     albertel 3457: 		foreach my $item (keys(%mediafiles)) {
                   3458: 		    if ($name eq $item) {
1.1164    raeburn  3459:                         $pathfrom = $attr->{'value'};
                   3460:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3461: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3462: 			last;
                   3463: 		    }
                   3464: 		}
1.1164    raeburn  3465:                 if ($name eq 'flashvars') {
                   3466:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3467:                 }
                   3468:                 if ($pathfrom ne '') {
                   3469:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3470:                                          $pathfrom);
                   3471:                 }
1.640     albertel 3472: 	    }
                   3473: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3474: 		foreach my $item (keys(%javafiles)) {
                   3475: 		    if ($attr->{$item}) {
                   3476: 			$javafiles{$item} = $attr->{$item};
                   3477: 			last;
                   3478: 		    }
                   3479: 		}
                   3480: 		foreach my $item (keys(%mediafiles)) {
                   3481: 		    if ($attr->{$item}) {
                   3482: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3483: 			last;
                   3484: 		    }
                   3485: 		}
1.1164    raeburn  3486:                 if (lc($tagname) eq 'embed') {
                   3487:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3488:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3489:                                              $attr->{'src'});
                   3490:                     }
                   3491:                 }
1.640     albertel 3492: 	    }
1.1164    raeburn  3493:             if ($t->[4] =~ m{/>$}) {
                   3494:                 pop(@state);  
                   3495:             }
1.640     albertel 3496: 	} elsif ($t->[0] eq 'E') {
                   3497: 	    my ($tagname) = ($t->[1]);
                   3498: 	    if ($javafiles{'codebase'} ne '') {
                   3499: 		$javafiles{'codebase'} .= '/';
                   3500: 	    }  
                   3501: 	    if (lc($tagname) eq 'applet' ||
                   3502: 		lc($tagname) eq 'object' ||
                   3503: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3504: 		) {
                   3505: 		foreach my $item (keys(%javafiles)) {
                   3506: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3507: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3508: 			&add_filetype($allfiles,$file,$item);
                   3509: 		    }
                   3510: 		}
                   3511: 	    } 
                   3512: 	    pop @state;
                   3513: 	}
                   3514:     }
1.1164    raeburn  3515:     foreach my $id (sort(keys(%flashvars))) {
                   3516:         if ($shockwave{$id} ne '') {
                   3517:             my @pairs = split(/\&/,$flashvars{$id});
                   3518:             foreach my $pair (@pairs) {
                   3519:                 my ($key,$value) = split(/\=/,$pair);
                   3520:                 if ($key eq 'thumb') {
                   3521:                     &add_filetype($allfiles,$value,$key);
                   3522:                 } elsif ($key eq 'content') {
                   3523:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3524:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3525:                     if ($ext ne '') {
                   3526:                         &add_filetype($allfiles,$path.$value,$ext);
                   3527:                     }
                   3528:                 }
                   3529:             }
                   3530:         }
                   3531:     }
1.637     raeburn  3532:     return 'ok';
                   3533: }
                   3534: 
1.639     albertel 3535: sub add_filetype {
                   3536:     my ($allfiles,$file,$type)=@_;
                   3537:     if (exists($allfiles->{$file})) {
                   3538: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3539: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3540: 	}
                   3541:     } else {
                   3542: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3543:     }
                   3544: }
                   3545: 
1.1164    raeburn  3546: sub embedded_dependency {
                   3547:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3548:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3549:         if (($identifier ne '') &&
                   3550:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3551:             ($pathfrom ne '')) {
                   3552:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3553:             foreach my $dep (@{$related->{$identifier}}) {
                   3554:                 &add_filetype($allfiles,$path.$dep,'object');
                   3555:             }
                   3556:         }
                   3557:     }
                   3558:     return;
                   3559: }
                   3560: 
1.493     albertel 3561: sub removeuploadedurl {
1.984     neumanie 3562:     my ($url)=@_;	
                   3563:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3564:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3565: }
                   3566: 
                   3567: sub removeuserfile {
                   3568:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3569:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3570:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3571:     if ($result eq 'ok') {	
1.798     raeburn  3572:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3573:             my $metafile = $fname.'.meta';
                   3574:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3575: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3576:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3577:             my $sqlresult = 
1.823     albertel 3578:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3579:                                         'portfolio_metadata',$group,
                   3580:                                         'delete');
1.798     raeburn  3581:         }
                   3582:     }
                   3583:     return $result;
1.257     www      3584: }
1.15      www      3585: 
1.530     albertel 3586: sub mkdiruserfile {
                   3587:     my ($docuname,$docudom,$dir)=@_;
                   3588:     my $home=&homeserver($docuname,$docudom);
                   3589:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3590: }
                   3591: 
1.531     albertel 3592: sub renameuserfile {
                   3593:     my ($docuname,$docudom,$old,$new)=@_;
                   3594:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3595:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3596:                         &escape("$old").':'.&escape("$new"),$home);
                   3597:     if ($result eq 'ok') {
                   3598:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3599:             my $oldmeta = $old.'.meta';
                   3600:             my $newmeta = $new.'.meta';
                   3601:             my $metaresult = 
                   3602:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3603: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3604:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3605:             my $sqlresult = 
1.823     albertel 3606:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3607:                                         'portfolio_metadata',$group,
                   3608:                                         'delete');
1.798     raeburn  3609:         }
                   3610:     }
                   3611:     return $result;
1.531     albertel 3612: }
                   3613: 
1.14      www      3614: # ------------------------------------------------------------------------- Log
                   3615: 
                   3616: sub log {
                   3617:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3618:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3619: }
                   3620: 
                   3621: # ------------------------------------------------------------------ Course Log
1.352     www      3622: #
                   3623: # This routine flushes several buffers of non-mission-critical nature
                   3624: #
1.157     www      3625: 
                   3626: sub flushcourselogs {
1.352     www      3627:     &logthis('Flushing log buffers');
                   3628: #
                   3629: # course logs
                   3630: # This is a log of all transactions in a course, which can be used
                   3631: # for data mining purposes
                   3632: #
                   3633: # It also collects the courseid database, which lists last transaction
                   3634: # times and course titles for all courseids
                   3635: #
                   3636:     my %courseidbuffer=();
1.921     raeburn  3637:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3638:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3639: 		          &escape($courselogs{$crsid}),
                   3640: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3641: 	    delete $courselogs{$crsid};
                   3642:         } else {
                   3643:             &logthis('Failed to flush log buffer for '.$crsid);
                   3644:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3645:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3646:                         " exceeded maximum size, deleting.</font>");
                   3647:                delete $courselogs{$crsid};
                   3648:             }
1.352     www      3649:         }
1.920     raeburn  3650:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3651:             'description' => $coursedescrbuf{$crsid},
                   3652:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3653:             'type'        => $coursetypebuf{$crsid},
                   3654:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3655:         };
1.191     harris41 3656:     }
1.352     www      3657: #
                   3658: # Write course id database (reverse lookup) to homeserver of courses 
                   3659: # Is used in pickcourse
                   3660: #
1.840     albertel 3661:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3662:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3663:                                     $courseidbuffer{$crs_home},
                   3664:                                     $crs_home,'timeonly');
1.352     www      3665:     }
                   3666: #
                   3667: # File accesses
                   3668: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3669: #
1.449     matthew  3670:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3671:         if ($entry =~ /___count$/) {
                   3672:             my ($dom,$name);
1.807     albertel 3673:             ($dom,$name,undef)=
1.811     albertel 3674: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3675:             if (! defined($dom) || $dom eq '' || 
                   3676:                 ! defined($name) || $name eq '') {
1.620     albertel 3677:                 my $cid = $env{'request.course.id'};
                   3678:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3679:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3680:             }
1.450     matthew  3681:             my $value = $accesshash{$entry};
                   3682:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3683:             my %temphash=($url => $value);
1.449     matthew  3684:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3685:             if ($result eq 'ok') {
                   3686:                 delete $accesshash{$entry};
                   3687:             }
                   3688:         } else {
1.811     albertel 3689:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3690:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3691:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3692:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3693:                 delete $accesshash{$entry};
                   3694:             }
1.185     www      3695:         }
1.191     harris41 3696:     }
1.352     www      3697: #
                   3698: # Roles
                   3699: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3700: #
1.800     albertel 3701:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3702:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3703: 	    split(/\:/,$entry);
                   3704:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3705:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3706:                 $rudom,$runame) eq 'ok') {
                   3707: 	    delete $userrolehash{$entry};
                   3708:         }
                   3709:     }
1.662     raeburn  3710: #
                   3711: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3712: #
                   3713:     my %domrolebuffer = ();
1.1000    raeburn  3714:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3715:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3716:         if ($domrolebuffer{$rudom}) {
                   3717:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3718:                       '='.&escape($domainrolehash{$entry});
                   3719:         } else {
                   3720:             $domrolebuffer{$rudom}.=&escape($entry).
                   3721:                       '='.&escape($domainrolehash{$entry});
                   3722:         }
                   3723:         delete $domainrolehash{$entry};
                   3724:     }
                   3725:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3726: 	my %servers = &get_servers($dom,'library');
                   3727: 	foreach my $tryserver (keys(%servers)) {
                   3728: 	    unless (&reply('domroleput:'.$dom.':'.
                   3729: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3730: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3731: 	    }
1.662     raeburn  3732:         }
                   3733:     }
1.186     www      3734:     $dumpcount++;
1.157     www      3735: }
                   3736: 
                   3737: sub courselog {
                   3738:     my $what=shift;
1.158     www      3739:     $what=time.':'.$what;
1.620     albertel 3740:     unless ($env{'request.course.id'}) { return ''; }
                   3741:     $coursedombuf{$env{'request.course.id'}}=
                   3742:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3743:     $coursenumbuf{$env{'request.course.id'}}=
                   3744:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3745:     $coursehombuf{$env{'request.course.id'}}=
                   3746:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3747:     $coursedescrbuf{$env{'request.course.id'}}=
                   3748:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3749:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3750:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3751:     $courseownerbuf{$env{'request.course.id'}}=
                   3752:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3753:     $coursetypebuf{$env{'request.course.id'}}=
                   3754:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3755:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3756: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3757:     } else {
1.620     albertel 3758: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3759:     }
1.620     albertel 3760:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3761: 	&flushcourselogs();
                   3762:     }
1.158     www      3763: }
                   3764: 
                   3765: sub courseacclog {
                   3766:     my $fnsymb=shift;
1.620     albertel 3767:     unless ($env{'request.course.id'}) { return ''; }
                   3768:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3769:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3770:         $what.=':POST';
1.583     matthew  3771:         # FIXME: Probably ought to escape things....
1.800     albertel 3772: 	foreach my $key (keys(%env)) {
                   3773:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3774:                 my $formitem = $1;
                   3775:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3776:                     $what.=':'.$formitem.'='.$env{$key};
                   3777:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3778:                     $what.=':'.$formitem.'='.$env{$key};
                   3779:                 }
1.158     www      3780:             }
1.191     harris41 3781:         }
1.583     matthew  3782:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3783:         # FIXME: We should not be depending on a form parameter that someone
                   3784:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3785:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3786:             $what.= ':POST';
                   3787:             # FIXME: Probably ought to escape things....
                   3788:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3789:                                  'crsdiscuss') {
1.620     albertel 3790:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3791:             }
                   3792:         }
1.158     www      3793:     }
                   3794:     &courselog($what);
1.149     www      3795: }
                   3796: 
1.185     www      3797: sub countacc {
                   3798:     my $url=&declutter(shift);
1.458     matthew  3799:     return if (! defined($url) || $url eq '');
1.620     albertel 3800:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3801: #
                   3802: # Mark that this url was used in this course
                   3803: #
1.620     albertel 3804:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3805: #
                   3806: # Increase the access count for this resource in this child process
                   3807: #
1.281     www      3808:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3809:     $accesshash{$key}++;
1.185     www      3810: }
1.349     www      3811: 
1.361     www      3812: sub linklog {
                   3813:     my ($from,$to)=@_;
                   3814:     $from=&declutter($from);
                   3815:     $to=&declutter($to);
                   3816:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3817:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3818: }
1.1160    www      3819: 
                   3820: sub statslog {
                   3821:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3822:     if ($users<2) { return; }
                   3823:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3824:             'course'       => $env{'request.course.id'},
                   3825:             'sections'     => '"all"',
                   3826:             'num_students' => $users,
                   3827:             'part'         => $part,
                   3828:             'symb'         => $symb,
                   3829:             'mean_tries'   => $av_attempts,
                   3830:             'deg_of_diff'  => $degdiff});
                   3831:     foreach my $key (keys(%dynstore)) {
                   3832:         $accesshash{$key}=$dynstore{$key};
                   3833:     }
                   3834: }
1.361     www      3835:   
1.349     www      3836: sub userrolelog {
                   3837:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3838:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3839:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3840:        $userrolehash
                   3841:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3842:                     =$tend.':'.$tstart;
1.662     raeburn  3843:     }
1.1169    droeschl 3844:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3845:        $userrolehash
                   3846:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3847:                     =$tend.':'.$tstart;
                   3848:     }
1.1169    droeschl 3849:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3850:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3851:        $domainrolehash
                   3852:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3853:                     = $tend.':'.$tstart;
                   3854:     }
1.351     www      3855: }
                   3856: 
1.957     raeburn  3857: sub courserolelog {
                   3858:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3859:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3860:         my $cdom = $1;
                   3861:         my $cnum = $2;
                   3862:         my $sec = $3;
                   3863:         my $namespace = 'rolelog';
                   3864:         my %storehash = (
                   3865:                            role    => $trole,
                   3866:                            start   => $tstart,
                   3867:                            end     => $tend,
                   3868:                            selfenroll => $selfenroll,
                   3869:                            context    => $context,
                   3870:                         );
                   3871:         if ($trole eq 'gr') {
                   3872:             $namespace = 'groupslog';
                   3873:             $storehash{'group'} = $sec;
                   3874:         } else {
                   3875:             $storehash{'section'} = $sec;
                   3876:         }
                   3877:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3878:                    $domain,$cnum,$cdom);
                   3879:         if (($trole ne 'st') || ($sec ne '')) {
                   3880:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3881:         }
                   3882:     }
                   3883:     return;
                   3884: }
                   3885: 
1.1172.2.9  raeburn  3886: sub domainrolelog {
                   3887:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3888:     if ($area =~ m{^/($match_domain)/$}) {
                   3889:         my $cdom = $1;
                   3890:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3891:         my $namespace = 'rolelog';
                   3892:         my %storehash = (
                   3893:                            role    => $trole,
                   3894:                            start   => $tstart,
                   3895:                            end     => $tend,
                   3896:                            context => $context,
                   3897:                         );
                   3898:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3899:                    $domain,$domconfiguser,$cdom);
                   3900:     }
                   3901:     return;
                   3902: 
                   3903: }
                   3904: 
                   3905: sub coauthorrolelog {
                   3906:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3907:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3908:         my $audom = $1;
                   3909:         my $auname = $2;
                   3910:         my $namespace = 'rolelog';
                   3911:         my %storehash = (
                   3912:                            role    => $trole,
                   3913:                            start   => $tstart,
                   3914:                            end     => $tend,
                   3915:                            context => $context,
                   3916:                         );
                   3917:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3918:                    $domain,$auname,$audom);
                   3919:     }
                   3920:     return;
                   3921: }
                   3922: 
1.351     www      3923: sub get_course_adv_roles {
1.948     raeburn  3924:     my ($cid,$codes) = @_;
1.620     albertel 3925:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3926:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3927:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3928:     my %nothide=();
1.800     albertel 3929:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3930:         if ($user !~ /:/) {
                   3931: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3932:         } else {
                   3933:             $nothide{$user}=1;
                   3934:         }
1.470     www      3935:     }
1.1172.2.23  raeburn  3936:     my @possdoms = ($coursehash{'domain'});
                   3937:     if ($coursehash{'checkforpriv'}) {
                   3938:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3939:     }
1.351     www      3940:     my %returnhash=();
                   3941:     my %dumphash=
                   3942:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3943:     my $now=time;
1.997     raeburn  3944:     my %privileged;
1.1000    raeburn  3945:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3946: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3947:         if (($tstart) && ($tstart<0)) { next; }
                   3948:         if (($tend) && ($tend<$now)) { next; }
                   3949:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3950:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3951: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  3952:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3953:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3954: 	if ($role eq 'cr') { next; }
1.948     raeburn  3955:         if ($codes) {
                   3956:             if ($section) { $role .= ':'.$section; }
                   3957:             if ($returnhash{$role}) {
                   3958:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3959:             } else {
                   3960:                 $returnhash{$role}=$username.':'.$domain;
                   3961:             }
1.351     www      3962:         } else {
1.988     raeburn  3963:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3964:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3965:             if ($returnhash{$key}) {
                   3966: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3967:             } else {
                   3968:                 $returnhash{$key}=$username.':'.$domain;
                   3969:             }
1.351     www      3970:         }
1.948     raeburn  3971:     }
1.400     www      3972:     return %returnhash;
                   3973: }
                   3974: 
                   3975: sub get_my_roles {
1.937     raeburn  3976:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3977:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3978:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3979:     my (%dumphash,%nothide);
1.1086    raeburn  3980:     if ($context eq 'userroles') {
1.1166    raeburn  3981:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3982:     } else {
1.1172.2.23  raeburn  3983:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3984:         if ($hidepriv) {
                   3985:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3986:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3987:                 if ($user !~ /:/) {
                   3988:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3989:                 } else {
                   3990:                     $nothide{$user} = 1;
                   3991:                 }
                   3992:             }
                   3993:         }
1.858     raeburn  3994:     }
1.400     www      3995:     my %returnhash=();
                   3996:     my $now=time;
1.999     raeburn  3997:     my %privileged;
1.800     albertel 3998:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3999:         my ($role,$tend,$tstart);
                   4000:         if ($context eq 'userroles') {
1.1149    raeburn  4001:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4002: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4003:         } else {
                   4004:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4005:         }
1.400     www      4006:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4007:         my $status = 'active';
1.939     raeburn  4008:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4009:             $status = 'previous';
                   4010:         } 
                   4011:         if (($tstart) && ($now<$tstart)) {
                   4012:             $status = 'future';
                   4013:         }
                   4014:         if (ref($types) eq 'ARRAY') {
                   4015:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4016:                 next;
                   4017:             } 
                   4018:         } else {
                   4019:             if ($status ne 'active') {
                   4020:                 next;
                   4021:             }
                   4022:         }
1.867     raeburn  4023:         my ($rolecode,$username,$domain,$section,$area);
                   4024:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4025:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4026:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4027:         } else {
                   4028:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4029:         }
1.832     raeburn  4030:         if (ref($roledoms) eq 'ARRAY') {
                   4031:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4032:                 next;
                   4033:             }
                   4034:         }
                   4035:         if (ref($roles) eq 'ARRAY') {
                   4036:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4037:                 if ($role =~ /^cr\//) {
                   4038:                     if (!grep(/^cr$/,@{$roles})) {
                   4039:                         next;
                   4040:                     }
1.1104    raeburn  4041:                 } elsif ($role =~ /^gr\//) {
                   4042:                     if (!grep(/^gr$/,@{$roles})) {
                   4043:                         next;
                   4044:                     }
1.922     raeburn  4045:                 } else {
                   4046:                     next;
                   4047:                 }
1.832     raeburn  4048:             }
1.867     raeburn  4049:         }
1.937     raeburn  4050:         if ($hidepriv) {
1.1172.2.23  raeburn  4051:             my @privroles = ('dc','su');
1.999     raeburn  4052:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4053:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4054:             } else {
1.1172.2.23  raeburn  4055:                 my $possdoms = [$domain];
                   4056:                 if (ref($roledoms) eq 'ARRAY') {
                   4057:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4058:                 }
1.1172.2.23  raeburn  4059:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4060:                     if (!$nothide{$username.':'.$domain}) {
                   4061:                         next;
                   4062:                     }
                   4063:                 }
1.937     raeburn  4064:             }
                   4065:         }
1.933     raeburn  4066:         if ($withsec) {
                   4067:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4068:                 $tstart.':'.$tend;
                   4069:         } else {
                   4070:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4071:         }
1.832     raeburn  4072:     }
1.373     www      4073:     return %returnhash;
1.399     www      4074: }
                   4075: 
                   4076: # ----------------------------------------------------- Frontpage Announcements
                   4077: #
                   4078: #
                   4079: 
                   4080: sub postannounce {
                   4081:     my ($server,$text)=@_;
1.844     albertel 4082:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4083:     unless ($text=~/\w/) { $text=''; }
                   4084:     return &reply('setannounce:'.&escape($text),$server);
                   4085: }
                   4086: 
                   4087: sub getannounce {
1.448     albertel 4088: 
                   4089:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4090: 	my $announcement='';
1.800     albertel 4091: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4092: 	close($fh);
1.399     www      4093: 	if ($announcement=~/\w/) { 
                   4094: 	    return 
                   4095:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4096:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4097: 	} else {
                   4098: 	    return '';
                   4099: 	}
                   4100:     } else {
                   4101: 	return '';
                   4102:     }
1.351     www      4103: }
1.353     www      4104: 
                   4105: # ---------------------------------------------------------- Course ID routines
                   4106: # Deal with domain's nohist_courseid.db files
                   4107: #
                   4108: 
                   4109: sub courseidput {
1.921     raeburn  4110:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4111:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4112:     my $outcome;
                   4113:     if ($caller eq 'timeonly') {
                   4114:         my $cids = '';
                   4115:         foreach my $item (keys(%$storehash)) {
                   4116:             $cids.=&escape($item).'&';
                   4117:         }
                   4118:         $cids=~s/\&$//;
                   4119:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4120:                           $coursehome);       
                   4121:     } else {
                   4122:         my $items = '';
                   4123:         foreach my $item (keys(%$storehash)) {
                   4124:             $items.= &escape($item).'='.
                   4125:                      &freeze_escape($$storehash{$item}).'&';
                   4126:         }
                   4127:         $items=~s/\&$//;
                   4128:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4129:                           $coursehome);
1.918     raeburn  4130:     }
                   4131:     if ($outcome eq 'unknown_cmd') {
                   4132:         my $what;
                   4133:         foreach my $cid (keys(%$storehash)) {
                   4134:             $what .= &escape($cid).'=';
1.921     raeburn  4135:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4136:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4137:             }
                   4138:             $what =~ s/\:$/&/;
                   4139:         }
                   4140:         $what =~ s/\&$//;  
                   4141:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4142:     } else {
                   4143:         return $outcome;
                   4144:     }
1.353     www      4145: }
                   4146: 
                   4147: sub courseiddump {
1.921     raeburn  4148:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4149:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4150:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4151:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4152:     my $as_hash = 1;
                   4153:     my %returnhash;
                   4154:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4155:     my %libserv = &all_library();
                   4156:     foreach my $tryserver (keys(%libserv)) {
                   4157:         if ( (  $hostidflag == 1 
                   4158: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4159: 	     || (!defined($hostidflag)) ) {
                   4160: 
1.918     raeburn  4161: 	    if (($domfilter eq '') ||
                   4162: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4163:                 my $rep;
                   4164:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4165:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4166:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4167:                                 &escape($descfilter), &escape($instcodefilter),
                   4168:                                 &escape($ownerfilter), &escape($coursefilter),
                   4169:                                 &escape($typefilter), &escape($regexp_ok),
                   4170:                                 $as_hash, &escape($selfenrollonly),
                   4171:                                 &escape($catfilter), $showhidden, $caller,
                   4172:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4173:                                 &escape($createdbefore), &escape($createdafter),
                   4174:                                 &escape($creationcontext), $domcloner)));
                   4175:                 } else {
                   4176:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4177:                              $sincefilter.':'.&escape($descfilter).':'.
                   4178:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4179:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4180:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4181:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4182:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4183:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4184:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4185:                              &escape($creationcontext).':'.$domcloner,
                   4186:                              $tryserver);
                   4187:                 }
                   4188: 
1.918     raeburn  4189:                 my @pairs=split(/\&/,$rep);
                   4190:                 foreach my $item (@pairs) {
                   4191:                     my ($key,$value)=split(/\=/,$item,2);
                   4192:                     $key = &unescape($key);
                   4193:                     next if ($key =~ /^error: 2 /);
                   4194:                     my $result = &thaw_unescape($value);
                   4195:                     if (ref($result) eq 'HASH') {
                   4196:                         $returnhash{$key}=$result;
                   4197:                     } else {
1.921     raeburn  4198:                         my @responses = split(/:/,$value);
                   4199:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4200:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4201:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4202:                         }
1.1008    raeburn  4203:                     }
1.353     www      4204:                 }
                   4205:             }
                   4206:         }
                   4207:     }
                   4208:     return %returnhash;
                   4209: }
                   4210: 
1.1055    raeburn  4211: sub courselastaccess {
                   4212:     my ($cdom,$cnum,$hostidref) = @_;
                   4213:     my %returnhash;
                   4214:     if ($cdom && $cnum) {
                   4215:         my $chome = &homeserver($cnum,$cdom);
                   4216:         if ($chome ne 'no_host') {
                   4217:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4218:             &extract_lastaccess(\%returnhash,$rep);
                   4219:         }
                   4220:     } else {
                   4221:         if (!$cdom) { $cdom=''; }
                   4222:         my %libserv = &all_library();
                   4223:         foreach my $tryserver (keys(%libserv)) {
                   4224:             if (ref($hostidref) eq 'ARRAY') {
                   4225:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4226:             } 
                   4227:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4228:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4229:                 &extract_lastaccess(\%returnhash,$rep);
                   4230:             }
                   4231:         }
                   4232:     }
                   4233:     return %returnhash;
                   4234: }
                   4235: 
                   4236: sub extract_lastaccess {
                   4237:     my ($returnhash,$rep) = @_;
                   4238:     if (ref($returnhash) eq 'HASH') {
                   4239:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4240:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4241:                  $rep eq '') {
                   4242:             my @pairs=split(/\&/,$rep);
                   4243:             foreach my $item (@pairs) {
                   4244:                 my ($key,$value)=split(/\=/,$item,2);
                   4245:                 $key = &unescape($key);
                   4246:                 next if ($key =~ /^error: 2 /);
                   4247:                 $returnhash->{$key} = &thaw_unescape($value);
                   4248:             }
                   4249:         }
                   4250:     }
                   4251:     return;
                   4252: }
                   4253: 
1.658     raeburn  4254: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4255: 
                   4256: sub dcmailput {
1.685     raeburn  4257:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4258:     my $status = &Apache::lonnet::critical(
1.740     www      4259:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4260:        &escape($message),$server);
1.662     raeburn  4261:     return $status;
                   4262: }
                   4263: 
1.658     raeburn  4264: sub dcmaildump {
                   4265:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4266:     my %returnhash=();
1.846     albertel 4267: 
                   4268:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4269:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4270:                                                          &escape($enddate).':';
                   4271: 	my @esc_senders=map { &escape($_)} @$senders;
                   4272: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4273: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4274:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4275:             if (($key) && ($value)) {
                   4276:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4277:             }
                   4278:         }
                   4279:     }
                   4280:     return %returnhash;
                   4281: }
1.662     raeburn  4282: # ---------------------------------------------------------- Domain roles
                   4283: 
                   4284: sub get_domain_roles {
                   4285:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4286:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4287:         $startdate = '.';
                   4288:     }
1.1018    raeburn  4289:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4290:         $enddate = '.';
                   4291:     }
1.922     raeburn  4292:     my $rolelist;
                   4293:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4294:         $rolelist = join('&',@{$roles});
1.922     raeburn  4295:     }
1.662     raeburn  4296:     my %personnel = ();
1.841     albertel 4297: 
                   4298:     my %servers = &get_servers($dom,'library');
                   4299:     foreach my $tryserver (keys(%servers)) {
                   4300: 	%{$personnel{$tryserver}}=();
                   4301: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4302: 					    &escape($startdate).':'.
                   4303: 					    &escape($enddate).':'.
                   4304: 					    &escape($rolelist), $tryserver))) {
                   4305: 	    my ($key,$value) = split(/\=/,$line,2);
                   4306: 	    if (($key) && ($value)) {
                   4307: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4308: 	    }
                   4309: 	}
1.662     raeburn  4310:     }
                   4311:     return %personnel;
                   4312: }
1.658     raeburn  4313: 
1.1057    www      4314: # ----------------------------------------------------------- Interval timing 
1.149     www      4315: 
1.1153    www      4316: {
                   4317: # Caches needed for speedup of navmaps
                   4318: # We don't want to cache this for very long at all (5 seconds at most)
                   4319: # 
                   4320: # The user for whom we cache
                   4321: my $cachedkey='';
                   4322: # The cached times for this user
                   4323: my %cachedtimes=();
                   4324: # When this was last done
                   4325: my $cachedtime=();
                   4326: 
                   4327: sub load_all_first_access {
1.1154    raeburn  4328:     my ($uname,$udom)=@_;
1.1156    www      4329:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4330:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4331:         return;
                   4332:     }
                   4333:     $cachedtime=time;
                   4334:     $cachedkey=$uname.':'.$udom;
                   4335:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4336: }
                   4337: 
1.504     albertel 4338: sub get_first_access {
1.1162    raeburn  4339:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4340:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4341:     if ($argsymb) { $symb=$argsymb; }
                   4342:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4343:     if ($argmap) { $map = $argmap; }
1.926     albertel 4344:     if ($type eq 'course') {
                   4345: 	$res='course';
                   4346:     } elsif ($type eq 'map') {
1.588     albertel 4347: 	$res=&symbread($map);
                   4348:     } else {
                   4349: 	$res=$symb;
                   4350:     }
1.1153    www      4351:     &load_all_first_access($uname,$udom);
                   4352:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4353: }
                   4354: 
                   4355: sub set_first_access {
1.1162    raeburn  4356:     my ($type,$interval)=@_;
1.790     albertel 4357:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4358:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4359:     if ($type eq 'course') {
                   4360: 	$res='course';
                   4361:     } elsif ($type eq 'map') {
1.588     albertel 4362: 	$res=&symbread($map);
                   4363:     } else {
                   4364: 	$res=$symb;
                   4365:     }
1.1153    www      4366:     $cachedkey='';
1.1162    raeburn  4367:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4368:     if (!$firstaccess) {
1.1162    raeburn  4369:         my $start = time;
                   4370: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4371:                           $udom,$uname);
                   4372:         if ($putres eq 'ok') {
                   4373:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4374:                  $udom,$uname); 
                   4375:             &appenv(
                   4376:                      {
                   4377:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4378:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4379:                      }
                   4380:                   );
                   4381:         }
                   4382:         return $putres;
1.505     albertel 4383:     }
                   4384:     return 'already_set';
1.504     albertel 4385: }
1.1153    www      4386: }
1.1172.2.32  raeburn  4387: 
                   4388: sub checkout {
                   4389:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4390:     my $now=time;
                   4391:     my $lonhost=$perlvar{'lonHostID'};
                   4392:     my $infostr=&escape(
                   4393:                  'CHECKOUTTOKEN&'.
                   4394:                  $tuname.'&'.
                   4395:                  $tudom.'&'.
                   4396:                  $tcrsid.'&'.
                   4397:                  $symb.'&'.
                   4398:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4399:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4400:     if ($token=~/^error\:/) {
                   4401:         &logthis("<font color=\"blue\">WARNING: ".
                   4402:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4403:                  "</font>");
                   4404:         return '';
                   4405:     }
                   4406: 
                   4407:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4408:     $token=~tr/a-z/A-Z/;
                   4409: 
                   4410:     my %infohash=('resource.0.outtoken' => $token,
                   4411:                   'resource.0.checkouttime' => $now,
                   4412:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4413: 
                   4414:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4415:        return '';
                   4416:     } else {
                   4417:         &logthis("<font color=\"blue\">WARNING: ".
                   4418:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4419:                  "</font>");
                   4420:     }
                   4421: 
                   4422:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4423:                          &escape('Checkout '.$infostr.' - '.
                   4424:                                                  $token)) ne 'ok') {
                   4425:         return '';
                   4426:     } else {
                   4427:         &logthis("<font color=\"blue\">WARNING: ".
                   4428:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4429:                  "</font>");
                   4430:     }
                   4431:     return $token;
                   4432: }
                   4433: 
                   4434: # ------------------------------------------------------------ Check in an item
                   4435: 
                   4436: sub checkin {
                   4437:     my $token=shift;
                   4438:     my $now=time;
                   4439:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4440:     $lonhost=~tr/A-Z/a-z/;
                   4441:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4442:     $dtoken=~s/\W/\_/g;
                   4443:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4444:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4445: 
                   4446:     unless (($tuname) && ($tudom)) {
                   4447:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4448:         return '';
                   4449:     }
                   4450: 
                   4451:     unless (&allowed('mgr',$tcrsid)) {
                   4452:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4453:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4454:         return '';
                   4455:     }
                   4456: 
                   4457:     my %infohash=('resource.0.intoken' => $token,
                   4458:                   'resource.0.checkintime' => $now,
                   4459:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4460: 
                   4461:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4462:        return '';
                   4463:     }
                   4464: 
                   4465:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4466:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4467:         return '';
                   4468:     }
                   4469: 
                   4470:     return ($symb,$tuname,$tudom,$tcrsid);
                   4471: }
                   4472: 
1.110     www      4473: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4474: 
                   4475: sub expirespread {
                   4476:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4477:     my $cid=$env{'request.course.id'}; 
1.110     www      4478:     if ($cid) {
                   4479:        my $now=time;
                   4480:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4481:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4482:                             $env{'course.'.$cid.'.num'}.
1.110     www      4483: 	        	    ':nohist_expirationdates:'.
                   4484:                             &escape($key).'='.$now,
1.620     albertel 4485:                             $env{'course.'.$cid.'.home'})
1.110     www      4486:     }
                   4487:     return 'ok';
1.14      www      4488: }
                   4489: 
1.109     www      4490: # ----------------------------------------------------- Devalidate Spreadsheets
                   4491: 
                   4492: sub devalidate {
1.325     www      4493:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4494:     my $cid=$env{'request.course.id'}; 
1.109     www      4495:     if ($cid) {
1.391     matthew  4496:         # delete the stored spreadsheets for
                   4497:         # - the student level sheet of this user in course's homespace
                   4498:         # - the assessment level sheet for this resource 
                   4499:         #   for this user in user's homespace
1.553     albertel 4500: 	# - current conditional state info
1.325     www      4501: 	my $key=$uname.':'.$udom.':';
1.109     www      4502:         my $status=
1.299     matthew  4503: 	    &del('nohist_calculatedsheets',
1.391     matthew  4504: 		 [$key.'studentcalc:'],
1.620     albertel 4505: 		 $env{'course.'.$cid.'.domain'},
                   4506: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4507: 		.' '.
                   4508: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4509: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4510:         unless ($status eq 'ok ok') {
                   4511:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4512:                     $uname.' at '.$udom.' for '.
1.109     www      4513: 		    $symb.': '.$status);
1.133     albertel 4514:         }
1.553     albertel 4515: 	&delenv('user.state.'.$cid);
1.109     www      4516:     }
                   4517: }
                   4518: 
1.265     albertel 4519: sub get_scalar {
                   4520:     my ($string,$end) = @_;
                   4521:     my $value;
                   4522:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4523: 	$value = $1;
                   4524:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4525: 	$value = $1;
                   4526:     }
                   4527:     return &unescape($value);
                   4528: }
                   4529: 
                   4530: sub array2str {
                   4531:   my (@array) = @_;
                   4532:   my $result=&arrayref2str(\@array);
                   4533:   $result=~s/^__ARRAY_REF__//;
                   4534:   $result=~s/__END_ARRAY_REF__$//;
                   4535:   return $result;
                   4536: }
                   4537: 
1.204     albertel 4538: sub arrayref2str {
                   4539:   my ($arrayref) = @_;
1.265     albertel 4540:   my $result='__ARRAY_REF__';
1.204     albertel 4541:   foreach my $elem (@$arrayref) {
1.265     albertel 4542:     if(ref($elem) eq 'ARRAY') {
                   4543:       $result.=&arrayref2str($elem).'&';
                   4544:     } elsif(ref($elem) eq 'HASH') {
                   4545:       $result.=&hashref2str($elem).'&';
                   4546:     } elsif(ref($elem)) {
                   4547:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4548:     } else {
                   4549:       $result.=&escape($elem).'&';
                   4550:     }
                   4551:   }
                   4552:   $result=~s/\&$//;
1.265     albertel 4553:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4554:   return $result;
                   4555: }
                   4556: 
1.168     albertel 4557: sub hash2str {
1.204     albertel 4558:   my (%hash) = @_;
                   4559:   my $result=&hashref2str(\%hash);
1.265     albertel 4560:   $result=~s/^__HASH_REF__//;
                   4561:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4562:   return $result;
                   4563: }
                   4564: 
                   4565: sub hashref2str {
                   4566:   my ($hashref)=@_;
1.265     albertel 4567:   my $result='__HASH_REF__';
1.800     albertel 4568:   foreach my $key (sort(keys(%$hashref))) {
                   4569:     if (ref($key) eq 'ARRAY') {
                   4570:       $result.=&arrayref2str($key).'=';
                   4571:     } elsif (ref($key) eq 'HASH') {
                   4572:       $result.=&hashref2str($key).'=';
                   4573:     } elsif (ref($key)) {
1.265     albertel 4574:       $result.='=';
1.800     albertel 4575:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4576:     } else {
1.1132    raeburn  4577: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4578:     }
                   4579: 
1.800     albertel 4580:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4581:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4582:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4583:       $result.=&hashref2str($hashref->{$key}).'&';
                   4584:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4585:        $result.='&';
1.800     albertel 4586:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4587:     } else {
1.800     albertel 4588:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4589:     }
                   4590:   }
1.168     albertel 4591:   $result=~s/\&$//;
1.265     albertel 4592:   $result .= '__END_HASH_REF__';
1.168     albertel 4593:   return $result;
                   4594: }
                   4595: 
                   4596: sub str2hash {
1.265     albertel 4597:     my ($string)=@_;
                   4598:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4599:     return %$hash;
                   4600: }
                   4601: 
                   4602: sub str2hashref {
1.168     albertel 4603:   my ($string) = @_;
1.265     albertel 4604: 
                   4605:   my %hash;
                   4606: 
                   4607:   if($string !~ /^__HASH_REF__/) {
                   4608:       if (! ($string eq '' || !defined($string))) {
                   4609: 	  $hash{'error'}='Not hash reference';
                   4610:       }
                   4611:       return (\%hash, $string);
                   4612:   }
                   4613: 
                   4614:   $string =~ s/^__HASH_REF__//;
                   4615: 
                   4616:   while($string !~ /^__END_HASH_REF__/) {
                   4617:       #key
                   4618:       my $key='';
                   4619:       if($string =~ /^__HASH_REF__/) {
                   4620:           ($key, $string)=&str2hashref($string);
                   4621:           if(defined($key->{'error'})) {
                   4622:               $hash{'error'}='Bad data';
                   4623:               return (\%hash, $string);
                   4624:           }
                   4625:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4626:           ($key, $string)=&str2arrayref($string);
                   4627:           if($key->[0] eq 'Array reference error') {
                   4628:               $hash{'error'}='Bad data';
                   4629:               return (\%hash, $string);
                   4630:           }
                   4631:       } else {
                   4632:           $string =~ s/^(.*?)=//;
1.267     albertel 4633: 	  $key=&unescape($1);
1.265     albertel 4634:       }
                   4635:       $string =~ s/^=//;
                   4636: 
                   4637:       #value
                   4638:       my $value='';
                   4639:       if($string =~ /^__HASH_REF__/) {
                   4640:           ($value, $string)=&str2hashref($string);
                   4641:           if(defined($value->{'error'})) {
                   4642:               $hash{'error'}='Bad data';
                   4643:               return (\%hash, $string);
                   4644:           }
                   4645:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4646:           ($value, $string)=&str2arrayref($string);
                   4647:           if($value->[0] eq 'Array reference error') {
                   4648:               $hash{'error'}='Bad data';
                   4649:               return (\%hash, $string);
                   4650:           }
                   4651:       } else {
                   4652: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4653:       }
                   4654:       $string =~ s/^&//;
                   4655: 
                   4656:       $hash{$key}=$value;
1.204     albertel 4657:   }
1.265     albertel 4658: 
                   4659:   $string =~ s/^__END_HASH_REF__//;
                   4660: 
                   4661:   return (\%hash, $string);
1.204     albertel 4662: }
                   4663: 
                   4664: sub str2array {
1.265     albertel 4665:     my ($string)=@_;
                   4666:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4667:     return @$array;
                   4668: }
                   4669: 
                   4670: sub str2arrayref {
1.204     albertel 4671:   my ($string) = @_;
1.265     albertel 4672:   my @array;
                   4673: 
                   4674:   if($string !~ /^__ARRAY_REF__/) {
                   4675:       if (! ($string eq '' || !defined($string))) {
                   4676: 	  $array[0]='Array reference error';
                   4677:       }
                   4678:       return (\@array, $string);
                   4679:   }
                   4680: 
                   4681:   $string =~ s/^__ARRAY_REF__//;
                   4682: 
                   4683:   while($string !~ /^__END_ARRAY_REF__/) {
                   4684:       my $value='';
                   4685:       if($string =~ /^__HASH_REF__/) {
                   4686:           ($value, $string)=&str2hashref($string);
                   4687:           if(defined($value->{'error'})) {
                   4688:               $array[0] ='Array reference error';
                   4689:               return (\@array, $string);
                   4690:           }
                   4691:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4692:           ($value, $string)=&str2arrayref($string);
                   4693:           if($value->[0] eq 'Array reference error') {
                   4694:               $array[0] ='Array reference error';
                   4695:               return (\@array, $string);
                   4696:           }
                   4697:       } else {
                   4698: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4699:       }
                   4700:       $string =~ s/^&//;
                   4701: 
                   4702:       push(@array, $value);
1.191     harris41 4703:   }
1.265     albertel 4704: 
                   4705:   $string =~ s/^__END_ARRAY_REF__//;
                   4706: 
                   4707:   return (\@array, $string);
1.168     albertel 4708: }
                   4709: 
1.167     albertel 4710: # -------------------------------------------------------------------Temp Store
                   4711: 
1.168     albertel 4712: sub tmpreset {
                   4713:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4714:   if (!$symb) {
                   4715:     $symb=&symbread();
1.620     albertel 4716:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4717:   }
                   4718:   $symb=escape($symb);
                   4719: 
1.620     albertel 4720:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4721:   $namespace=~s/\//\_/g;
                   4722:   $namespace=~s/\W//g;
                   4723: 
1.620     albertel 4724:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4725:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4726:   if ($domain eq 'public' && $stuname eq 'public') {
                   4727:       $stuname=$ENV{'REMOTE_ADDR'};
                   4728:   }
1.1117    foxr     4729:   my $path=LONCAPA::tempdir();
1.168     albertel 4730:   my %hash;
                   4731:   if (tie(%hash,'GDBM_File',
                   4732: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4733: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4734:     foreach my $key (keys(%hash)) {
1.180     albertel 4735:       if ($key=~ /:$symb/) {
1.168     albertel 4736: 	delete($hash{$key});
                   4737:       }
                   4738:     }
                   4739:   }
                   4740: }
                   4741: 
1.167     albertel 4742: sub tmpstore {
1.168     albertel 4743:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4744: 
                   4745:   if (!$symb) {
                   4746:     $symb=&symbread();
1.620     albertel 4747:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4748:   }
                   4749:   $symb=escape($symb);
                   4750: 
                   4751:   if (!$namespace) {
                   4752:     # I don't think we would ever want to store this for a course.
                   4753:     # it seems this will only be used if we don't have a course.
1.620     albertel 4754:     #$namespace=$env{'request.course.id'};
1.168     albertel 4755:     #if (!$namespace) {
1.620     albertel 4756:       $namespace=$env{'request.state'};
1.168     albertel 4757:     #}
                   4758:   }
                   4759:   $namespace=~s/\//\_/g;
                   4760:   $namespace=~s/\W//g;
1.620     albertel 4761:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4762:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4763:   if ($domain eq 'public' && $stuname eq 'public') {
                   4764:       $stuname=$ENV{'REMOTE_ADDR'};
                   4765:   }
1.168     albertel 4766:   my $now=time;
                   4767:   my %hash;
1.1117    foxr     4768:   my $path=LONCAPA::tempdir();
1.168     albertel 4769:   if (tie(%hash,'GDBM_File',
                   4770: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4771: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4772:     $hash{"version:$symb"}++;
                   4773:     my $version=$hash{"version:$symb"};
                   4774:     my $allkeys=''; 
                   4775:     foreach my $key (keys(%$storehash)) {
                   4776:       $allkeys.=$key.':';
1.591     albertel 4777:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4778:     }
                   4779:     $hash{"$version:$symb:timestamp"}=$now;
                   4780:     $allkeys.='timestamp';
                   4781:     $hash{"$version:keys:$symb"}=$allkeys;
                   4782:     if (untie(%hash)) {
                   4783:       return 'ok';
                   4784:     } else {
                   4785:       return "error:$!";
                   4786:     }
                   4787:   } else {
                   4788:     return "error:$!";
                   4789:   }
                   4790: }
1.167     albertel 4791: 
1.168     albertel 4792: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4793: 
1.168     albertel 4794: sub tmprestore {
                   4795:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4796: 
1.168     albertel 4797:   if (!$symb) {
                   4798:     $symb=&symbread();
1.620     albertel 4799:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4800:   }
                   4801:   $symb=escape($symb);
                   4802: 
1.620     albertel 4803:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4804: 
1.620     albertel 4805:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4806:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4807:   if ($domain eq 'public' && $stuname eq 'public') {
                   4808:       $stuname=$ENV{'REMOTE_ADDR'};
                   4809:   }
1.168     albertel 4810:   my %returnhash;
                   4811:   $namespace=~s/\//\_/g;
                   4812:   $namespace=~s/\W//g;
                   4813:   my %hash;
1.1117    foxr     4814:   my $path=LONCAPA::tempdir();
1.168     albertel 4815:   if (tie(%hash,'GDBM_File',
                   4816: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4817: 	  &GDBM_READER(),0640)) {
1.168     albertel 4818:     my $version=$hash{"version:$symb"};
                   4819:     $returnhash{'version'}=$version;
                   4820:     my $scope;
                   4821:     for ($scope=1;$scope<=$version;$scope++) {
                   4822:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4823:       my @keys=split(/:/,$vkeys);
                   4824:       my $key;
                   4825:       $returnhash{"$scope:keys"}=$vkeys;
                   4826:       foreach $key (@keys) {
1.591     albertel 4827: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4828: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4829:       }
                   4830:     }
1.168     albertel 4831:     if (!(untie(%hash))) {
                   4832:       return "error:$!";
                   4833:     }
                   4834:   } else {
                   4835:     return "error:$!";
                   4836:   }
                   4837:   return %returnhash;
1.167     albertel 4838: }
                   4839: 
1.9       www      4840: # ----------------------------------------------------------------------- Store
                   4841: 
                   4842: sub store {
1.124     www      4843:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4844:     my $home='';
                   4845: 
1.168     albertel 4846:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4847: 
1.213     www      4848:     $symb=&symbclean($symb);
1.122     albertel 4849:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4850: 
1.620     albertel 4851:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4852:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4853: 
                   4854:     &devalidate($symb,$stuname,$domain);
1.109     www      4855: 
                   4856:     $symb=escape($symb);
1.187     www      4857:     if (!$namespace) { 
1.620     albertel 4858:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4859:           return ''; 
                   4860:        } 
                   4861:     }
1.620     albertel 4862:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4863: 
                   4864:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4865:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4866: 
1.12      www      4867:     my $namevalue='';
1.800     albertel 4868:     foreach my $key (keys(%$storehash)) {
                   4869:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4870:     }
1.12      www      4871:     $namevalue=~s/\&$//;
1.187     www      4872:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4873:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4874: }
                   4875: 
1.47      www      4876: # -------------------------------------------------------------- Critical Store
                   4877: 
                   4878: sub cstore {
1.124     www      4879:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4880:     my $home='';
                   4881: 
1.168     albertel 4882:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4883: 
1.213     www      4884:     $symb=&symbclean($symb);
1.122     albertel 4885:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4886: 
1.620     albertel 4887:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4888:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4889: 
                   4890:     &devalidate($symb,$stuname,$domain);
1.109     www      4891: 
                   4892:     $symb=escape($symb);
1.187     www      4893:     if (!$namespace) { 
1.620     albertel 4894:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4895:           return ''; 
                   4896:        } 
                   4897:     }
1.620     albertel 4898:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4899: 
                   4900:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4901:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4902: 
1.47      www      4903:     my $namevalue='';
1.800     albertel 4904:     foreach my $key (keys(%$storehash)) {
                   4905:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4906:     }
1.47      www      4907:     $namevalue=~s/\&$//;
1.187     www      4908:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4909:     return critical
                   4910:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4911: }
                   4912: 
1.9       www      4913: # --------------------------------------------------------------------- Restore
                   4914: 
                   4915: sub restore {
1.124     www      4916:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4917:     my $home='';
                   4918: 
1.168     albertel 4919:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4920: 
1.122     albertel 4921:     if (!$symb) {
1.1172.2.26  raeburn  4922:         return if ($namespace eq 'courserequests');
                   4923:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4924:     } else {
1.1172.2.26  raeburn  4925:         unless ($namespace eq 'courserequests') {
                   4926:             $symb=&escape(&symbclean($symb));
                   4927:         }
1.122     albertel 4928:     }
1.188     www      4929:     if (!$namespace) { 
1.620     albertel 4930:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4931:           return ''; 
                   4932:        } 
                   4933:     }
1.620     albertel 4934:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4935:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4936:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4937:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4938: 
1.12      www      4939:     my %returnhash=();
1.800     albertel 4940:     foreach my $line (split(/\&/,$answer)) {
                   4941: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4942:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4943:     }
1.75      www      4944:     my $version;
                   4945:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4946:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4947:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4948:        }
1.75      www      4949:     }
1.13      www      4950:     return %returnhash;
1.34      www      4951: }
                   4952: 
                   4953: # ---------------------------------------------------------- Course Description
1.1118    foxr     4954: #
                   4955: #  
1.34      www      4956: 
                   4957: sub coursedescription {
1.731     albertel 4958:     my ($courseid,$args)=@_;
1.34      www      4959:     $courseid=~s/^\///;
1.49      www      4960:     $courseid=~s/\_/\//g;
1.34      www      4961:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4962:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4963:     my $normalid=$cdomain.'_'.$cnum;
                   4964:     # need to always cache even if we get errors otherwise we keep 
                   4965:     # trying and trying and trying to get the course description.
                   4966:     my %envhash=();
                   4967:     my %returnhash=();
1.731     albertel 4968:     
                   4969:     my $expiretime=600;
                   4970:     if ($env{'request.course.id'} eq $normalid) {
                   4971: 	$expiretime=120;
                   4972:     }
                   4973: 
                   4974:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4975:     if (!$args->{'freshen_cache'}
                   4976: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4977: 	foreach my $key (keys(%env)) {
                   4978: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4979: 	    my ($setting) = $1;
                   4980: 	    $returnhash{$setting} = $env{$key};
                   4981: 	}
                   4982: 	return %returnhash;
                   4983:     }
                   4984: 
1.1118    foxr     4985:     # get the data again
                   4986: 
1.731     albertel 4987:     if (!$args->{'one_time'}) {
                   4988: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4989:     }
1.811     albertel 4990: 
1.34      www      4991:     if ($chome ne 'no_host') {
1.302     albertel 4992:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4993:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4994: 	   my $username = $env{'user.name'}; # Defult username
                   4995: 	   if(defined $args->{'user'}) {
                   4996: 	       $username = $args->{'user'};
                   4997: 	   }
1.129     albertel 4998:            $returnhash{'home'}= $chome;
                   4999: 	   $returnhash{'domain'} = $cdomain;
                   5000: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5001:            if (!defined($returnhash{'type'})) {
                   5002:                $returnhash{'type'} = 'Course';
                   5003:            }
1.130     albertel 5004:            while (my ($name,$value) = each %returnhash) {
1.53      www      5005:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5006:            }
1.270     www      5007:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5008:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5009: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5010:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5011:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5012:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5013:        }
                   5014:     }
1.731     albertel 5015:     if (!$args->{'one_time'}) {
1.949     raeburn  5016: 	&appenv(\%envhash);
1.731     albertel 5017:     }
1.302     albertel 5018:     return %returnhash;
1.461     www      5019: }
                   5020: 
1.1080    raeburn  5021: sub update_released_required {
                   5022:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5023:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5024:         $cid = $env{'request.course.id'};
                   5025:         $cdom = $env{'course.'.$cid.'.domain'};
                   5026:         $cnum = $env{'course.'.$cid.'.num'};
                   5027:         $chome = $env{'course.'.$cid.'.home'};
                   5028:     }
                   5029:     if ($needsrelease) {
                   5030:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5031:         my $needsupdate;
                   5032:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5033:             $needsupdate = 1;
                   5034:         } else {
                   5035:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5036:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5037:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5038:                 $needsupdate = 1;
                   5039:             }
                   5040:         }
                   5041:         if ($needsupdate) {
                   5042:             my %needshash = (
                   5043:                              'internal.releaserequired' => $needsrelease,
                   5044:                             );
                   5045:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5046:             if ($putresult eq 'ok') {
                   5047:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5048:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5049:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5050:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5051:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5052:                 }
                   5053:             }
                   5054:         }
                   5055:     }
                   5056:     return;
                   5057: }
                   5058: 
1.461     www      5059: # -------------------------------------------------See if a user is privileged
                   5060: 
                   5061: sub privileged {
1.1172.2.23  raeburn  5062:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5063:     my $now = time;
1.1172.2.23  raeburn  5064:     my $roles;
                   5065:     if (ref($possroles) eq 'ARRAY') {
                   5066:         $roles = $possroles;
                   5067:     } else {
                   5068:         $roles = ['dc','su'];
                   5069:     }
                   5070:     if (ref($possdomains) eq 'ARRAY') {
                   5071:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5072:         foreach my $dom (@{$possdomains}) {
                   5073:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5074:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5075:                 foreach my $role (@{$roles}) {
                   5076:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5077:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5078:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5079:                             return 1 unless (($end && $end < $now) ||
                   5080:                                              ($start && $start > $now));
                   5081:                         }
                   5082:                     }
                   5083:                 }
                   5084:             }
                   5085:         }
                   5086:     } else {
                   5087:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5088:         my $now = time;
1.1170    droeschl 5089: 
1.1172.2.23  raeburn  5090:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5091:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5092:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5093:                 return 1 unless ($tend && $tend < $now)
                   5094:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5095:             }
1.1172.2.23  raeburn  5096:         }
                   5097:     }
1.461     www      5098:     return 0;
1.9       www      5099: }
1.1       albertel 5100: 
1.1172.2.23  raeburn  5101: sub privileged_by_domain {
                   5102:     my ($domains,$roles) = @_;
                   5103:     my %privileged = ();
                   5104:     my $cachetime = 60*60*24;
                   5105:     my $now = time;
                   5106:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5107:         return %privileged;
                   5108:     }
                   5109:     foreach my $dom (@{$domains}) {
                   5110:         next if (ref($privileged{$dom}) eq 'HASH');
                   5111:         my $needroles;
                   5112:         foreach my $role (@{$roles}) {
                   5113:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5114:             if (defined($cached)) {
                   5115:                 if (ref($result) eq 'HASH') {
                   5116:                     $privileged{$dom}{$role} = $result;
                   5117:                 }
                   5118:             } else {
                   5119:                 $needroles = 1;
                   5120:             }
                   5121:         }
                   5122:         if ($needroles) {
                   5123:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5124:             $privileged{$dom} = {};
                   5125:             foreach my $server (keys(%dompersonnel)) {
                   5126:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5127:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5128:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5129:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5130:                         next if ($end && $end < $now);
                   5131:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5132:                             $dompersonnel{$server}{$item};
                   5133:                     }
                   5134:                 }
                   5135:             }
                   5136:             if (ref($privileged{$dom}) eq 'HASH') {
                   5137:                 foreach my $role (@{$roles}) {
                   5138:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5139:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5140:                     } else {
                   5141:                         my %hash = ();
                   5142:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5143:                     }
                   5144:                 }
                   5145:             }
                   5146:         }
                   5147:     }
                   5148:     return %privileged;
                   5149: }
                   5150: 
1.103     harris41 5151: # -------------------------------------------------------- Get user privileges
1.11      www      5152: 
                   5153: sub rolesinit {
1.1169    droeschl 5154:     my ($domain, $username) = @_;
                   5155:     my %userroles = ('user.login.time' => time);
                   5156:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5157: 
                   5158:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5159:     # also, blocking can be triggered by an activating timer
                   5160:     # it's saved in the user's %env.
                   5161:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5162:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5163:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5164:         %timerintchk, %timerintenv);
                   5165: 
1.1162    raeburn  5166:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5167:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5168:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5169:     }
1.1169    droeschl 5170: 
1.1162    raeburn  5171:     foreach my $key (keys(%timerinterval)) {
                   5172:         my ($cid,$rest) = split(/\0/,$key);
                   5173:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5174:     }
1.1169    droeschl 5175: 
1.11      www      5176:     my %allroles=();
1.1162    raeburn  5177:     my %allgroups=();
1.11      www      5178: 
1.1169    droeschl 5179:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5180:         my $role = $rolesdump{$area};
                   5181:         $area =~ s/\_\w\w$//;
                   5182: 
                   5183:         my ($trole, $tend, $tstart, $group_privs);
                   5184: 
                   5185:         if ($role =~ /^cr/) {
                   5186:         # Custom role, defined by a user 
                   5187:         # e.g., user.role.cr/msu/smith/mynewrole
                   5188:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5189:                 $trole = $1;
                   5190:                 ($tend, $tstart) = split('_', $2);
                   5191:             } else {
                   5192:                 $trole = $role;
                   5193:             }
                   5194:         } elsif ($role =~ m|^gr/|) {
                   5195:         # Role of member in a group, defined within a course/community
                   5196:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5197:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5198:             next if $tstart eq '-1';
                   5199:             ($trole, $group_privs) = split(/\//, $trole);
                   5200:             $group_privs = &unescape($group_privs);
                   5201:         } else {
                   5202:         # Just a normal role, defined in roles.tab
                   5203:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5204:         }
                   5205: 
                   5206:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5207:                  $username);
                   5208:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5209: 
                   5210:         # role expired or not available yet?
                   5211:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5212:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5213: 
                   5214:         next if $area eq '' or $trole eq '';
                   5215: 
                   5216:         my $spec = "$trole.$area";
                   5217:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5218: 
                   5219:         if ($trole =~ /^cr\//) {
                   5220:         # Custom role, defined by a user
                   5221:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5222:         } elsif ($trole eq 'gr') {
                   5223:         # Role of a member in a group, defined within a course/community
                   5224:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5225:             next;
                   5226:         } else {
                   5227:         # Normal role, defined in roles.tab
                   5228:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5229:         }
                   5230: 
                   5231:         my $cid = $tdomain.'_'.$trest;
                   5232:         unless ($firstaccchk{$cid}) {
                   5233:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5234:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5235:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5236:                         $coursetimerstarts{$cid}{$item}; 
                   5237:                 }
                   5238:             }
                   5239:             $firstaccchk{$cid} = 1;
                   5240:         }
                   5241:         unless ($timerintchk{$cid}) {
                   5242:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5243:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5244:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5245:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5246:                 }
1.12      www      5247:             }
1.1169    droeschl 5248:             $timerintchk{$cid} = 1;
1.191     harris41 5249:         }
1.11      www      5250:     }
1.1169    droeschl 5251: 
                   5252:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5253:         \%allroles, \%allgroups);
                   5254:     $env{'user.adv'} = $userroles{'user.adv'};
                   5255: 
1.1162    raeburn  5256:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5257: }
                   5258: 
1.567     raeburn  5259: sub set_arearole {
1.1172.2.19  raeburn  5260:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5261:     unless ($nolog) {
1.567     raeburn  5262: # log the associated role with the area
1.1172.2.19  raeburn  5263:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5264:     }
1.743     albertel 5265:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5266: }
                   5267: 
                   5268: sub custom_roleprivs {
                   5269:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5270:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5271:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5272:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5273:         my ($rdummy,$roledef)=
                   5274:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5275:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5276:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5277:             if (defined($syspriv)) {
1.1043    raeburn  5278:                 if ($trest =~ /^$match_community$/) {
                   5279:                     $syspriv =~ s/bre\&S//; 
                   5280:                 }
1.567     raeburn  5281:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5282:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5283:             }
                   5284:             if ($tdomain ne '') {
                   5285:                 if (defined($dompriv)) {
                   5286:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5287:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5288:                 }
                   5289:                 if (($trest ne '') && (defined($coursepriv))) {
                   5290:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5291:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5292:                 }
                   5293:             }
                   5294:         }
                   5295:     }
                   5296: }
                   5297: 
1.678     raeburn  5298: sub group_roleprivs {
                   5299:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5300:     my $access = 1;
                   5301:     my $now = time;
                   5302:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5303:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5304:     if ($access) {
1.811     albertel 5305:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5306:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5307:     }
                   5308: }
1.567     raeburn  5309: 
                   5310: sub standard_roleprivs {
                   5311:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5312:     if (defined($pr{$trole.':s'})) {
                   5313:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5314:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5315:     }
                   5316:     if ($tdomain ne '') {
                   5317:         if (defined($pr{$trole.':d'})) {
                   5318:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5319:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5320:         }
                   5321:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5322:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5323:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5324:         }
                   5325:     }
                   5326: }
                   5327: 
                   5328: sub set_userprivs {
1.1064    raeburn  5329:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5330:     my $author=0;
                   5331:     my $adv=0;
1.678     raeburn  5332:     my %grouproles = ();
                   5333:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5334:         my @groupkeys; 
1.1000    raeburn  5335:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5336:             push(@groupkeys,$role);
                   5337:         }
                   5338:         if (ref($groups_roles) eq 'HASH') {
                   5339:             foreach my $key (keys(%{$groups_roles})) {
                   5340:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5341:                     push(@groupkeys,$key);
                   5342:                 }
                   5343:             }
                   5344:         }
                   5345:         if (@groupkeys > 0) {
                   5346:             foreach my $role (@groupkeys) {
                   5347:                 my ($trole,$area,$sec,$extendedarea);
                   5348:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5349:                     $trole = $1;
                   5350:                     $area = $2;
                   5351:                     $sec = $3;
                   5352:                     $extendedarea = $area.$sec;
                   5353:                     if (exists($$allgroups{$area})) {
                   5354:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5355:                             my $spec = $trole.'.'.$extendedarea;
                   5356:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5357:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5358:                         }
1.678     raeburn  5359:                     }
                   5360:                 }
                   5361:             }
                   5362:         }
                   5363:     }
1.800     albertel 5364:     foreach my $group (keys(%grouproles)) {
                   5365:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5366:     }
1.800     albertel 5367:     foreach my $role (keys(%{$allroles})) {
                   5368:         my %thesepriv;
1.941     raeburn  5369:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5370:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5371:             if ($item ne '') {
                   5372:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5373:                 if ($restrictions eq '') {
                   5374:                     $thesepriv{$privilege}='F';
                   5375:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5376:                     $thesepriv{$privilege}.=$restrictions;
                   5377:                 }
                   5378:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5379:             }
                   5380:         }
                   5381:         my $thesestr='';
1.1104    raeburn  5382:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5383: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5384: 	}
                   5385:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5386:     }
                   5387:     return ($author,$adv);
                   5388: }
                   5389: 
1.994     raeburn  5390: sub role_status {
1.1104    raeburn  5391:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5392:     my @pwhere = ();
                   5393:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5394:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5395:         unless (!defined($$role) || $$role eq '') {
                   5396:             $$where=join('.',@pwhere);
                   5397:             $$trolecode=$$role.'.'.$$where;
                   5398:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5399:             $$tstatus='is';
1.1104    raeburn  5400:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5401:                 $$tstatus='future';
1.1034    raeburn  5402:                 if ($$tstart<$now) {
                   5403:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5404:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5405:                             my (%allroles,%allgroups,$group_privs,
                   5406:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5407:                             my %userroles = (
                   5408:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5409:                             );
1.1064    raeburn  5410:                             @rolecodes = ('cm'); 
1.1002    raeburn  5411:                             my $spec=$$role.'.'.$$where;
                   5412:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5413:                             if ($$role =~ /^cr\//) {
                   5414:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5415:                                 push(@rolecodes,'cr');
1.1002    raeburn  5416:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5417:                                 push(@rolecodes,$$role);
1.1002    raeburn  5418:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5419:                                                     $env{'user.name'});
1.1064    raeburn  5420:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5421:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5422:                                 $group_privs = &unescape($group_privs);
                   5423:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5424:                                 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  5425:                                 &get_groups_roles($tdomain,$trest,
                   5426:                                                   \%course_roles,\@rolecodes,
                   5427:                                                   \%groups_roles);
1.1002    raeburn  5428:                             } else {
1.1064    raeburn  5429:                                 push(@rolecodes,$$role);
1.1002    raeburn  5430:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5431:                             }
1.1064    raeburn  5432:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5433:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5434:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5435:                         }
                   5436:                     }
1.1034    raeburn  5437:                     $$tstatus = 'is';
1.1002    raeburn  5438:                 }
1.994     raeburn  5439:             }
                   5440:             if ($$tend) {
1.1104    raeburn  5441:                 if ($$tend<$update) {
1.994     raeburn  5442:                     $$tstatus='expired';
                   5443:                 } elsif ($$tend<$now) {
                   5444:                     $$tstatus='will_not';
                   5445:                 }
                   5446:             }
                   5447:         }
                   5448:     }
                   5449: }
                   5450: 
1.1104    raeburn  5451: sub get_groups_roles {
                   5452:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5453:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5454:                   (ref($rolecodes) eq 'ARRAY') && 
                   5455:                   (ref($groups_roles) eq 'HASH')); 
                   5456:     if (keys(%{$cdom_courseroles}) > 0) {
                   5457:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5458:         if ($cdom ne '' && $cnum ne '') {
                   5459:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5460:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5461:                     my $crsrole = $1;
                   5462:                     my $crssec = $2;
                   5463:                     if ($crsrole =~ /^cr/) {
                   5464:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5465:                             push(@{$rolecodes},'cr');
                   5466:                         }
                   5467:                     } else {
                   5468:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5469:                             push(@{$rolecodes},$crsrole);
                   5470:                         }
                   5471:                     }
                   5472:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5473:                     if ($crssec ne '') {
                   5474:                         $rolekey .= "/$crssec";
                   5475:                     }
                   5476:                     $rolekey .= './';
                   5477:                     $groups_roles->{$rolekey} = $rolecodes;
                   5478:                 }
                   5479:             }
                   5480:         }
                   5481:     }
                   5482:     return;
                   5483: }
                   5484: 
                   5485: sub delete_env_groupprivs {
                   5486:     my ($where,$courseroles,$possroles) = @_;
                   5487:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5488:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5489:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5490:         %{$courseroles->{$udom}} =
                   5491:             &get_my_roles('','','userroles',['active'],
                   5492:                           $possroles,[$udom],1);
                   5493:     }
                   5494:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5495:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5496:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5497:             my $area = '/'.$cdom.'/'.$cnum;
                   5498:             my $privkey = "user.priv.$crsrole.$area";
                   5499:             if ($crssec ne '') {
                   5500:                 $privkey .= '/'.$crssec;
                   5501:             }
                   5502:             $privkey .= ".$area/$group";
                   5503:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5504:         }
                   5505:     }
                   5506:     return;
                   5507: }
                   5508: 
1.994     raeburn  5509: sub check_adhoc_privs {
1.1104    raeburn  5510:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5511:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5512:     my $setprivs;
1.994     raeburn  5513:     if ($env{$cckey}) {
                   5514:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5515:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5516:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5517:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5518:             $setprivs = 1;
1.994     raeburn  5519:         }
                   5520:     } else {
1.1088    raeburn  5521:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5522:         $setprivs = 1;
1.994     raeburn  5523:     }
1.1172.2.9  raeburn  5524:     return $setprivs;
1.994     raeburn  5525: }
                   5526: 
                   5527: sub set_adhoc_privileges {
                   5528: # role can be cc or ca
1.1088    raeburn  5529:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5530:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5531:     my $spec = $role.'.'.$area;
                   5532:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5533:                                   $env{'user.name'},1);
1.994     raeburn  5534:     my %ccrole = ();
                   5535:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5536:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5537:     &appenv(\%userroles,[$role,'cm']);
                   5538:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5539:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5540:         &appenv( {'request.role'        => $spec,
                   5541:                   'request.role.domain' => $dcdom,
                   5542:                   'request.course.sec'  => ''
                   5543:                  }
                   5544:                );
                   5545:         my $tadv=0;
                   5546:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5547:         &appenv({'request.role.adv'    => $tadv});
                   5548:     }
1.994     raeburn  5549: }
                   5550: 
1.12      www      5551: # --------------------------------------------------------------- get interface
                   5552: 
                   5553: sub get {
1.131     albertel 5554:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5555:    my $items='';
1.800     albertel 5556:    foreach my $item (@$storearr) {
                   5557:        $items.=&escape($item).'&';
1.191     harris41 5558:    }
1.12      www      5559:    $items=~s/\&$//;
1.620     albertel 5560:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5561:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5562:    my $uhome=&homeserver($uname,$udomain);
                   5563: 
1.133     albertel 5564:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5565:    my @pairs=split(/\&/,$rep);
1.273     albertel 5566:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5567:      return @pairs;
                   5568:    }
1.15      www      5569:    my %returnhash=();
1.42      www      5570:    my $i=0;
1.800     albertel 5571:    foreach my $item (@$storearr) {
                   5572:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5573:       $i++;
1.191     harris41 5574:    }
1.15      www      5575:    return %returnhash;
1.27      www      5576: }
                   5577: 
                   5578: # --------------------------------------------------------------- del interface
                   5579: 
                   5580: sub del {
1.133     albertel 5581:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5582:    my $items='';
1.800     albertel 5583:    foreach my $item (@$storearr) {
                   5584:        $items.=&escape($item).'&';
1.191     harris41 5585:    }
1.984     neumanie 5586: 
1.27      www      5587:    $items=~s/\&$//;
1.620     albertel 5588:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5589:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5590:    my $uhome=&homeserver($uname,$udomain);
                   5591:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5592: }
                   5593: 
                   5594: # -------------------------------------------------------------- dump interface
                   5595: 
1.1172.2.22  raeburn  5596: sub unserialize {
                   5597:     my ($rep, $escapedkeys) = @_;
                   5598: 
                   5599:     return {} if $rep =~ /^error/;
                   5600: 
                   5601:     my %returnhash=();
                   5602:     foreach my $item (split(/\&/,$rep)) {
                   5603:         my ($key, $value) = split(/=/, $item, 2);
                   5604:         $key = unescape($key) unless $escapedkeys;
                   5605:         next if $key =~ /^error: 2 /;
                   5606:         $returnhash{$key} = &thaw_unescape($value);
                   5607:     }
                   5608:     return \%returnhash;
                   5609: }
                   5610: 
                   5611: # see Lond::dump_with_regexp
                   5612: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5613: sub dump {
1.1172.2.22  raeburn  5614:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5615:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5616:     if (!$uname) { $uname=$env{'user.name'}; }
                   5617:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5618: 
1.1172.2.22  raeburn  5619:     my $reply;
                   5620:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5621:         # user is hosted on this machine
                   5622:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5623:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5624:         return %{&unserialize($reply, $escapedkeys)};
                   5625:     }
1.755     albertel 5626:     if ($regexp) {
                   5627: 	$regexp=&escape($regexp);
                   5628:     } else {
                   5629: 	$regexp='.';
                   5630:     }
1.1166    raeburn  5631:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5632:     my @pairs=split(/\&/,$rep);
                   5633:     my %returnhash=();
1.1098    foxr     5634:     if (!($rep =~ /^error/ )) {
                   5635: 	foreach my $item (@pairs) {
                   5636: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5637:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5638: 	    next if ($key =~ /^error: 2 /);
                   5639: 	    $returnhash{$key}=&thaw_unescape($value);
                   5640: 	}
1.755     albertel 5641:     }
                   5642:     return %returnhash;
1.407     www      5643: }
                   5644: 
1.1098    foxr     5645: 
1.717     albertel 5646: # --------------------------------------------------------- dumpstore interface
                   5647: 
                   5648: sub dumpstore {
                   5649:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5650:    # same as dump but keys must be escaped. They may contain colon separated
                   5651:    # lists of values that may themself contain colons (e.g. symbs).
                   5652:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5653: }
                   5654: 
1.407     www      5655: # -------------------------------------------------------------- keys interface
                   5656: 
                   5657: sub getkeys {
                   5658:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5659:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5660:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5661:    my $uhome=&homeserver($uname,$udomain);
                   5662:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5663:    my @keyarray=();
1.800     albertel 5664:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5665:       next if ($key =~ /^error: 2 /);
1.800     albertel 5666:       push(@keyarray,&unescape($key));
1.407     www      5667:    }
                   5668:    return @keyarray;
1.318     matthew  5669: }
                   5670: 
1.319     matthew  5671: # --------------------------------------------------------------- currentdump
                   5672: sub currentdump {
1.328     matthew  5673:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5674:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5675:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5676:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5677:    my $uhome = &homeserver($sname,$sdom);
                   5678:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5679:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5680:    #
1.318     matthew  5681:    my %returnhash=();
1.319     matthew  5682:    #
                   5683:    if ($rep eq "unknown_cmd") { 
                   5684:        # an old lond will not know currentdump
                   5685:        # Do a dump and make it look like a currentdump
1.822     albertel 5686:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5687:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5688:        my %hash = @tmp;
                   5689:        @tmp=();
1.424     matthew  5690:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5691:    } else {
                   5692:        my @pairs=split(/\&/,$rep);
1.800     albertel 5693:        foreach my $pair (@pairs) {
                   5694:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5695:            my ($symb,$param) = split(/:/,$key);
                   5696:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5697:                                                         &thaw_unescape($value);
1.319     matthew  5698:        }
1.191     harris41 5699:    }
1.12      www      5700:    return %returnhash;
1.424     matthew  5701: }
                   5702: 
                   5703: sub convert_dump_to_currentdump{
                   5704:     my %hash = %{shift()};
                   5705:     my %returnhash;
                   5706:     # Code ripped from lond, essentially.  The only difference
                   5707:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5708:     # we might run in to problems with parameter names =~ /^v\./
                   5709:     while (my ($key,$value) = each(%hash)) {
                   5710:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5711: 	$symb  = &unescape($symb);
                   5712: 	$param = &unescape($param);
1.424     matthew  5713:         next if ($v eq 'version' || $symb eq 'keys');
                   5714:         next if (exists($returnhash{$symb}) &&
                   5715:                  exists($returnhash{$symb}->{$param}) &&
                   5716:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5717:         $returnhash{$symb}->{$param}=$value;
                   5718:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5719:     }
                   5720:     #
                   5721:     # Remove all of the keys in the hashes which keep track of
                   5722:     # the version of the parameter.
                   5723:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5724:         # use a foreach because we are going to delete from the hash.
                   5725:         foreach my $key (keys(%$param_hash)) {
                   5726:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5727:         }
                   5728:     }
                   5729:     return \%returnhash;
1.12      www      5730: }
                   5731: 
1.627     albertel 5732: # ------------------------------------------------------ critical inc interface
                   5733: 
                   5734: sub cinc {
                   5735:     return &inc(@_,'critical');
                   5736: }
                   5737: 
1.449     matthew  5738: # --------------------------------------------------------------- inc interface
                   5739: 
                   5740: sub inc {
1.627     albertel 5741:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5742:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5743:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5744:     my $uhome=&homeserver($uname,$udomain);
                   5745:     my $items='';
                   5746:     if (! ref($store)) {
                   5747:         # got a single value, so use that instead
                   5748:         $items = &escape($store).'=&';
                   5749:     } elsif (ref($store) eq 'SCALAR') {
                   5750:         $items = &escape($$store).'=&';        
                   5751:     } elsif (ref($store) eq 'ARRAY') {
                   5752:         $items = join('=&',map {&escape($_);} @{$store});
                   5753:     } elsif (ref($store) eq 'HASH') {
                   5754:         while (my($key,$value) = each(%{$store})) {
                   5755:             $items.= &escape($key).'='.&escape($value).'&';
                   5756:         }
                   5757:     }
                   5758:     $items=~s/\&$//;
1.627     albertel 5759:     if ($critical) {
                   5760: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5761:     } else {
                   5762: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5763:     }
1.449     matthew  5764: }
                   5765: 
1.12      www      5766: # --------------------------------------------------------------- put interface
                   5767: 
                   5768: sub put {
1.134     albertel 5769:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5770:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5771:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5772:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5773:    my $items='';
1.800     albertel 5774:    foreach my $item (keys(%$storehash)) {
                   5775:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5776:    }
1.12      www      5777:    $items=~s/\&$//;
1.134     albertel 5778:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5779: }
                   5780: 
1.631     albertel 5781: # ------------------------------------------------------------ newput interface
                   5782: 
                   5783: sub newput {
                   5784:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5785:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5786:    if (!$uname) { $uname=$env{'user.name'}; }
                   5787:    my $uhome=&homeserver($uname,$udomain);
                   5788:    my $items='';
                   5789:    foreach my $key (keys(%$storehash)) {
                   5790:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5791:    }
                   5792:    $items=~s/\&$//;
                   5793:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5794: }
                   5795: 
                   5796: # ---------------------------------------------------------  putstore interface
                   5797: 
1.524     raeburn  5798: sub putstore {
1.715     albertel 5799:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5800:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5801:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5802:    my $uhome=&homeserver($uname,$udomain);
                   5803:    my $items='';
1.715     albertel 5804:    foreach my $key (keys(%$storehash)) {
                   5805:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5806:    }
1.715     albertel 5807:    $items=~s/\&$//;
1.716     albertel 5808:    my $esc_symb=&escape($symb);
                   5809:    my $esc_v=&escape($version);
1.715     albertel 5810:    my $reply =
1.716     albertel 5811:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5812: 	      $uhome);
                   5813:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5814:        # gfall back to way things use to be done
1.715     albertel 5815:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5816: 			    $uname);
1.524     raeburn  5817:    }
1.715     albertel 5818:    return $reply;
                   5819: }
                   5820: 
                   5821: sub old_putstore {
1.716     albertel 5822:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5823:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5824:     if (!$uname) { $uname=$env{'user.name'}; }
                   5825:     my $uhome=&homeserver($uname,$udomain);
                   5826:     my %newstorehash;
1.800     albertel 5827:     foreach my $item (keys(%$storehash)) {
                   5828: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5829: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5830:     }
                   5831:     my $items='';
                   5832:     my %allitems = ();
1.800     albertel 5833:     foreach my $item (keys(%newstorehash)) {
                   5834: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5835: 	    my $key = $1.':keys:'.$2;
                   5836: 	    $allitems{$key} .= $3.':';
                   5837: 	}
1.800     albertel 5838: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5839:     }
1.800     albertel 5840:     foreach my $item (keys(%allitems)) {
                   5841: 	$allitems{$item} =~ s/\:$//;
                   5842: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5843:     }
                   5844:     $items=~s/\&$//;
                   5845:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5846: }
                   5847: 
1.47      www      5848: # ------------------------------------------------------ critical put interface
                   5849: 
                   5850: sub cput {
1.134     albertel 5851:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5853:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5854:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5855:    my $items='';
1.800     albertel 5856:    foreach my $item (keys(%$storehash)) {
                   5857:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5858:    }
1.47      www      5859:    $items=~s/\&$//;
1.134     albertel 5860:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5861: }
                   5862: 
                   5863: # -------------------------------------------------------------- eget interface
                   5864: 
                   5865: sub eget {
1.133     albertel 5866:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5867:    my $items='';
1.800     albertel 5868:    foreach my $item (@$storearr) {
                   5869:        $items.=&escape($item).'&';
1.191     harris41 5870:    }
1.12      www      5871:    $items=~s/\&$//;
1.620     albertel 5872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5873:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5874:    my $uhome=&homeserver($uname,$udomain);
                   5875:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5876:    my @pairs=split(/\&/,$rep);
                   5877:    my %returnhash=();
1.42      www      5878:    my $i=0;
1.800     albertel 5879:    foreach my $item (@$storearr) {
                   5880:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5881:       $i++;
1.191     harris41 5882:    }
1.12      www      5883:    return %returnhash;
                   5884: }
                   5885: 
1.667     albertel 5886: # ------------------------------------------------------------ tmpput interface
                   5887: sub tmpput {
1.802     raeburn  5888:     my ($storehash,$server,$context)=@_;
1.667     albertel 5889:     my $items='';
1.800     albertel 5890:     foreach my $item (keys(%$storehash)) {
                   5891: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5892:     }
                   5893:     $items=~s/\&$//;
1.802     raeburn  5894:     if (defined($context)) {
                   5895:         $items .= ':'.&escape($context);
                   5896:     }
1.667     albertel 5897:     return &reply("tmpput:$items",$server);
                   5898: }
                   5899: 
                   5900: # ------------------------------------------------------------ tmpget interface
                   5901: sub tmpget {
1.688     albertel 5902:     my ($token,$server)=@_;
                   5903:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5904:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5905:     my %returnhash;
                   5906:     foreach my $item (split(/\&/,$rep)) {
                   5907: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5908:         next if ($key =~ /^error: 2 /);
1.667     albertel 5909: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5910:     }
                   5911:     return %returnhash;
                   5912: }
                   5913: 
1.1113    raeburn  5914: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5915: sub tmpdel {
                   5916:     my ($token,$server)=@_;
                   5917:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5918:     return &reply("tmpdel:$token",$server);
                   5919: }
                   5920: 
1.1172.2.13  raeburn  5921: # ------------------------------------------------------------ get_timebased_id
                   5922: 
                   5923: sub get_timebased_id {
                   5924:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5925:         $maxtries) = @_;
                   5926:     my ($newid,$error,$dellock);
                   5927:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5928:         return ('','ok','invalid call to get suffix');
                   5929:     }
                   5930: 
                   5931: # set defaults for any optional args for which values were not supplied
                   5932:     if ($who eq '') {
                   5933:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5934:     }
                   5935:     if (!$locktries) {
                   5936:         $locktries = 3;
                   5937:     }
                   5938:     if (!$maxtries) {
                   5939:         $maxtries = 10;
                   5940:     }
                   5941: 
                   5942:     if (($cdom eq '') || ($cnum eq '')) {
                   5943:         if ($env{'request.course.id'}) {
                   5944:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5945:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5946:         }
                   5947:         if (($cdom eq '') || ($cnum eq '')) {
                   5948:             return ('','ok','call to get suffix not in course context');
                   5949:         }
                   5950:     }
                   5951: 
                   5952: # construct locking item
                   5953:     my $lockhash = {
                   5954:                       $prefix."\0".'locked_'.$keyid => $who,
                   5955:                    };
                   5956:     my $tries = 0;
                   5957: 
                   5958: # attempt to get lock on nohist_$namespace file
                   5959:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5960:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5961:         $tries ++;
                   5962:         sleep 1;
                   5963:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5964:     }
                   5965: 
                   5966: # attempt to get unique identifier, based on current timestamp
                   5967:     if ($gotlock eq 'ok') {
                   5968:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5969:         my $id = time;
                   5970:         $newid = $id;
                   5971:         my $idtries = 0;
                   5972:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5973:             if ($idtype eq 'concat') {
                   5974:                 $newid = $id.$idtries;
                   5975:             } else {
                   5976:                 $newid ++;
                   5977:             }
                   5978:             $idtries ++;
                   5979:         }
                   5980:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5981:             my %new_item =  (
                   5982:                               $prefix."\0".$newid => $who,
                   5983:                             );
                   5984:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5985:                                                  $cdom,$cnum);
                   5986:             if ($putresult ne 'ok') {
                   5987:                 undef($newid);
                   5988:                 $error = 'error saving new item: '.$putresult;
                   5989:             }
                   5990:         } else {
                   5991:              $error = ('error: no unique suffix available for the new item ');
                   5992:         }
                   5993: #  remove lock
                   5994:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5995:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5996:     } else {
                   5997:         $error = "error: could not obtain lockfile\n";
                   5998:         $dellock = 'ok';
                   5999:     }
                   6000:     return ($newid,$dellock,$error);
                   6001: }
                   6002: 
1.765     albertel 6003: # -------------------------------------------------- portfolio access checking
                   6004: 
                   6005: sub portfolio_access {
1.766     albertel 6006:     my ($requrl) = @_;
1.765     albertel 6007:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6008:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6009:     if ($result) {
                   6010:         my %setters;
                   6011:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6012:             my ($startblock,$endblock) =
                   6013:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6014:             if ($startblock && $endblock) {
                   6015:                 return 'B';
                   6016:             }
                   6017:         } else {
                   6018:             my ($startblock,$endblock) =
                   6019:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6020:             if ($startblock && $endblock) {
                   6021:                 return 'B';
                   6022:             }
                   6023:         }
                   6024:     }
1.765     albertel 6025:     if ($result eq 'ok') {
1.766     albertel 6026:        return 'F';
1.765     albertel 6027:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6028:        return 'A';
1.765     albertel 6029:     }
1.766     albertel 6030:     return '';
1.765     albertel 6031: }
                   6032: 
                   6033: sub get_portfolio_access {
1.767     albertel 6034:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6035: 
                   6036:     if (!ref($access_hash)) {
                   6037: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6038: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6039: 						   $file_name);
                   6040: 	$access_hash = $access_controls{$file_name};
                   6041:     }
                   6042: 
1.765     albertel 6043:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6044:     my $now = time;
                   6045:     if (ref($access_hash) eq 'HASH') {
                   6046:         foreach my $key (keys(%{$access_hash})) {
                   6047:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6048:             if ($start > $now) {
                   6049:                 next;
                   6050:             }
                   6051:             if ($end && $end<$now) {
                   6052:                 next;
                   6053:             }
                   6054:             if ($scope eq 'public') {
                   6055:                 $public = $key;
                   6056:                 last;
                   6057:             } elsif ($scope eq 'guest') {
                   6058:                 $guest = $key;
                   6059:             } elsif ($scope eq 'domains') {
                   6060:                 push(@domains,$key);
                   6061:             } elsif ($scope eq 'users') {
                   6062:                 push(@users,$key);
                   6063:             } elsif ($scope eq 'course') {
                   6064:                 push(@courses,$key);
                   6065:             } elsif ($scope eq 'group') {
                   6066:                 push(@groups,$key);
                   6067:             }
                   6068:         }
                   6069:         if ($public) {
                   6070:             return 'ok';
                   6071:         }
                   6072:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6073:             if ($guest) {
                   6074:                 return $guest;
                   6075:             }
                   6076:         } else {
                   6077:             if (@domains > 0) {
                   6078:                 foreach my $domkey (@domains) {
                   6079:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6080:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6081:                             return 'ok';
                   6082:                         }
                   6083:                     }
                   6084:                 }
                   6085:             }
                   6086:             if (@users > 0) {
                   6087:                 foreach my $userkey (@users) {
1.865     raeburn  6088:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6089:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6090:                             if (ref($item) eq 'HASH') {
                   6091:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6092:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6093:                                     return 'ok';
                   6094:                                 }
                   6095:                             }
                   6096:                         }
                   6097:                     } 
1.765     albertel 6098:                 }
                   6099:             }
                   6100:             my %roleshash;
                   6101:             my @courses_and_groups = @courses;
                   6102:             push(@courses_and_groups,@groups); 
                   6103:             if (@courses_and_groups > 0) {
                   6104:                 my (%allgroups,%allroles); 
                   6105:                 my ($start,$end,$role,$sec,$group);
                   6106:                 foreach my $envkey (%env) {
1.1060    raeburn  6107:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6108:                         my $cid = $2.'_'.$3; 
                   6109:                         if ($1 eq 'gr') {
                   6110:                             $group = $4;
                   6111:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6112:                         } else {
                   6113:                             if ($4 eq '') {
                   6114:                                 $sec = 'none';
                   6115:                             } else {
                   6116:                                 $sec = $4;
                   6117:                             }
                   6118:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6119:                         }
1.811     albertel 6120:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6121:                         my $cid = $2.'_'.$3;
                   6122:                         if ($4 eq '') {
                   6123:                             $sec = 'none';
                   6124:                         } else {
                   6125:                             $sec = $4;
                   6126:                         }
                   6127:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6128:                     }
                   6129:                 }
                   6130:                 if (keys(%allroles) == 0) {
                   6131:                     return;
                   6132:                 }
                   6133:                 foreach my $key (@courses_and_groups) {
                   6134:                     my %content = %{$$access_hash{$key}};
                   6135:                     my $cnum = $content{'number'};
                   6136:                     my $cdom = $content{'domain'};
                   6137:                     my $cid = $cdom.'_'.$cnum;
                   6138:                     if (!exists($allroles{$cid})) {
                   6139:                         next;
                   6140:                     }    
                   6141:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6142:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6143:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6144:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6145:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6146:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6147:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6148:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6149:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6150:                                         if (grep/^all$/,@sections) {
                   6151:                                             return 'ok';
                   6152:                                         } else {
                   6153:                                             if (grep/^$sec$/,@sections) {
                   6154:                                                 return 'ok';
                   6155:                                             }
                   6156:                                         }
                   6157:                                     }
                   6158:                                 }
                   6159:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6160:                                     if (grep/^none$/,@groups) {
                   6161:                                         return 'ok';
                   6162:                                     }
                   6163:                                 } else {
                   6164:                                     if (grep/^all$/,@groups) {
                   6165:                                         return 'ok';
                   6166:                                     } 
                   6167:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6168:                                         if (grep/^$group$/,@groups) {
                   6169:                                             return 'ok';
                   6170:                                         }
                   6171:                                     }
                   6172:                                 } 
                   6173:                             }
                   6174:                         }
                   6175:                     }
                   6176:                 }
                   6177:             }
                   6178:             if ($guest) {
                   6179:                 return $guest;
                   6180:             }
                   6181:         }
                   6182:     }
                   6183:     return;
                   6184: }
                   6185: 
                   6186: sub course_group_datechecker {
                   6187:     my ($dates,$now,$status) = @_;
                   6188:     my ($start,$end) = split(/\./,$dates);
                   6189:     if (!$start && !$end) {
                   6190:         return 'ok';
                   6191:     }
                   6192:     if (grep/^active$/,@{$status}) {
                   6193:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6194:             return 'ok';
                   6195:         }
                   6196:     }
                   6197:     if (grep/^previous$/,@{$status}) {
                   6198:         if ($end > $now ) {
                   6199:             return 'ok';
                   6200:         }
                   6201:     }
                   6202:     if (grep/^future$/,@{$status}) {
                   6203:         if ($start > $now) {
                   6204:             return 'ok';
                   6205:         }
                   6206:     }
                   6207:     return; 
                   6208: }
                   6209: 
                   6210: sub parse_portfolio_url {
                   6211:     my ($url) = @_;
                   6212: 
                   6213:     my ($type,$udom,$unum,$group,$file_name);
                   6214:     
1.823     albertel 6215:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6216: 	$type = 1;
                   6217:         $udom = $1;
                   6218:         $unum = $2;
                   6219:         $file_name = $3;
1.823     albertel 6220:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6221: 	$type = 2;
                   6222:         $udom = $1;
                   6223:         $unum = $2;
                   6224:         $group = $3;
                   6225:         $file_name = $3.'/'.$4;
                   6226:     }
                   6227:     if (wantarray) {
                   6228: 	return ($type,$udom,$unum,$file_name,$group);
                   6229:     }
                   6230:     return $type;
                   6231: }
                   6232: 
                   6233: sub is_portfolio_url {
                   6234:     my ($url) = @_;
                   6235:     return scalar(&parse_portfolio_url($url));
                   6236: }
                   6237: 
1.798     raeburn  6238: sub is_portfolio_file {
                   6239:     my ($file) = @_;
1.820     raeburn  6240:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6241:         return 1;
                   6242:     }
                   6243:     return;
                   6244: }
                   6245: 
1.976     raeburn  6246: sub usertools_access {
1.1084    raeburn  6247:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6248:     my ($access,%tools);
                   6249:     if ($context eq '') {
                   6250:         $context = 'tools';
                   6251:     }
                   6252:     if ($context eq 'requestcourses') {
                   6253:         %tools = (
                   6254:                       official   => 1,
                   6255:                       unofficial => 1,
1.1006    raeburn  6256:                       community  => 1,
1.985     raeburn  6257:                  );
1.1172.2.9  raeburn  6258:     } elsif ($context eq 'requestauthor') {
                   6259:         %tools = (
                   6260:                       requestauthor => 1,
                   6261:                  );
1.985     raeburn  6262:     } else {
                   6263:         %tools = (
                   6264:                       aboutme   => 1,
                   6265:                       blog      => 1,
1.1172.2.6  raeburn  6266:                       webdav    => 1,
1.985     raeburn  6267:                       portfolio => 1,
                   6268:                  );
                   6269:     }
1.976     raeburn  6270:     return if (!defined($tools{$tool}));
                   6271: 
                   6272:     if ((!defined($udom)) || (!defined($uname))) {
                   6273:         $udom = $env{'user.domain'};
                   6274:         $uname = $env{'user.name'};
                   6275:     }
                   6276: 
1.978     raeburn  6277:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6278:         if ($action ne 'reload') {
1.985     raeburn  6279:             if ($context eq 'requestcourses') {
                   6280:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6281:             } elsif ($context eq 'requestauthor') {
                   6282:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6283:             } else {
                   6284:                 return $env{'environment.availabletools.'.$tool};
                   6285:             }
                   6286:         }
1.976     raeburn  6287:     }
                   6288: 
1.1172.2.9  raeburn  6289:     my ($toolstatus,$inststatus,$envkey);
                   6290:     if ($context eq 'requestauthor') {
                   6291:         $envkey = $context;
                   6292:     } else {
                   6293:         $envkey = $context.'.'.$tool;
                   6294:     }
1.976     raeburn  6295: 
1.985     raeburn  6296:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6297:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6298:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6299:         $inststatus = $env{'environment.inststatus'};
                   6300:     } else {
1.1084    raeburn  6301:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6302:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6303:             $inststatus = $userenvref->{'inststatus'};
                   6304:         } else {
1.1172.2.9  raeburn  6305:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6306:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6307:             $inststatus = $userenv{'inststatus'};
                   6308:         }
1.976     raeburn  6309:     }
                   6310: 
                   6311:     if ($toolstatus ne '') {
                   6312:         if ($toolstatus) {
                   6313:             $access = 1;
                   6314:         } else {
                   6315:             $access = 0;
                   6316:         }
                   6317:         return $access;
                   6318:     }
                   6319: 
1.1084    raeburn  6320:     my ($is_adv,%domdef);
                   6321:     if (ref($is_advref) eq 'HASH') {
                   6322:         $is_adv = $is_advref->{'is_adv'};
                   6323:     } else {
                   6324:         $is_adv = &is_advanced_user($udom,$uname);
                   6325:     }
                   6326:     if (ref($domdefref) eq 'HASH') {
                   6327:         %domdef = %{$domdefref};
                   6328:     } else {
                   6329:         %domdef = &get_domain_defaults($udom);
                   6330:     }
1.976     raeburn  6331:     if (ref($domdef{$tool}) eq 'HASH') {
                   6332:         if ($is_adv) {
                   6333:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6334:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6335:                     $access = 1;
                   6336:                 } else {
                   6337:                     $access = 0;
                   6338:                 }
                   6339:                 return $access;
                   6340:             }
                   6341:         }
                   6342:         if ($inststatus ne '') {
                   6343:             my ($hasaccess,$hasnoaccess);
                   6344:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6345:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6346:                     if ($domdef{$tool}{$affiliation}) {
                   6347:                         $hasaccess = 1;
                   6348:                     } else {
                   6349:                         $hasnoaccess = 1;
                   6350:                     }
                   6351:                 }
                   6352:             }
                   6353:             if ($hasaccess || $hasnoaccess) {
                   6354:                 if ($hasaccess) {
                   6355:                     $access = 1;
                   6356:                 } elsif ($hasnoaccess) {
                   6357:                     $access = 0; 
                   6358:                 }
                   6359:                 return $access;
                   6360:             }
                   6361:         } else {
                   6362:             if ($domdef{$tool}{'default'} ne '') {
                   6363:                 if ($domdef{$tool}{'default'}) {
                   6364:                     $access = 1;
                   6365:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6366:                     $access = 0;
                   6367:                 }
                   6368:                 return $access;
                   6369:             }
                   6370:         }
                   6371:     } else {
1.1172.2.6  raeburn  6372:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6373:             $access = 1;
                   6374:         } else {
                   6375:             $access = 0;
                   6376:         }
1.976     raeburn  6377:         return $access;
                   6378:     }
                   6379: }
                   6380: 
1.1050    raeburn  6381: sub is_course_owner {
                   6382:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6383:     if (($udom eq '') || ($uname eq '')) {
                   6384:         $udom = $env{'user.domain'};
                   6385:         $uname = $env{'user.name'};
                   6386:     }
                   6387:     unless (($udom eq '') || ($uname eq '')) {
                   6388:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6389:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6390:                 return 1;
                   6391:             } else {
                   6392:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6393:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6394:                     return 1;
                   6395:                 }
                   6396:             }
                   6397:         }
                   6398:     }
                   6399:     return;
                   6400: }
                   6401: 
1.976     raeburn  6402: sub is_advanced_user {
                   6403:     my ($udom,$uname) = @_;
1.1085    raeburn  6404:     if ($udom ne '' && $uname ne '') {
                   6405:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6406:             if (wantarray) {
                   6407:                 return ($env{'user.adv'},$env{'user.author'});
                   6408:             } else {
                   6409:                 return $env{'user.adv'};
                   6410:             }
1.1085    raeburn  6411:         }
                   6412:     }
1.976     raeburn  6413:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6414:     my %allroles;
1.1128    raeburn  6415:     my ($is_adv,$is_author);
1.976     raeburn  6416:     foreach my $role (keys(%roleshash)) {
                   6417:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6418:         my $area = '/'.$tdomain.'/'.$trest;
                   6419:         if ($sec ne '') {
                   6420:             $area .= '/'.$sec;
                   6421:         }
                   6422:         if (($area ne '') && ($trole ne '')) {
                   6423:             my $spec=$trole.'.'.$area;
                   6424:             if ($trole =~ /^cr\//) {
                   6425:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6426:             } elsif ($trole ne 'gr') {
                   6427:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6428:             }
1.1128    raeburn  6429:             if ($trole eq 'au') {
                   6430:                 $is_author = 1;
                   6431:             }
1.976     raeburn  6432:         }
                   6433:     }
                   6434:     foreach my $role (keys(%allroles)) {
                   6435:         last if ($is_adv);
                   6436:         foreach my $item (split(/:/,$allroles{$role})) {
                   6437:             if ($item ne '') {
                   6438:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6439:                 if ($privilege eq 'adv') {
                   6440:                     $is_adv = 1;
                   6441:                     last;
                   6442:                 }
                   6443:             }
                   6444:         }
                   6445:     }
1.1128    raeburn  6446:     if (wantarray) {
                   6447:         return ($is_adv,$is_author);
                   6448:     }
1.976     raeburn  6449:     return $is_adv;
                   6450: }
1.798     raeburn  6451: 
1.1035    raeburn  6452: sub check_can_request {
1.1036    raeburn  6453:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6454:     my $canreq = 0;
                   6455:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6456:     my @options = ('approval','validate','autolimit');
                   6457:     my $optregex = join('|',@options);
                   6458:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6459:         foreach my $type (@{$types}) {
                   6460:             if (&usertools_access($env{'user.name'},
                   6461:                                   $env{'user.domain'},
                   6462:                                   $type,undef,'requestcourses')) {
                   6463:                 $canreq ++;
1.1036    raeburn  6464:                 if (ref($request_domains) eq 'HASH') {
                   6465:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6466:                 }
1.1035    raeburn  6467:                 if ($dom eq $env{'user.domain'}) {
                   6468:                     $can_request->{$type} = 1;
                   6469:                 }
                   6470:             }
                   6471:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6472:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6473:                 if (@curr > 0) {
1.1036    raeburn  6474:                     foreach my $item (@curr) {
                   6475:                         if (ref($request_domains) eq 'HASH') {
                   6476:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6477:                             if ($otherdom ne '') {
                   6478:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6479:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6480:                                         push(@{$request_domains->{$type}},$otherdom);
                   6481:                                     }
                   6482:                                 } else {
                   6483:                                     push(@{$request_domains->{$type}},$otherdom);
                   6484:                                 }
                   6485:                             }
                   6486:                         }
                   6487:                     }
                   6488:                     unless($dom eq $env{'user.domain'}) {
                   6489:                         $canreq ++;
1.1035    raeburn  6490:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6491:                             $can_request->{$type} = 1;
                   6492:                         }
                   6493:                     }
                   6494:                 }
                   6495:             }
                   6496:         }
                   6497:     }
                   6498:     return $canreq;
                   6499: }
                   6500: 
1.341     www      6501: # ---------------------------------------------- Custom access rule evaluation
                   6502: 
                   6503: sub customaccess {
                   6504:     my ($priv,$uri)=@_;
1.807     albertel 6505:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6506:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6507:     $udom = &LONCAPA::clean_domain($udom);
                   6508:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6509:     my $access=0;
1.800     albertel 6510:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6511: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6512: 	if ($type eq 'user') {
                   6513: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6514: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6515: 		if ($tdom) {
                   6516: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6517: 		}
1.896     albertel 6518: 		if ($tuname) {
                   6519: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6520: 		}
                   6521: 		$access=($effect eq 'allow');
                   6522: 		last;
                   6523: 	    }
                   6524: 	} else {
                   6525: 	    if ($role) {
                   6526: 		if ($role ne $urole) { next; }
                   6527: 	    }
                   6528: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6529: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6530: 		if ($tdom) {
                   6531: 		    if ($tdom ne $udom) { next; }
                   6532: 		}
                   6533: 		if ($tcrs) {
                   6534: 		    if ($tcrs ne $ucrs) { next; }
                   6535: 		}
                   6536: 		if ($tsec) {
                   6537: 		    if ($tsec ne $usec) { next; }
                   6538: 		}
                   6539: 		$access=($effect eq 'allow');
                   6540: 		last;
                   6541: 	    }
                   6542: 	    if ($realm eq '' && $role eq '') {
                   6543: 		$access=($effect eq 'allow');
                   6544: 	    }
1.402     bowersj2 6545: 	}
1.341     www      6546:     }
                   6547:     return $access;
                   6548: }
                   6549: 
1.103     harris41 6550: # ------------------------------------------------- Check for a user privilege
1.12      www      6551: 
                   6552: sub allowed {
1.810     raeburn  6553:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6554:     my $ver_orguri=$uri;
1.439     www      6555:     $uri=&deversion($uri);
1.152     www      6556:     my $orguri=$uri;
1.52      www      6557:     $uri=&declutter($uri);
1.809     raeburn  6558: 
1.810     raeburn  6559:     if ($priv eq 'evb') {
                   6560: # Evade communication block restrictions for specified role in a course
                   6561:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6562:             return $1;
                   6563:         } else {
                   6564:             return;
                   6565:         }
                   6566:     }
                   6567: 
1.620     albertel 6568:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6569: # Free bre access to adm and meta resources
1.775     albertel 6570:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6571: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6572: 	&& ($priv eq 'bre')) {
1.14      www      6573: 	return 'F';
1.159     www      6574:     }
                   6575: 
1.545     banghart 6576: # Free bre access to user's own portfolio contents
1.714     raeburn  6577:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6578:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6579: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6580:         my %setters;
                   6581:         my ($startblock,$endblock) = 
                   6582:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6583:         if ($startblock && $endblock) {
                   6584:             return 'B';
                   6585:         } else {
                   6586:             return 'F';
                   6587:         }
1.545     banghart 6588:     }
                   6589: 
1.762     raeburn  6590: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6591:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6592:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6593:         if (exists($env{'request.course.id'})) {
                   6594:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6595:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6596:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6597:                 my $courseprivid=$env{'request.course.id'};
                   6598:                 $courseprivid=~s/\_/\//;
                   6599:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6600:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6601:                     return $1; 
1.762     raeburn  6602:                 } else {
                   6603:                     if ($env{'request.course.sec'}) {
                   6604:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6605:                     }
                   6606:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6607:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6608:                         return $2;
                   6609:                     }
1.714     raeburn  6610:                 }
                   6611:             }
                   6612:         }
                   6613:     }
                   6614: 
1.159     www      6615: # Free bre to public access
                   6616: 
                   6617:     if ($priv eq 'bre') {
1.238     www      6618:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6619: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6620:            return 'F'; 
                   6621:         }
1.238     www      6622:         if ($copyright eq 'priv') {
                   6623:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6624: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6625: 		return '';
                   6626:             }
                   6627:         }
                   6628:         if ($copyright eq 'domain') {
                   6629:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6630: 	    unless (($env{'user.domain'} eq $1) ||
                   6631:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6632: 		return '';
                   6633:             }
1.262     matthew  6634:         }
1.620     albertel 6635:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6636:             # Library role, so allow browsing of resources in this domain.
                   6637:             return 'F';
1.238     www      6638:         }
1.341     www      6639:         if ($copyright eq 'custom') {
                   6640: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6641:         }
1.14      www      6642:     }
1.264     matthew  6643:     # Domain coordinator is trying to create a course
1.620     albertel 6644:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6645:         # uri is the requested domain in this case.
                   6646:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6647:         # a role of dc for the domain in question.
1.620     albertel 6648:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6649:     }
1.29      www      6650: 
1.52      www      6651:     my $thisallowed='';
                   6652:     my $statecond=0;
                   6653:     my $courseprivid='';
                   6654: 
1.1039    raeburn  6655:     my $ownaccess;
1.1043    raeburn  6656:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6657:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6658:         if ($uri eq '') {
                   6659:             $ownaccess = 1;
                   6660:         } else {
                   6661:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6662:                 my $udom = $env{'user.domain'};
                   6663:                 my $uname = $env{'user.name'};
                   6664:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6665:                     $ownaccess = 1;
1.1040    raeburn  6666:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6667:                     unless ($uri =~ m{\.\./}) {
                   6668:                         $ownaccess = 1;
                   6669:                     }
                   6670:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6671:                     my $now = time;
                   6672:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6673:                         my $adom = $1;
                   6674:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6675:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6676:                                 my ($start,$end) = split('.',$env{$key});
                   6677:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6678:                                     $ownaccess = 1;
                   6679:                                     last;
                   6680:                                 }
                   6681:                             }
                   6682:                         }
                   6683:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6684:                         my $adom = $1;
                   6685:                         my $aname = $2;
1.1042    raeburn  6686:                         foreach my $role ('ca','aa') { 
                   6687:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6688:                                 my ($start,$end) =
                   6689:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6690:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6691:                                     $ownaccess = 1;
                   6692:                                     last;
                   6693:                                 }
1.1039    raeburn  6694:                             }
                   6695:                         }
                   6696:                     }
                   6697:                 }
                   6698:             }
                   6699:         }
                   6700:     }
                   6701: 
1.52      www      6702: # Course
                   6703: 
1.620     albertel 6704:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6705:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6706:             $thisallowed.=$1;
                   6707:         }
1.52      www      6708:     }
1.29      www      6709: 
1.52      www      6710: # Domain
                   6711: 
1.620     albertel 6712:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6713:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6714:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6715:             $thisallowed.=$1;
                   6716:         }
1.12      www      6717:     }
1.52      www      6718: 
1.1141    raeburn  6719: # User who is not author or co-author might still be able to edit
                   6720: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6721:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6722:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6723:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6724:             $thisallowed.=$1;
                   6725:         }
                   6726:     }
                   6727: 
1.52      www      6728: # Course: uri itself is a course
1.66      www      6729:     my $courseuri=$uri;
                   6730:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6731:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6732: 
1.620     albertel 6733:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6734:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6735:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6736:             $thisallowed.=$1;
                   6737:         }
1.12      www      6738:     }
1.29      www      6739: 
1.665     albertel 6740: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6741: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6742:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6743: 	$thisallowed='';
1.671     raeburn  6744:         my ($match)=&is_on_map($uri);
                   6745:         if ($match) {
                   6746:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6747:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6748:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6749:                 if (@blockers > 0) {
                   6750:                     $thisallowed = 'B';
                   6751:                 } else {
                   6752:                     $thisallowed.=$1;
                   6753:                 }
1.671     raeburn  6754:             }
                   6755:         } else {
1.705     albertel 6756:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6757:             if ($refuri) {
                   6758:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6759:                     $thisallowed='F';
1.671     raeburn  6760:                 } else {
                   6761:                     $refuri=&declutter($refuri);
                   6762:                     my ($match) = &is_on_map($refuri);
                   6763:                     if ($match) {
1.1162    raeburn  6764:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6765:                         if (@blockers > 0) {
                   6766:                             $thisallowed = 'B';
                   6767:                         } else {
                   6768:                             $thisallowed='F';
                   6769:                         }
1.671     raeburn  6770:                     }
1.669     raeburn  6771:                 }
1.671     raeburn  6772:             }
                   6773:         }
1.314     www      6774:     }
1.492     albertel 6775: 
1.766     albertel 6776:     if ($priv eq 'bre'
                   6777: 	&& $thisallowed ne 'F' 
                   6778: 	&& $thisallowed ne '2'
                   6779: 	&& &is_portfolio_url($uri)) {
                   6780: 	$thisallowed = &portfolio_access($uri);
                   6781:     }
                   6782:     
1.52      www      6783: # Full access at system, domain or course-wide level? Exit.
1.29      www      6784:     if ($thisallowed=~/F/) {
                   6785: 	return 'F';
                   6786:     }
                   6787: 
1.52      www      6788: # If this is generating or modifying users, exit with special codes
1.29      www      6789: 
1.643     www      6790:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6791: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6792: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6793: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6794: 	    unless ($auname) { return $thisallowed; }
                   6795: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6796: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6797: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6798: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6799: 	}
1.52      www      6800: 	return $thisallowed;
                   6801:     }
                   6802: #
1.103     harris41 6803: # Gathered so far: system, domain and course wide privileges
1.52      www      6804: #
                   6805: # Course: See if uri or referer is an individual resource that is part of 
                   6806: # the course
                   6807: 
1.620     albertel 6808:     if ($env{'request.course.id'}) {
1.232     www      6809: 
1.620     albertel 6810:        $courseprivid=$env{'request.course.id'};
                   6811:        if ($env{'request.course.sec'}) {
                   6812:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6813:        }
                   6814:        $courseprivid=~s/\_/\//;
                   6815:        my $checkreferer=1;
1.232     www      6816:        my ($match,$cond)=&is_on_map($uri);
                   6817:        if ($match) {
                   6818:            $statecond=$cond;
1.620     albertel 6819:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6820:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6821:                my $value = $1;
                   6822:                if ($priv eq 'bre') {
                   6823:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6824:                    if (@blockers > 0) {
                   6825:                        $thisallowed = 'B';
                   6826:                    } else {
                   6827:                        $thisallowed.=$value;
                   6828:                    }
                   6829:                } else {
                   6830:                    $thisallowed.=$value;
                   6831:                }
1.52      www      6832:                $checkreferer=0;
                   6833:            }
1.29      www      6834:        }
1.83      www      6835:        
1.148     www      6836:        if ($checkreferer) {
1.620     albertel 6837: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6838:             unless ($refuri) {
1.800     albertel 6839:                 foreach my $key (keys(%env)) {
                   6840: 		    if ($key=~/^httpref\..*\*/) {
                   6841: 			my $pattern=$key;
1.156     www      6842:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6843:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6844:                         $pattern=~s/\//\\\//g;
1.152     www      6845:                         if ($orguri=~/$pattern/) {
1.800     albertel 6846: 			    $refuri=$env{$key};
1.148     www      6847:                         }
                   6848:                     }
1.191     harris41 6849:                 }
1.148     www      6850:             }
1.232     www      6851: 
1.148     www      6852:          if ($refuri) { 
1.152     www      6853: 	  $refuri=&declutter($refuri);
1.232     www      6854:           my ($match,$cond)=&is_on_map($refuri);
                   6855:             if ($match) {
                   6856:               my $refstatecond=$cond;
1.620     albertel 6857:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6858:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6859:                   my $value = $1;
                   6860:                   if ($priv eq 'bre') {
                   6861:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6862:                       if (@blockers > 0) {
                   6863:                           $thisallowed = 'B';
                   6864:                       } else {
                   6865:                           $thisallowed.=$value;
                   6866:                       }
                   6867:                   } else {
                   6868:                       $thisallowed.=$value;
                   6869:                   }
1.53      www      6870:                   $uri=$refuri;
                   6871:                   $statecond=$refstatecond;
1.52      www      6872:               }
                   6873:           }
1.148     www      6874:         }
1.29      www      6875:        }
1.52      www      6876:    }
1.29      www      6877: 
1.52      www      6878: #
1.103     harris41 6879: # Gathered now: all privileges that could apply, and condition number
1.52      www      6880: # 
                   6881: #
                   6882: # Full or no access?
                   6883: #
1.29      www      6884: 
1.52      www      6885:     if ($thisallowed=~/F/) {
                   6886: 	return 'F';
                   6887:     }
1.29      www      6888: 
1.52      www      6889:     unless ($thisallowed) {
                   6890:         return '';
                   6891:     }
1.29      www      6892: 
1.52      www      6893: # Restrictions exist, deal with them
                   6894: #
                   6895: #   C:according to course preferences
                   6896: #   R:according to resource settings
                   6897: #   L:unless locked
                   6898: #   X:according to user session state
                   6899: #
                   6900: 
                   6901: # Possibly locked functionality, check all courses
1.54      www      6902: # Locks might take effect only after 10 minutes cache expiration for other
                   6903: # courses, and 2 minutes for current course
1.52      www      6904: 
                   6905:     my $envkey;
                   6906:     if ($thisallowed=~/L/) {
1.1000    raeburn  6907:         foreach $envkey (keys(%env)) {
1.54      www      6908:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6909:                my $courseid=$2;
                   6910:                my $roleid=$1.'.'.$2;
1.92      www      6911:                $courseid=~s/^\///;
1.54      www      6912:                my $expiretime=600;
1.620     albertel 6913:                if ($env{'request.role'} eq $roleid) {
1.54      www      6914: 		  $expiretime=120;
                   6915:                }
                   6916: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6917:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6918:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6919: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6920:                }
1.620     albertel 6921:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6922:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6923: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6924:                        &log($env{'user.domain'},$env{'user.name'},
                   6925:                             $env{'user.home'},
1.57      www      6926:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6927:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6928:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6929: 		       return '';
                   6930:                    }
                   6931:                }
1.620     albertel 6932:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6933:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6934: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6935:                        &log($env{'user.domain'},$env{'user.name'},
                   6936:                             $env{'user.home'},
1.57      www      6937:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6938:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6939:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6940: 		       return '';
                   6941:                    }
                   6942:                }
                   6943: 	   }
1.29      www      6944:        }
1.52      www      6945:     }
                   6946:    
                   6947: #
                   6948: # Rest of the restrictions depend on selected course
                   6949: #
                   6950: 
1.620     albertel 6951:     unless ($env{'request.course.id'}) {
1.766     albertel 6952: 	if ($thisallowed eq 'A') {
                   6953: 	    return 'A';
1.814     raeburn  6954:         } elsif ($thisallowed eq 'B') {
                   6955:             return 'B';
1.766     albertel 6956: 	} else {
                   6957: 	    return '1';
                   6958: 	}
1.52      www      6959:     }
1.29      www      6960: 
1.52      www      6961: #
                   6962: # Now user is definitely in a course
                   6963: #
1.53      www      6964: 
                   6965: 
                   6966: # Course preferences
                   6967: 
                   6968:    if ($thisallowed=~/C/) {
1.620     albertel 6969:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6970:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6971:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6972: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6973: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6974: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6975: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6976: 			$env{'request.course.id'});
                   6977: 	   }
1.237     www      6978:            return '';
                   6979:        }
                   6980: 
1.620     albertel 6981:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6982: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6983: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6984: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6985: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6986: 			$env{'request.course.id'});
                   6987: 	   }
1.54      www      6988:            return '';
                   6989:        }
1.53      www      6990:    }
                   6991: 
                   6992: # Resource preferences
                   6993: 
                   6994:    if ($thisallowed=~/R/) {
1.620     albertel 6995:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6996:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6997: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6998: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6999: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7000: 	   }
                   7001: 	   return '';
1.54      www      7002:        }
1.53      www      7003:    }
1.30      www      7004: 
1.246     www      7005: # Restricted by state or randomout?
1.30      www      7006: 
1.52      www      7007:    if ($thisallowed=~/X/) {
1.620     albertel 7008:       if ($env{'acc.randomout'}) {
1.579     albertel 7009: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7010:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7011:             return ''; 
                   7012:          }
1.247     www      7013:       }
                   7014:       if (&condval($statecond)) {
1.52      www      7015: 	 return '2';
                   7016:       } else {
                   7017:          return '';
                   7018:       }
                   7019:    }
1.30      www      7020: 
1.766     albertel 7021:     if ($thisallowed eq 'A') {
                   7022: 	return 'A';
1.814     raeburn  7023:     } elsif ($thisallowed eq 'B') {
                   7024:         return 'B';
1.766     albertel 7025:     }
1.52      www      7026:    return 'F';
1.232     www      7027: }
1.1162    raeburn  7028: 
1.1172.2.13  raeburn  7029: # ------------------------------------------- Check construction space access
                   7030: 
                   7031: sub constructaccess {
                   7032:     my ($url,$setpriv)=@_;
                   7033: 
                   7034: # We do not allow editing of previous versions of files
                   7035:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7036: 
                   7037: # Get username and domain from URL
                   7038:     my ($ownername,$ownerdomain,$ownerhome);
                   7039: 
                   7040:     ($ownerdomain,$ownername) =
                   7041:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7042: 
                   7043: # The URL does not really point to any authorspace, forget it
                   7044:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7045: 
                   7046: # Now we need to see if the user has access to the authorspace of
                   7047: # $ownername at $ownerdomain
                   7048: 
                   7049:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7050: # Real author for this?
                   7051:        $ownerhome = $env{'user.home'};
                   7052:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7053:           return ($ownername,$ownerdomain,$ownerhome);
                   7054:        }
                   7055:     } else {
                   7056: # Co-author for this?
                   7057:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7058:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7059:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7060:             return ($ownername,$ownerdomain,$ownerhome);
                   7061:         }
                   7062:     }
                   7063: 
                   7064: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7065: # we might as well leave
                   7066:    unless ($setpriv) { return ''; }
                   7067: 
                   7068: # Backdoor access?
                   7069:     my $allowed=&allowed('eco',$ownerdomain);
                   7070: # Nope
                   7071:     unless ($allowed) { return ''; }
                   7072: # Looks like we may have access, but could be locked by the owner of the construction space
                   7073:     if ($allowed eq 'U') {
                   7074:         my %blocked=&get('environment',['domcoord.author'],
                   7075:                          $ownerdomain,$ownername);
                   7076: # Is blocked by owner
                   7077:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7078:     }
                   7079:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7080: # Grant temporary access
                   7081:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7082:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7083:         if (!$update) { $update = $then; }
                   7084:         my $refresh=$env{'user.refresh.time'};
                   7085:         if (!$refresh) { $refresh = $update; }
                   7086:         my $now = time;
                   7087:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7088:                            $now,'ca','constructaccess');
                   7089:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7090:         return($ownername,$ownerdomain,$ownerhome);
                   7091:     }
                   7092: # No business here
                   7093:     return '';
                   7094: }
                   7095: 
1.1162    raeburn  7096: sub get_comm_blocks {
                   7097:     my ($cdom,$cnum) = @_;
                   7098:     if ($cdom eq '' || $cnum eq '') {
                   7099:         return unless ($env{'request.course.id'});
                   7100:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7101:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7102:     }
                   7103:     my %commblocks;
                   7104:     my $hashid=$cdom.'_'.$cnum;
                   7105:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7106:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7107:         %commblocks = %{$blocksref};
                   7108:     } else {
                   7109:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7110:         my $cachetime = 600;
                   7111:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7112:     }
                   7113:     return %commblocks;
                   7114: }
                   7115: 
                   7116: sub has_comm_blocking {
                   7117:     my ($priv,$symb,$uri,$blocks) = @_;
                   7118:     return unless ($env{'request.course.id'});
                   7119:     return unless ($priv eq 'bre');
                   7120:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7121:     my %commblocks;
                   7122:     if (ref($blocks) eq 'HASH') {
                   7123:         %commblocks = %{$blocks};
                   7124:     } else {
                   7125:         %commblocks = &get_comm_blocks();
                   7126:     }
                   7127:     return unless (keys(%commblocks) > 0);
                   7128:     if (!$symb) { $symb=&symbread($uri,1); }
                   7129:     my ($map,$resid,undef)=&decode_symb($symb);
                   7130:     my %tocheck = (
                   7131:                     maps      => $map,
                   7132:                     resources => $symb,
                   7133:                   );
                   7134:     my @blockers;
                   7135:     my $now = time;
1.1163    raeburn  7136:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7137:     foreach my $block (keys(%commblocks)) {
                   7138:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7139:             my ($start,$end) = ($1,$2);
                   7140:             if ($start <= $now && $end >= $now) {
                   7141:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7142:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7143:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7144:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7145:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7146:                                     push(@blockers,$block);
                   7147:                                 }
                   7148:                             }
                   7149:                         }
                   7150:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7151:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7152:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7153:                                     push(@blockers,$block);
                   7154:                                 }
                   7155:                             }
                   7156:                         }
                   7157:                     }
                   7158:                 }
                   7159:             }
                   7160:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7161:             my $item = $1;
1.1163    raeburn  7162:             my @to_test;
1.1162    raeburn  7163:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7164:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7165:                     my $check_interval;
                   7166:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7167:                         my @interval;
                   7168:                         my $type = 'map';
                   7169:                         if ($item eq 'course') {
                   7170:                             $type = 'course';
                   7171:                             @interval=&EXT("resource.0.interval");
                   7172:                         } else {
                   7173:                             if ($item =~ /___\d+___/) {
                   7174:                                 $type = 'resource';
                   7175:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7176:                                 if (ref($navmap)) {                        
                   7177:                                     my $res = $navmap->getBySymb($item); 
                   7178:                                     push(@to_test,$res);
                   7179:                                 }
1.1162    raeburn  7180:                             } else {
                   7181:                                 my $mapsymb = &symbread($item,1);
                   7182:                                 if ($mapsymb) {
                   7183:                                     if (ref($navmap)) {
                   7184:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7185:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7186:                                         foreach my $res (@to_test) {
1.1162    raeburn  7187:                                             my $symb = $res->symb();
                   7188:                                             next if ($symb eq $mapsymb);
                   7189:                                             if ($symb ne '') {
                   7190:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7191:                                                 last;
                   7192:                                             }
                   7193:                                         }
                   7194:                                     }
                   7195:                                 }
                   7196:                             }
                   7197:                         }
                   7198:                         if ($interval[0] =~ /\d+/) {
                   7199:                             my $first_access;
                   7200:                             if ($type eq 'resource') {
                   7201:                                 $first_access=&get_first_access($interval[1],$item);
                   7202:                             } elsif ($type eq 'map') {
                   7203:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7204:                             } else {
                   7205:                                 $first_access=&get_first_access($interval[1]);
                   7206:                             }
                   7207:                             if ($first_access) {
                   7208:                                 my $timesup = $first_access+$interval[0];
                   7209:                                 if ($timesup > $now) {
1.1163    raeburn  7210:                                     foreach my $res (@to_test) {
                   7211:                                         if ($res->is_problem()) {
                   7212:                                             if ($res->completable()) {
                   7213:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7214:                                                     push(@blockers,$block);
                   7215:                                                 }
                   7216:                                                 last;
                   7217:                                             }
                   7218:                                         }
1.1162    raeburn  7219:                                     }
                   7220:                                 }
                   7221:                             }
                   7222:                         }
                   7223:                     }
                   7224:                 }
                   7225:             }
                   7226:         }
                   7227:     }
                   7228:     return @blockers;
                   7229: }
                   7230: 
                   7231: sub check_docs_block {
                   7232:     my ($docsblock,$tocheck) =@_;
                   7233:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7234:         return;
                   7235:     }
                   7236:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7237:         if ($tocheck->{'maps'}) {
                   7238:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7239:                 return 1;
                   7240:             }
                   7241:         }
                   7242:     }
                   7243:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7244:         if ($tocheck->{'resources'}) {
                   7245:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7246:                 return 1;
                   7247:             }
                   7248:         }
                   7249:     }
                   7250:     return;
                   7251: }
                   7252: 
1.1133    foxr     7253: #
                   7254: #   Removes the versino from a URI and
                   7255: #   splits it in to its filename and path to the filename.
                   7256: #   Seems like File::Basename could have done this more clearly.
                   7257: #   Parameters:
                   7258: #      $uri   - input URI
                   7259: #   Returns:
                   7260: #     Two element list consisting of 
                   7261: #     $pathname  - the URI up to and excluding the trailing /
                   7262: #     $filename  - The part of the URI following the last /
                   7263: #  NOTE:
                   7264: #    Another realization of this is simply:
                   7265: #    use File::Basename;
                   7266: #    ...
                   7267: #    $uri = shift;
                   7268: #    $filename = basename($uri);
                   7269: #    $path     = dirname($uri);
                   7270: #    return ($filename, $path);
                   7271: #
                   7272: #     The implementation below is probably faster however.
                   7273: #
1.710     albertel 7274: sub split_uri_for_cond {
                   7275:     my $uri=&deversion(&declutter(shift));
                   7276:     my @uriparts=split(/\//,$uri);
                   7277:     my $filename=pop(@uriparts);
                   7278:     my $pathname=join('/',@uriparts);
                   7279:     return ($pathname,$filename);
                   7280: }
1.232     www      7281: # --------------------------------------------------- Is a resource on the map?
                   7282: 
                   7283: sub is_on_map {
1.710     albertel 7284:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7285:     #Trying to find the conditional for the file
1.620     albertel 7286:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7287: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7288:     if ($match) {
1.289     bowersj2 7289: 	return (1,$1);
                   7290:     } else {
1.434     www      7291: 	return (0,0);
1.289     bowersj2 7292:     }
1.12      www      7293: }
                   7294: 
1.427     www      7295: # --------------------------------------------------------- Get symb from alias
                   7296: 
                   7297: sub get_symb_from_alias {
                   7298:     my $symb=shift;
                   7299:     my ($map,$resid,$url)=&decode_symb($symb);
                   7300: # Already is a symb
                   7301:     if ($url) { return $symb; }
                   7302: # Must be an alias
                   7303:     my $aliassymb='';
                   7304:     my %bighash;
1.620     albertel 7305:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7306:                             &GDBM_READER(),0640)) {
                   7307:         my $rid=$bighash{'mapalias_'.$symb};
                   7308: 	if ($rid) {
                   7309: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7310: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7311: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7312: 	}
                   7313:         untie %bighash;
                   7314:     }
                   7315:     return $aliassymb;
                   7316: }
                   7317: 
1.12      www      7318: # ----------------------------------------------------------------- Define Role
                   7319: 
                   7320: sub definerole {
                   7321:   if (allowed('mcr','/')) {
                   7322:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7323:     foreach my $role (split(':',$sysrole)) {
                   7324: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7325:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7326:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7327: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7328:                return "refused:s:$crole&$cqual"; 
                   7329:             }
                   7330:         }
1.191     harris41 7331:     }
1.800     albertel 7332:     foreach my $role (split(':',$domrole)) {
                   7333: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7334:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7335:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7336: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7337:                return "refused:d:$crole&$cqual"; 
                   7338:             }
                   7339:         }
1.191     harris41 7340:     }
1.800     albertel 7341:     foreach my $role (split(':',$courole)) {
                   7342: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7343:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7344:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7345: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7346:                return "refused:c:$crole&$cqual"; 
                   7347:             }
                   7348:         }
1.191     harris41 7349:     }
1.620     albertel 7350:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7351:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7352: 	        "rolesdef_$rolename=".
                   7353:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7354:     return reply($command,$env{'user.home'});
1.12      www      7355:   } else {
                   7356:     return 'refused';
                   7357:   }
1.105     harris41 7358: }
                   7359: 
                   7360: # ---------------- Make a metadata query against the network of library servers
                   7361: 
                   7362: sub metadata_query {
1.1172.2.33  raeburn  7363:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7364:     my %rhash;
1.845     albertel 7365:     my %libserv = &all_library();
1.244     matthew  7366:     my @server_list = (defined($server_array) ? @$server_array
                   7367:                                               : keys(%libserv) );
                   7368:     for my $server (@server_list) {
1.1172.2.33  raeburn  7369:         my $domains = '';
                   7370:         if (ref($domains_hash) eq 'HASH') {
                   7371:             $domains = $domains_hash->{$server};    
                   7372:         }
1.118     harris41 7373: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7374: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7375: 	    $rhash{$server}=$reply;
                   7376: 	}
                   7377: 	else {
                   7378: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7379: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7380: 			     $server);
                   7381: 	    $rhash{$server}=$reply;
                   7382: 	}
1.112     harris41 7383:     }
1.118     harris41 7384:     return \%rhash;
1.240     www      7385: }
                   7386: 
                   7387: # ----------------------------------------- Send log queries and wait for reply
                   7388: 
                   7389: sub log_query {
                   7390:     my ($uname,$udom,$query,%filters)=@_;
                   7391:     my $uhome=&homeserver($uname,$udom);
                   7392:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7393:     my $uhost=&hostname($uhome);
1.800     albertel 7394:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7395:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7396:                        $uhome);
1.479     albertel 7397:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7398:     return get_query_reply($queryid);
                   7399: }
                   7400: 
1.818     raeburn  7401: # -------------------------- Update MySQL table for portfolio file
                   7402: 
                   7403: sub update_portfolio_table {
1.821     raeburn  7404:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7405:     if ($group ne '') {
                   7406:         $file_name =~s /^\Q$group\E//;
                   7407:     }
1.818     raeburn  7408:     my $homeserver = &homeserver($uname,$udom);
                   7409:     my $queryid=
1.821     raeburn  7410:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7411:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7412:     my $reply = &get_query_reply($queryid);
                   7413:     return $reply;
                   7414: }
                   7415: 
1.899     raeburn  7416: # -------------------------- Update MySQL allusers table
                   7417: 
                   7418: sub update_allusers_table {
                   7419:     my ($uname,$udom,$names) = @_;
                   7420:     my $homeserver = &homeserver($uname,$udom);
                   7421:     my $queryid=
                   7422:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7423:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7424:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7425:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7426:                'generation='.&escape($names->{'generation'}).'%%'.
                   7427:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7428:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7429:     return;
1.899     raeburn  7430: }
                   7431: 
1.508     raeburn  7432: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7433: 
                   7434: sub fetch_enrollment_query {
1.511     raeburn  7435:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7436:     my $homeserver;
1.547     raeburn  7437:     my $maxtries = 1;
1.508     raeburn  7438:     if ($context eq 'automated') {
                   7439:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7440:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7441:     } else {
                   7442:         $homeserver = &homeserver($cnum,$dom);
                   7443:     }
1.838     albertel 7444:     my $host=&hostname($homeserver);
1.506     raeburn  7445:     my $cmd = '';
1.1000    raeburn  7446:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7447:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7448:     }
                   7449:     $cmd =~ s/%%$//;
                   7450:     $cmd = &escape($cmd);
                   7451:     my $query = 'fetchenrollment';
1.620     albertel 7452:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7453:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7454:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7455:         return 'error: '.$queryid;
                   7456:     }
1.506     raeburn  7457:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7458:     my $tries = 1;
                   7459:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7460:         $reply = &get_query_reply($queryid);
                   7461:         $tries ++;
                   7462:     }
1.526     raeburn  7463:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7464:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7465:     } else {
1.901     albertel 7466:         my @responses = split(/:/,$reply);
1.515     raeburn  7467:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7468:             foreach my $line (@responses) {
                   7469:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7470:                 $$replyref{$key} = $value;
                   7471:             }
                   7472:         } else {
1.1117    foxr     7473:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7474:             foreach my $line (@responses) {
                   7475:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7476:                 $$replyref{$key} = $value;
                   7477:                 if ($value > 0) {
1.800     albertel 7478:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7479:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7480:                         my $destname = $pathname.'/'.$filename;
                   7481:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7482:                         if ($xml_classlist =~ /^error/) {
                   7483:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7484:                         } else {
1.506     raeburn  7485:                             if ( open(FILE,">$destname") ) {
                   7486:                                 print FILE &unescape($xml_classlist);
                   7487:                                 close(FILE);
1.526     raeburn  7488:                             } else {
                   7489:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7490:                             }
                   7491:                         }
                   7492:                     }
                   7493:                 }
                   7494:             }
                   7495:         }
                   7496:         return 'ok';
                   7497:     }
                   7498:     return 'error';
                   7499: }
                   7500: 
1.242     www      7501: sub get_query_reply {
                   7502:     my $queryid=shift;
1.1117    foxr     7503:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7504:     my $reply='';
                   7505:     for (1..100) {
                   7506: 	sleep 2;
                   7507:         if (-e $replyfile.'.end') {
1.448     albertel 7508: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7509: 		$reply = join('',<$fh>);
                   7510: 		close($fh);
1.240     www      7511: 	   } else { return 'error: reply_file_error'; }
1.242     www      7512:            return &unescape($reply);
                   7513: 	}
1.240     www      7514:     }
1.242     www      7515:     return 'timeout:'.$queryid;
1.240     www      7516: }
                   7517: 
                   7518: sub courselog_query {
1.241     www      7519: #
                   7520: # possible filters:
                   7521: # url: url or symb
                   7522: # username
                   7523: # domain
                   7524: # action: view, submit, grade
                   7525: # start: timestamp
                   7526: # end: timestamp
                   7527: #
1.240     www      7528:     my (%filters)=@_;
1.620     albertel 7529:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7530:     if ($filters{'url'}) {
                   7531: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7532:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7533:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7534:     }
1.620     albertel 7535:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7536:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7537:     return &log_query($cname,$cdom,'courselog',%filters);
                   7538: }
                   7539: 
                   7540: sub userlog_query {
1.858     raeburn  7541: #
                   7542: # possible filters:
                   7543: # action: log check role
                   7544: # start: timestamp
                   7545: # end: timestamp
                   7546: #
1.240     www      7547:     my ($uname,$udom,%filters)=@_;
                   7548:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7549: }
                   7550: 
1.506     raeburn  7551: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7552: 
                   7553: sub auto_run {
1.508     raeburn  7554:     my ($cnum,$cdom) = @_;
1.876     raeburn  7555:     my $response = 0;
                   7556:     my $settings;
                   7557:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7558:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7559:         $settings = $domconfig{'autoenroll'};
                   7560:         if ($settings->{'run'} eq '1') {
                   7561:             $response = 1;
                   7562:         }
                   7563:     } else {
1.934     raeburn  7564:         my $homeserver;
                   7565:         if (&is_course($cdom,$cnum)) {
                   7566:             $homeserver = &homeserver($cnum,$cdom);
                   7567:         } else {
                   7568:             $homeserver = &domain($cdom,'primary');
                   7569:         }
                   7570:         if ($homeserver ne 'no_host') {
                   7571:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7572:         }
1.876     raeburn  7573:     }
1.506     raeburn  7574:     return $response;
                   7575: }
1.776     albertel 7576: 
1.506     raeburn  7577: sub auto_get_sections {
1.508     raeburn  7578:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7579:     my $homeserver;
                   7580:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7581:         $homeserver = &homeserver($cnum,$cdom);
                   7582:     }
                   7583:     if (!defined($homeserver)) { 
                   7584:         if ($cdom =~ /^$match_domain$/) {
                   7585:             $homeserver = &domain($cdom,'primary');
                   7586:         }
                   7587:     }
                   7588:     my @secs;
                   7589:     if (defined($homeserver)) {
                   7590:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7591:         unless ($response eq 'refused') {
                   7592:             @secs = split(/:/,$response);
                   7593:         }
1.506     raeburn  7594:     }
                   7595:     return @secs;
                   7596: }
1.776     albertel 7597: 
1.506     raeburn  7598: sub auto_new_course {
1.1099    raeburn  7599:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7600:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7601:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7602:     return $response;
                   7603: }
1.776     albertel 7604: 
1.506     raeburn  7605: sub auto_validate_courseID {
1.508     raeburn  7606:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7607:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7608:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7609:     return $response;
                   7610: }
1.776     albertel 7611: 
1.1007    raeburn  7612: sub auto_validate_instcode {
1.1020    raeburn  7613:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7614:     my ($homeserver,$response);
                   7615:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7616:         $homeserver = &homeserver($cnum,$cdom);
                   7617:     }
                   7618:     if (!defined($homeserver)) {
                   7619:         if ($cdom =~ /^$match_domain$/) {
                   7620:             $homeserver = &domain($cdom,'primary');
                   7621:         }
                   7622:     }
1.1065    raeburn  7623:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7624:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7625:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7626:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7627: }
                   7628: 
1.506     raeburn  7629: sub auto_create_password {
1.873     raeburn  7630:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7631:     my ($homeserver,$response);
1.506     raeburn  7632:     my $create_passwd = 0;
                   7633:     my $authchk = '';
1.873     raeburn  7634:     if ($udom =~ /^$match_domain$/) {
                   7635:         $homeserver = &domain($udom,'primary');
                   7636:     }
                   7637:     if ($homeserver eq '') {
                   7638:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7639:             $homeserver = &homeserver($cnum,$cdom);
                   7640:         }
                   7641:     }
                   7642:     if ($homeserver eq '') {
                   7643:         $authchk = 'nodomain';
1.506     raeburn  7644:     } else {
1.873     raeburn  7645:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7646:         if ($response eq 'refused') {
                   7647:             $authchk = 'refused';
                   7648:         } else {
1.901     albertel 7649:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7650:         }
1.506     raeburn  7651:     }
                   7652:     return ($authparam,$create_passwd,$authchk);
                   7653: }
                   7654: 
1.706     raeburn  7655: sub auto_photo_permission {
                   7656:     my ($cnum,$cdom,$students) = @_;
                   7657:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7658:     my ($outcome,$perm_reqd,$conditions) = 
                   7659: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7660:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7661: 	return (undef,undef);
                   7662:     }
1.706     raeburn  7663:     return ($outcome,$perm_reqd,$conditions);
                   7664: }
                   7665: 
                   7666: sub auto_checkphotos {
                   7667:     my ($uname,$udom,$pid) = @_;
                   7668:     my $homeserver = &homeserver($uname,$udom);
                   7669:     my ($result,$resulttype);
                   7670:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7671: 				   &escape($uname).':'.&escape($pid),
                   7672: 				   $homeserver));
1.709     albertel 7673:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7674: 	return (undef,undef);
                   7675:     }
1.706     raeburn  7676:     if ($outcome) {
                   7677:         ($result,$resulttype) = split(/:/,$outcome);
                   7678:     } 
                   7679:     return ($result,$resulttype);
                   7680: }
                   7681: 
                   7682: sub auto_photochoice {
                   7683:     my ($cnum,$cdom) = @_;
                   7684:     my $homeserver = &homeserver($cnum,$cdom);
                   7685:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7686: 						       &escape($cdom),
                   7687: 						       $homeserver)));
1.709     albertel 7688:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7689: 	return (undef,undef);
                   7690:     }
1.706     raeburn  7691:     return ($update,$comment);
                   7692: }
                   7693: 
                   7694: sub auto_photoupdate {
                   7695:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7696:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7697:     my $host=&hostname($homeserver);
1.706     raeburn  7698:     my $cmd = '';
                   7699:     my $maxtries = 1;
1.800     albertel 7700:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7701:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7702:     }
                   7703:     $cmd =~ s/%%$//;
                   7704:     $cmd = &escape($cmd);
                   7705:     my $query = 'institutionalphotos';
                   7706:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7707:     unless ($queryid=~/^\Q$host\E\_/) {
                   7708:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7709:         return 'error: '.$queryid;
                   7710:     }
                   7711:     my $reply = &get_query_reply($queryid);
                   7712:     my $tries = 1;
                   7713:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7714:         $reply = &get_query_reply($queryid);
                   7715:         $tries ++;
                   7716:     }
                   7717:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7718:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7719:     } else {
                   7720:         my @responses = split(/:/,$reply);
                   7721:         my $outcome = shift(@responses); 
                   7722:         foreach my $item (@responses) {
                   7723:             my ($key,$value) = split(/=/,$item);
                   7724:             $$photo{$key} = $value;
                   7725:         }
                   7726:         return $outcome;
                   7727:     }
                   7728:     return 'error';
                   7729: }
                   7730: 
1.521     raeburn  7731: sub auto_instcode_format {
1.793     albertel 7732:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7733: 	$cat_order) = @_;
1.521     raeburn  7734:     my $courses = '';
1.772     raeburn  7735:     my @homeservers;
1.521     raeburn  7736:     if ($caller eq 'global') {
1.841     albertel 7737: 	my %servers = &get_servers($codedom,'library');
                   7738: 	foreach my $tryserver (keys(%servers)) {
                   7739: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7740: 		push(@homeservers,$tryserver);
                   7741: 	    }
1.584     raeburn  7742:         }
1.1022    raeburn  7743:     } elsif ($caller eq 'requests') {
                   7744:         if ($codedom =~ /^$match_domain$/) {
                   7745:             my $chome = &domain($codedom,'primary');
                   7746:             unless ($chome eq 'no_host') {
                   7747:                 push(@homeservers,$chome);
                   7748:             }
                   7749:         }
1.521     raeburn  7750:     } else {
1.772     raeburn  7751:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7752:     }
1.793     albertel 7753:     foreach my $code (keys(%{$instcodes})) {
                   7754:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7755:     }
                   7756:     chop($courses);
1.772     raeburn  7757:     my $ok_response = 0;
                   7758:     my $response;
                   7759:     while (@homeservers > 0 && $ok_response == 0) {
                   7760:         my $server = shift(@homeservers); 
                   7761:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7762:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7763:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7764: 		split(/:/,$response);
1.772     raeburn  7765:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7766:             push(@{$codetitles},&str2array($codetitles_str));
                   7767:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7768:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7769:             $ok_response = 1;
                   7770:         }
                   7771:     }
                   7772:     if ($ok_response) {
1.521     raeburn  7773:         return 'ok';
1.772     raeburn  7774:     } else {
                   7775:         return $response;
1.521     raeburn  7776:     }
                   7777: }
                   7778: 
1.792     raeburn  7779: sub auto_instcode_defaults {
                   7780:     my ($domain,$returnhash,$code_order) = @_;
                   7781:     my @homeservers;
1.841     albertel 7782: 
                   7783:     my %servers = &get_servers($domain,'library');
                   7784:     foreach my $tryserver (keys(%servers)) {
                   7785: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7786: 	    push(@homeservers,$tryserver);
                   7787: 	}
1.792     raeburn  7788:     }
1.841     albertel 7789: 
1.792     raeburn  7790:     my $response;
1.841     albertel 7791:     foreach my $server (@homeservers) {
1.792     raeburn  7792:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7793:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7794: 	
                   7795: 	foreach my $pair (split(/\&/,$response)) {
                   7796: 	    my ($name,$value)=split(/\=/,$pair);
                   7797: 	    if ($name eq 'code_order') {
                   7798: 		@{$code_order} = split(/\&/,&unescape($value));
                   7799: 	    } else {
                   7800: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7801: 	    }
                   7802: 	}
                   7803: 	return 'ok';
1.792     raeburn  7804:     }
1.841     albertel 7805: 
                   7806:     return $response;
1.1003    raeburn  7807: }
                   7808: 
                   7809: sub auto_possible_instcodes {
1.1007    raeburn  7810:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7811:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7812:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7813:         return;
                   7814:     }
1.1003    raeburn  7815:     my (@homeservers,$uhome);
                   7816:     if (defined(&domain($domain,'primary'))) {
                   7817:         $uhome=&domain($domain,'primary');
                   7818:         push(@homeservers,&domain($domain,'primary'));
                   7819:     } else {
                   7820:         my %servers = &get_servers($domain,'library');
                   7821:         foreach my $tryserver (keys(%servers)) {
                   7822:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7823:                 push(@homeservers,$tryserver);
                   7824:             }
                   7825:         }
                   7826:     }
                   7827:     my $response;
                   7828:     foreach my $server (@homeservers) {
                   7829:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7830:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7831:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7832:             split(':',$response);
                   7833:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7834:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7835:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7836:             my ($name,$value)=split('=',$item);
                   7837:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7838:         }
                   7839:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7840:             my ($name,$value)=split('=',$item);
                   7841:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7842:         }
                   7843:         return 'ok';
                   7844:     }
                   7845:     return $response;
                   7846: }
1.792     raeburn  7847: 
1.1010    raeburn  7848: sub auto_courserequest_checks {
                   7849:     my ($dom) = @_;
1.1020    raeburn  7850:     my ($homeserver,%validations);
                   7851:     if ($dom =~ /^$match_domain$/) {
                   7852:         $homeserver = &domain($dom,'primary');
                   7853:     }
                   7854:     unless ($homeserver eq 'no_host') {
                   7855:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7856:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7857:             my @items = split(/&/,$response);
                   7858:             foreach my $item (@items) {
                   7859:                 my ($key,$value) = split('=',$item);
                   7860:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7861:             }
                   7862:         }
                   7863:     }
1.1010    raeburn  7864:     return %validations; 
                   7865: }
                   7866: 
1.1020    raeburn  7867: sub auto_courserequest_validation {
                   7868:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7869:     my ($homeserver,$response);
                   7870:     if ($dom =~ /^$match_domain$/) {
                   7871:         $homeserver = &domain($dom,'primary');
                   7872:     }
                   7873:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7874:           
1.1020    raeburn  7875:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7876:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7877:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7878:                                     $homeserver));
                   7879:     }
                   7880:     return $response;
                   7881: }
                   7882: 
1.777     albertel 7883: sub auto_validate_class_sec {
1.918     raeburn  7884:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7885:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7886:     my $ownerlist;
                   7887:     if (ref($owners) eq 'ARRAY') {
                   7888:         $ownerlist = join(',',@{$owners});
                   7889:     } else {
                   7890:         $ownerlist = $owners;
                   7891:     }
1.773     raeburn  7892:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7893:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7894:     return $response;
                   7895: }
                   7896: 
1.679     raeburn  7897: # ------------------------------------------------------- Course Group routines
                   7898: 
                   7899: sub get_coursegroups {
1.809     raeburn  7900:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7901:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7902: }
                   7903: 
1.679     raeburn  7904: sub modify_coursegroup {
                   7905:     my ($cdom,$cnum,$groupsettings) = @_;
                   7906:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7907: }
                   7908: 
1.809     raeburn  7909: sub toggle_coursegroup_status {
                   7910:     my ($cdom,$cnum,$group,$action) = @_;
                   7911:     my ($from_namespace,$to_namespace);
                   7912:     if ($action eq 'delete') {
                   7913:         $from_namespace = 'coursegroups';
                   7914:         $to_namespace = 'deleted_groups';
                   7915:     } else {
                   7916:         $from_namespace = 'deleted_groups';
                   7917:         $to_namespace = 'coursegroups';
                   7918:     }
                   7919:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7920:     if (my $tmp = &error(%curr_group)) {
                   7921:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7922:         return ('read error',$tmp);
                   7923:     } else {
                   7924:         my %savedsettings = %curr_group; 
1.809     raeburn  7925:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7926:         my $deloutcome;
                   7927:         if ($result eq 'ok') {
1.809     raeburn  7928:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7929:         } else {
                   7930:             return ('write error',$result);
                   7931:         }
                   7932:         if ($deloutcome eq 'ok') {
                   7933:             return 'ok';
                   7934:         } else {
                   7935:             return ('delete error',$deloutcome);
                   7936:         }
                   7937:     }
                   7938: }
                   7939: 
1.679     raeburn  7940: sub modify_group_roles {
1.957     raeburn  7941:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7942:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7943:     my $role = 'gr/'.&escape($userprivs);
                   7944:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7945:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7946:     if ($result eq 'ok') {
                   7947:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7948:     }
1.679     raeburn  7949:     return $result;
                   7950: }
                   7951: 
                   7952: sub modify_coursegroup_membership {
                   7953:     my ($cdom,$cnum,$membership) = @_;
                   7954:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7955:     return $result;
                   7956: }
                   7957: 
1.682     raeburn  7958: sub get_active_groups {
                   7959:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7960:     my $now = time;
                   7961:     my %groups = ();
                   7962:     foreach my $key (keys(%env)) {
1.811     albertel 7963:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7964:             my ($start,$end) = split(/\./,$env{$key});
                   7965:             if (($end!=0) && ($end<$now)) { next; }
                   7966:             if (($start!=0) && ($start>$now)) { next; }
                   7967:             if ($1 eq $cdom && $2 eq $cnum) {
                   7968:                 $groups{$3} = $env{$key} ;
                   7969:             }
                   7970:         }
                   7971:     }
                   7972:     return %groups;
                   7973: }
                   7974: 
1.683     raeburn  7975: sub get_group_membership {
                   7976:     my ($cdom,$cnum,$group) = @_;
                   7977:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7978: }
                   7979: 
                   7980: sub get_users_groups {
                   7981:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7982:     my @usersgroups;
1.683     raeburn  7983:     my $cachetime=1800;
                   7984: 
                   7985:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7986:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7987:     if (defined($cached)) {
1.734     albertel 7988:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7989:     } else {  
                   7990:         $grouplist = '';
1.816     raeburn  7991:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7992:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7993:         my $access_end = $env{'course.'.$courseid.
                   7994:                               '.default_enrollment_end_date'};
                   7995:         my $now = time;
                   7996:         foreach my $key (keys(%roleshash)) {
                   7997:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7998:                 my $group = $1;
                   7999:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8000:                     my $start = $2;
                   8001:                     my $end = $1;
                   8002:                     if ($start == -1) { next; } # deleted from group
                   8003:                     if (($start!=0) && ($start>$now)) { next; }
                   8004:                     if (($end!=0) && ($end<$now)) {
                   8005:                         if ($access_end && $access_end < $now) {
                   8006:                             if ($access_end - $end < 86400) {
                   8007:                                 push(@usersgroups,$group);
1.733     raeburn  8008:                             }
                   8009:                         }
1.817     raeburn  8010:                         next;
1.733     raeburn  8011:                     }
1.817     raeburn  8012:                     push(@usersgroups,$group);
1.683     raeburn  8013:                 }
                   8014:             }
                   8015:         }
1.817     raeburn  8016:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8017:         $grouplist = join(':',@usersgroups);
                   8018:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8019:     }
1.733     raeburn  8020:     return @usersgroups;
1.683     raeburn  8021: }
                   8022: 
                   8023: sub devalidate_getgroups_cache {
                   8024:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8025:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8026: 
1.683     raeburn  8027:     my $hashid="$udom:$uname:$courseid";
                   8028:     &devalidate_cache_new('getgroups',$hashid);
                   8029: }
                   8030: 
1.12      www      8031: # ------------------------------------------------------------------ Plain Text
                   8032: 
                   8033: sub plaintext {
1.988     raeburn  8034:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8035:     if ($short =~ m{^cr/}) {
1.758     albertel 8036: 	return (split('/',$short))[-1];
                   8037:     }
1.742     raeburn  8038:     if (!defined($cid)) {
                   8039:         $cid = $env{'request.course.id'};
                   8040:     }
                   8041:     my %rolenames = (
1.1008    raeburn  8042:                       Course    => 'std',
                   8043:                       Community => 'alt1',
1.742     raeburn  8044:                     );
1.1037    raeburn  8045:     if ($cid ne '') {
                   8046:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8047:             unless ($forcedefault) {
                   8048:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8049:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8050:                 return &Apache::lonlocal::mt($roletext);
                   8051:             }
                   8052:         }
                   8053:     }
                   8054:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8055:         (defined($rolenames{$type})) && 
                   8056:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8057:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8058:     } elsif ($cid ne '') {
                   8059:         my $crstype = $env{'course.'.$cid.'.type'};
                   8060:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8061:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8062:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8063:         }
1.742     raeburn  8064:     }
1.1037    raeburn  8065:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8066: }
                   8067: 
                   8068: # ----------------------------------------------------------------- Assign Role
                   8069: 
                   8070: sub assignrole {
1.957     raeburn  8071:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8072:         $context)=@_;
1.21      www      8073:     my $mrole;
                   8074:     if ($role =~ /^cr\//) {
1.393     www      8075:         my $cwosec=$url;
1.811     albertel 8076:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8077: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8078:            my $refused = 1;
                   8079:            if ($context eq 'requestcourses') {
                   8080:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8081:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8082:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8083:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8084:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8085:                            if ($crsenv{'internal.courseowner'} eq
                   8086:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8087:                                $refused = '';
                   8088:                            }
                   8089:                        }
                   8090:                    }
                   8091:                }
                   8092:            }
                   8093:            if ($refused) {
                   8094:                &logthis('Refused custom assignrole: '.
                   8095:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8096:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8097:                return 'refused';
                   8098:            }
1.104     www      8099:         }
1.21      www      8100:         $mrole='cr';
1.678     raeburn  8101:     } elsif ($role =~ /^gr\//) {
                   8102:         my $cwogrp=$url;
1.811     albertel 8103:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8104:         unless (&allowed('mdg',$cwogrp)) {
                   8105:             &logthis('Refused group assignrole: '.
                   8106:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8107:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8108:             return 'refused';
                   8109:         }
                   8110:         $mrole='gr';
1.21      www      8111:     } else {
1.82      www      8112:         my $cwosec=$url;
1.811     albertel 8113:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8114:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8115:             my $refused;
                   8116:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8117:                 if (!(&allowed('c'.$role,$url))) {
                   8118:                     $refused = 1;
                   8119:                 }
                   8120:             } else {
                   8121:                 $refused = 1;
                   8122:             }
1.947     raeburn  8123:             if ($refused) {
1.1045    raeburn  8124:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8125:                 if (!$selfenroll && $context eq 'course') {
                   8126:                     my %crsenv;
                   8127:                     if ($role eq 'cc' || $role eq 'co') {
                   8128:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8129:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8130:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8131:                                 if ($crsenv{'internal.courseowner'} eq 
                   8132:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8133:                                     $refused = '';
                   8134:                                 }
                   8135:                             }
                   8136:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8137:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8138:                                 if ($crsenv{'internal.courseowner'} eq 
                   8139:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8140:                                     $refused = '';
                   8141:                                 }
                   8142:                             }
                   8143:                         }
                   8144:                     }
                   8145:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8146:                     $refused = '';
1.1017    raeburn  8147:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8148:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8149:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8150:                         my $wrongcc;
                   8151:                         if ($cnum =~ /^$match_community$/) {
                   8152:                             $wrongcc = 1 if ($role eq 'cc');
                   8153:                         } else {
                   8154:                             $wrongcc = 1 if ($role eq 'co');
                   8155:                         }
                   8156:                         unless ($wrongcc) {
                   8157:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8158:                             if ($crsenv{'internal.courseowner'} eq 
                   8159:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8160:                                 $refused = '';
                   8161:                             }
1.1017    raeburn  8162:                         }
                   8163:                     }
1.1172.2.9  raeburn  8164:                 } elsif ($context eq 'requestauthor') {
                   8165:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8166:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8167:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8168:                             $refused = '';
                   8169:                         } else {
                   8170:                             my %domdefaults = &get_domain_defaults($udom);
                   8171:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8172:                                 my $checkbystatus;
                   8173:                                 if ($env{'user.adv'}) {
                   8174:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8175:                                     if ($disposition eq 'automatic') {
                   8176:                                         $refused = '';
                   8177:                                     } elsif ($disposition eq '') {
                   8178:                                         $checkbystatus = 1;
                   8179:                                     }
                   8180:                                 } else {
                   8181:                                     $checkbystatus = 1;
                   8182:                                 }
                   8183:                                 if ($checkbystatus) {
                   8184:                                     if ($env{'environment.inststatus'}) {
                   8185:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8186:                                         foreach my $type (@inststatuses) {
                   8187:                                             if (($type ne '') &&
                   8188:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8189:                                                 $refused = '';
                   8190:                                             }
                   8191:                                         }
                   8192:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8193:                                         $refused = '';
                   8194:                                     }
                   8195:                                 }
                   8196:                             }
                   8197:                         }
                   8198:                     }
1.1017    raeburn  8199:                 }
                   8200:                 if ($refused) {
1.947     raeburn  8201:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8202:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8203: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8204:                     return 'refused';
                   8205:                 }
1.932     raeburn  8206:             }
1.1131    raeburn  8207:         } elsif ($role eq 'au') {
                   8208:             if ($url ne '/'.$udom.'/') {
                   8209:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8210:                          ' to assign author role for '.$uname.':'.$udom.
                   8211:                          ' in domain: '.$url.' refused (wrong domain).');
                   8212:                 return 'refused';
                   8213:             }
1.104     www      8214:         }
1.21      www      8215:         $mrole=$role;
                   8216:     }
1.620     albertel 8217:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8218:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8219:     if ($end) { $command.='_'.$end; }
1.21      www      8220:     if ($start) {
                   8221: 	if ($end) { 
1.81      www      8222:            $command.='_'.$start; 
1.21      www      8223:         } else {
1.81      www      8224:            $command.='_0_'.$start;
1.21      www      8225:         }
                   8226:     }
1.739     raeburn  8227:     my $origstart = $start;
                   8228:     my $origend = $end;
1.957     raeburn  8229:     my $delflag;
1.357     www      8230: # actually delete
                   8231:     if ($deleteflag) {
1.373     www      8232: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8233: # modify command to delete the role
1.620     albertel 8234:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8235:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8236: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8237: # set start and finish to negative values for userrolelog
                   8238:            $start=-1;
                   8239:            $end=-1;
1.957     raeburn  8240:            $delflag = 1;
1.357     www      8241:         }
                   8242:     }
                   8243: # send command
1.349     www      8244:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8245: # log new user role if status is ok
1.349     www      8246:     if ($answer eq 'ok') {
1.663     raeburn  8247: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8248:         if (($role eq 'cc') || ($role eq 'in') ||
                   8249:             ($role eq 'ep') || ($role eq 'ad') ||
                   8250:             ($role eq 'ta') || ($role eq 'st') ||
                   8251:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8252:             ($role eq 'co')) {
1.1172.2.13  raeburn  8253: # for course roles, perform group memberships changes triggered by role change.
                   8254:             unless ($role =~ /^gr/) {
                   8255:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8256:                                                  $origstart,$selfenroll,$context);
                   8257:             }
1.1172.2.9  raeburn  8258:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8259:                            $selfenroll,$context);
                   8260:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8261:                  ($role eq 'au') || ($role eq 'dc')) {
                   8262:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8263:                            $context);
                   8264:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8265:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8266:                              $context);
                   8267:         }
1.1053    raeburn  8268:         if ($role eq 'cc') {
                   8269:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8270:         }
1.349     www      8271:     }
                   8272:     return $answer;
1.169     harris41 8273: }
                   8274: 
1.1053    raeburn  8275: sub autoupdate_coowners {
                   8276:     my ($url,$end,$start,$uname,$udom) = @_;
                   8277:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8278:     if (($cdom ne '') && ($cnum ne '')) {
                   8279:         my $now = time;
                   8280:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8281:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8282:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8283:             my $instcode = $coursehash{'internal.coursecode'};
                   8284:             if ($instcode ne '') {
1.1056    raeburn  8285:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8286:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8287:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8288:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8289:                         if ($result eq 'valid') {
                   8290:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8291:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8292:                                     push(@newcoowners,$coowner);
                   8293:                                 }
                   8294:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8295:                                     push(@newcoowners,$uname.':'.$udom);
                   8296:                                 }
                   8297:                                 @newcoowners = sort(@newcoowners);
                   8298:                             } else {
                   8299:                                 push(@newcoowners,$uname.':'.$udom);
                   8300:                             }
                   8301:                         } else {
                   8302:                             if ($coursehash{'internal.co-owners'}) {
                   8303:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8304:                                     unless ($coowner eq $uname.':'.$udom) {
                   8305:                                         push(@newcoowners,$coowner);
                   8306:                                     }
                   8307:                                 }
                   8308:                                 unless (@newcoowners > 0) {
                   8309:                                     $delcoowners = 1;
                   8310:                                     $coowners = '';
                   8311:                                 }
                   8312:                             }
                   8313:                         }
                   8314:                         if (@newcoowners || $delcoowners) {
                   8315:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8316:                                             $delcoowners,@newcoowners);
                   8317:                         }
                   8318:                     }
                   8319:                 }
                   8320:             }
                   8321:         }
                   8322:     }
                   8323: }
                   8324: 
                   8325: sub store_coowners {
                   8326:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8327:     my $cid = $cdom.'_'.$cnum;
                   8328:     my ($coowners,$delresult,$putresult);
                   8329:     if (@newcoowners) {
                   8330:         $coowners = join(',',@newcoowners);
                   8331:         my %coownershash = (
                   8332:                             'internal.co-owners' => $coowners,
                   8333:                            );
                   8334:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8335:         if ($putresult eq 'ok') {
                   8336:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8337:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8338:             }
                   8339:         }
                   8340:     }
                   8341:     if ($delcoowners) {
                   8342:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8343:         if ($delresult eq 'ok') {
                   8344:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8345:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8346:             }
                   8347:         }
                   8348:     }
                   8349:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8350:         my %crsinfo =
                   8351:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8352:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8353:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8354:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8355:         }
                   8356:     }
                   8357: }
                   8358: 
1.169     harris41 8359: # -------------------------------------------------- Modify user authentication
1.197     www      8360: # Overrides without validation
                   8361: 
1.169     harris41 8362: sub modifyuserauth {
                   8363:     my ($udom,$uname,$umode,$upass)=@_;
                   8364:     my $uhome=&homeserver($uname,$udom);
1.197     www      8365:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8366:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8367:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8368:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8369:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8370: 		     &escape($upass),$uhome);
1.620     albertel 8371:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8372:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8373:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8374:     &log($udom,,$uname,$uhome,
1.620     albertel 8375:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8376:                                      $env{'user.name'}.', '.$umode.
1.197     www      8377:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8378:     unless ($reply eq 'ok') {
1.197     www      8379:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8380: 	return 'error: '.$reply;
                   8381:     }   
1.170     harris41 8382:     return 'ok';
1.80      www      8383: }
                   8384: 
1.81      www      8385: # --------------------------------------------------------------- Modify a user
1.80      www      8386: 
1.81      www      8387: sub modifyuser {
1.206     matthew  8388:     my ($udom,    $uname, $uid,
                   8389:         $umode,   $upass, $first,
                   8390:         $middle,  $last,  $gene,
1.1058    raeburn  8391:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8392:     $udom= &LONCAPA::clean_domain($udom);
                   8393:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8394:     my $showcandelete = 'none';
                   8395:     if (ref($candelete) eq 'ARRAY') {
                   8396:         if (@{$candelete} > 0) {
                   8397:             $showcandelete = join(', ',@{$candelete});
                   8398:         }
                   8399:     }
1.81      www      8400:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8401:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8402: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8403:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8404:                                      ' desiredhome not specified'). 
1.620     albertel 8405:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8406:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8407:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8408:     my $newuser;
                   8409:     if ($uhome eq 'no_host') {
                   8410:         $newuser = 1;
                   8411:     }
1.80      www      8412: # ----------------------------------------------------------------- Create User
1.406     albertel 8413:     if (($uhome eq 'no_host') && 
                   8414: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8415:         my $unhome='';
1.844     albertel 8416:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8417:             $unhome = $desiredhome;
1.620     albertel 8418: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8419: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8420:         } else { # load balancing routine for determining $unhome
1.81      www      8421:             my $loadm=10000000;
1.841     albertel 8422: 	    my %servers = &get_servers($udom,'library');
                   8423: 	    foreach my $tryserver (keys(%servers)) {
                   8424: 		my $answer=reply('load',$tryserver);
                   8425: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8426: 		    $loadm=$answer;
                   8427: 		    $unhome=$tryserver;
                   8428: 		}
1.80      www      8429: 	    }
                   8430:         }
                   8431:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8432: 	    return 'error: unable to find a home server for '.$uname.
                   8433:                    ' in domain '.$udom;
1.80      www      8434:         }
                   8435:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8436:                          &escape($upass),$unhome);
                   8437: 	unless ($reply eq 'ok') {
                   8438:             return 'error: '.$reply;
                   8439:         }   
1.230     stredwic 8440:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8441:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8442: 	    return 'error: unable verify users home machine.';
1.80      www      8443:         }
1.209     matthew  8444:     }   # End of creation of new user
1.80      www      8445: # ---------------------------------------------------------------------- Add ID
                   8446:     if ($uid) {
                   8447:        $uid=~tr/A-Z/a-z/;
                   8448:        my %uidhash=&idrget($udom,$uname);
1.196     www      8449:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8450:          && (!$forceid)) {
1.80      www      8451: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8452: 	      return 'error: user id "'.$uid.'" does not match '.
                   8453:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8454:           }
                   8455:        } else {
                   8456: 	  &idput($udom,($uname => $uid));
                   8457:        }
                   8458:     }
                   8459: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8460:     my @tmp=&get('environment',
1.899     raeburn  8461: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8462:                     'permanentemail','inststatus'],
1.134     albertel 8463: 		   $udom,$uname);
1.1075    raeburn  8464:     my (%names,%oldnames);
1.313     matthew  8465:     if ($tmp[0] =~ m/^error:.*/) { 
                   8466:         %names=(); 
                   8467:     } else {
                   8468:         %names = @tmp;
1.1075    raeburn  8469:         %oldnames = %names;
1.313     matthew  8470:     }
1.388     www      8471: #
1.1058    raeburn  8472: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8473: # of users did not contain them), do not overwrite existing values
                   8474: # unless field is in $candelete array ref.  
                   8475: #
                   8476: 
                   8477:     my @fields = ('firstname','middlename','lastname','generation',
                   8478:                   'permanentemail','id');
                   8479:     my %newvalues;
                   8480:     if (ref($candelete) eq 'ARRAY') {
                   8481:         foreach my $field (@fields) {
                   8482:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8483:                 if ($field eq 'firstname') {
                   8484:                     $names{$field} = $first;
                   8485:                 } elsif ($field eq 'middlename') {
                   8486:                     $names{$field} = $middle;
                   8487:                 } elsif ($field eq 'lastname') {
                   8488:                     $names{$field} = $last;
                   8489:                 } elsif ($field eq 'generation') { 
                   8490:                     $names{$field} = $gene;
                   8491:                 } elsif ($field eq 'permanentemail') {
                   8492:                     $names{$field} = $email;
                   8493:                 } elsif ($field eq 'id') {
                   8494:                     $names{$field}  = $uid;
                   8495:                 }
                   8496:             }
                   8497:         }
                   8498:     }
1.388     www      8499:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8500:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8501:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8502:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8503:     if ($email) {
                   8504:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8505:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8506:     }
1.899     raeburn  8507:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8508:     if (defined($inststatus)) {
                   8509:         $names{'inststatus'} = '';
                   8510:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8511:         if (ref($usertypes) eq 'HASH') {
                   8512:             my @okstatuses; 
                   8513:             foreach my $item (split(/:/,$inststatus)) {
                   8514:                 if (defined($usertypes->{$item})) {
                   8515:                     push(@okstatuses,$item);  
                   8516:                 }
                   8517:             }
                   8518:             if (@okstatuses) {
                   8519:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8520:             }
                   8521:         }
                   8522:     }
1.1075    raeburn  8523:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8524:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8525:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8526:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8527:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8528:     } else {
                   8529:         $logmsg .= ' during self creation';
                   8530:     }
1.1075    raeburn  8531:     my $changed;
                   8532:     if ($newuser) {
                   8533:         $changed = 1;
                   8534:     } else {
                   8535:         foreach my $field (@fields) {
                   8536:             if ($names{$field} ne $oldnames{$field}) {
                   8537:                 $changed = 1;
                   8538:                 last;
                   8539:             }
                   8540:         }
                   8541:     }
                   8542:     unless ($changed) {
                   8543:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8544:         &logthis($logmsg);
                   8545:         return 'ok';
                   8546:     }
                   8547:     my $reply = &put('environment', \%names, $udom,$uname);
                   8548:     if ($reply ne 'ok') { 
                   8549:         return 'error: '.$reply;
                   8550:     }
1.1087    raeburn  8551:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8552:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8553:     }
1.1075    raeburn  8554:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8555:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8556:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8557:     &logthis($logmsg);
1.134     albertel 8558:     return 'ok';
1.80      www      8559: }
                   8560: 
1.81      www      8561: # -------------------------------------------------------------- Modify student
1.80      www      8562: 
1.81      www      8563: sub modifystudent {
                   8564:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8565:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8566:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8567:     if (!$cid) {
1.620     albertel 8568: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8569: 	    return 'not_in_class';
                   8570: 	}
1.80      www      8571:     }
                   8572: # --------------------------------------------------------------- Make the user
1.81      www      8573:     my $reply=&modifyuser
1.209     matthew  8574: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8575:          $desiredhome,$email,$inststatus);
1.80      www      8576:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8577:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8578:     # student's environment
1.297     matthew  8579:     $uid = undef if (!$forceid);
1.455     albertel 8580:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8581: 					$gene,$usec,$end,$start,$type,$locktype,
                   8582:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8583:     return $reply;
                   8584: }
                   8585: 
                   8586: sub modify_student_enrollment {
1.1172.2.23  raeburn  8587:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8588:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8589:     my ($cdom,$cnum,$chome);
                   8590:     if (!$cid) {
1.620     albertel 8591: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8592: 	    return 'not_in_class';
                   8593: 	}
1.620     albertel 8594: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8595: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8596:     } else {
                   8597: 	($cdom,$cnum)=split(/_/,$cid);
                   8598:     }
1.620     albertel 8599:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8600:     if (!$chome) {
1.457     raeburn  8601: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8602:     }
1.455     albertel 8603:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8604:     # Make sure the user exists
1.81      www      8605:     my $uhome=&homeserver($uname,$udom);
                   8606:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8607: 	return 'error: no such user';
                   8608:     }
1.297     matthew  8609:     # Get student data if we were not given enough information
                   8610:     if (!defined($first)  || $first  eq '' || 
                   8611:         !defined($last)   || $last   eq '' || 
                   8612:         !defined($uid)    || $uid    eq '' || 
                   8613:         !defined($middle) || $middle eq '' || 
                   8614:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8615:         # They did not supply us with enough data to enroll the student, so
                   8616:         # we need to pick up more information.
1.297     matthew  8617:         my %tmp = &get('environment',
1.294     matthew  8618:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8619:                        ,$udom,$uname);
                   8620: 
1.800     albertel 8621:         #foreach my $key (keys(%tmp)) {
                   8622:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8623:         #}
1.294     matthew  8624:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8625:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8626:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8627:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8628:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8629:     }
1.556     albertel 8630:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8631:     my $user = "$uname:$udom";
                   8632:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8633:     my $reply=cput('classlist',
1.1148    raeburn  8634: 		   {$user => 
1.1172.2.19  raeburn  8635: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8636: 		   $cdom,$cnum);
1.1148    raeburn  8637:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8638:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8639:     } else { 
1.81      www      8640: 	return 'error: '.$reply;
                   8641:     }
1.297     matthew  8642:     # Add student role to user
1.83      www      8643:     my $uurl='/'.$cid;
1.81      www      8644:     $uurl=~s/\_/\//g;
                   8645:     if ($usec) {
                   8646: 	$uurl.='/'.$usec;
                   8647:     }
1.1148    raeburn  8648:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8649:                              $selfenroll,$context);
                   8650:     if ($result ne 'ok') {
                   8651:         if ($old_entry{$user} ne '') {
                   8652:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8653:         } else {
                   8654:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8655:         }
                   8656:     }
                   8657:     return $result; 
1.21      www      8658: }
                   8659: 
1.556     albertel 8660: sub format_name {
                   8661:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8662:     my $name;
                   8663:     if ($first ne 'lastname') {
                   8664: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8665:     } else {
                   8666: 	if ($lastname=~/\S/) {
                   8667: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8668: 	    $name=~s/\s+,/,/;
                   8669: 	} else {
                   8670: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8671: 	}
                   8672:     }
                   8673:     $name=~s/^\s+//;
                   8674:     $name=~s/\s+$//;
                   8675:     $name=~s/\s+/ /g;
                   8676:     return $name;
                   8677: }
                   8678: 
1.84      www      8679: # ------------------------------------------------- Write to course preferences
                   8680: 
                   8681: sub writecoursepref {
                   8682:     my ($courseid,%prefs)=@_;
                   8683:     $courseid=~s/^\///;
                   8684:     $courseid=~s/\_/\//g;
                   8685:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8686:     my $chome=homeserver($cnum,$cdomain);
                   8687:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8688: 	return 'error: no such course';
                   8689:     }
                   8690:     my $cstring='';
1.800     albertel 8691:     foreach my $pref (keys(%prefs)) {
                   8692: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8693:     }
1.84      www      8694:     $cstring=~s/\&$//;
                   8695:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8696: }
                   8697: 
                   8698: # ---------------------------------------------------------- Make/modify course
                   8699: 
                   8700: sub createcourse {
1.741     raeburn  8701:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8702:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8703:     $url=&declutter($url);
                   8704:     my $cid='';
1.1028    raeburn  8705:     if ($context eq 'requestcourses') {
                   8706:         my $can_create = 0;
                   8707:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8708:         if ($udom eq $ownerdom) {
                   8709:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8710:                                   $context)) {
                   8711:                 $can_create = 1;
                   8712:             }
                   8713:         } else {
                   8714:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8715:                                            $category);
                   8716:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8717:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8718:                 if (@curr > 0) {
                   8719:                     my @options = qw(approval validate autolimit);
                   8720:                     my $optregex = join('|',@options);
                   8721:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8722:                         $can_create = 1;
                   8723:                     }
                   8724:                 }
                   8725:             }
                   8726:         }
                   8727:         if ($can_create) {
                   8728:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8729:                 unless (&allowed('ccc',$udom)) {
                   8730:                     return 'refused'; 
                   8731:                 }
1.1017    raeburn  8732:             }
                   8733:         } else {
                   8734:             return 'refused';
                   8735:         }
1.1028    raeburn  8736:     } elsif (!&allowed('ccc',$udom)) {
                   8737:         return 'refused';
1.84      www      8738:     }
1.1011    raeburn  8739: # --------------------------------------------------------------- Get Unique ID
                   8740:     my $uname;
                   8741:     if ($cnum =~ /^$match_courseid$/) {
                   8742:         my $chome=&homeserver($cnum,$udom,'true');
                   8743:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8744:             $uname = $cnum;
                   8745:         } else {
1.1038    raeburn  8746:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8747:         }
                   8748:     } else {
1.1038    raeburn  8749:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8750:     }
                   8751:     return $uname if ($uname =~ /^error/);
                   8752: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8753:     if (!defined($course_server)) {
                   8754:         if (defined(&domain($udom,'primary'))) {
                   8755:             $course_server = &domain($udom,'primary');
                   8756:         } else {
                   8757:             $course_server = $env{'user.home'}; 
                   8758:         }
                   8759:     }
                   8760:     my %host_servers =
                   8761:         &Apache::lonnet::get_servers($udom,'library');
                   8762:     unless ($host_servers{$course_server}) {
                   8763:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8764:     }
1.84      www      8765: # ------------------------------------------------------------- Make the course
                   8766:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8767:                       $course_server);
1.84      www      8768:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8769:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8770:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8771: 	return 'error: no such course';
                   8772:     }
1.271     www      8773: # ----------------------------------------------------------------- Course made
1.516     raeburn  8774: # log existence
1.1029    raeburn  8775:     my $now = time;
1.918     raeburn  8776:     my $newcourse = {
                   8777:                     $udom.'_'.$uname => {
1.921     raeburn  8778:                                      description => $description,
                   8779:                                      inst_code   => $inst_code,
                   8780:                                      owner       => $course_owner,
                   8781:                                      type        => $crstype,
1.1029    raeburn  8782:                                      creator     => $env{'user.name'}.':'.
                   8783:                                                     $env{'user.domain'},
                   8784:                                      created     => $now,
                   8785:                                      context     => $context,
1.918     raeburn  8786:                                                 },
                   8787:                     };
1.921     raeburn  8788:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8789: # set toplevel url
1.271     www      8790:     my $topurl=$url;
                   8791:     unless ($nonstandard) {
                   8792: # ------------------------------------------ For standard courses, make top url
                   8793:         my $mapurl=&clutter($url);
1.278     www      8794:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8795:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8796: <map>
                   8797: <resource id="1" type="start"></resource>
                   8798: <resource id="2" src="$mapurl"></resource>
                   8799: <resource id="3" type="finish"></resource>
                   8800: <link index="1" from="1" to="2"></link>
                   8801: <link index="2" from="2" to="3"></link>
                   8802: </map>
                   8803: ENDINITMAP
                   8804:         $topurl=&declutter(
1.638     albertel 8805:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8806:                           );
                   8807:     }
                   8808: # ----------------------------------------------------------- Write preferences
1.84      www      8809:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8810:                      ('description'              => $description,
                   8811:                       'url'                      => $topurl,
                   8812:                       'internal.creator'         => $env{'user.name'}.':'.
                   8813:                                                     $env{'user.domain'},
                   8814:                       'internal.created'         => $now,
                   8815:                       'internal.creationcontext' => $context)
                   8816:                     );
1.84      www      8817:     return '/'.$udom.'/'.$uname;
                   8818: }
                   8819: 
1.1011    raeburn  8820: # ------------------------------------------------------------------- Create ID
                   8821: sub generate_coursenum {
1.1038    raeburn  8822:     my ($udom,$crstype) = @_;
1.1011    raeburn  8823:     my $domdesc = &domain($udom);
                   8824:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8825:     my $first;
                   8826:     if ($crstype eq 'Community') {
                   8827:         $first = '0';
                   8828:     } else {
                   8829:         $first = int(1+rand(9)); 
                   8830:     } 
                   8831:     my $uname=$first.
1.1011    raeburn  8832:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8833:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8834:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8835: # ----------------------------------------------- Make sure that does not exist
                   8836:     my $uhome=&homeserver($uname,$udom,'true');
                   8837:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8838:         if ($crstype eq 'Community') {
                   8839:             $first = '0';
                   8840:         } else {
                   8841:             $first = int(1+rand(9));
                   8842:         }
                   8843:         $uname=$first.
1.1011    raeburn  8844:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8845:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8846:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8847:         $uhome=&homeserver($uname,$udom,'true');
                   8848:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8849:             return 'error: unable to generate unique course-ID';
                   8850:         }
                   8851:     }
                   8852:     return $uname;
                   8853: }
                   8854: 
1.813     albertel 8855: sub is_course {
1.1167    droeschl 8856:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8857:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8858: 
                   8859:     return unless $cdom and $cnum;
                   8860: 
                   8861:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8862:         '.');
                   8863: 
1.1172.2.23  raeburn  8864:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8865:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8866: }
                   8867: 
1.1015    raeburn  8868: sub store_userdata {
                   8869:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8870:     my $result;
1.1016    raeburn  8871:     if ($datakey ne '') {
1.1013    raeburn  8872:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8873:             if ($udom eq '' || $uname eq '') {
                   8874:                 $udom = $env{'user.domain'};
                   8875:                 $uname = $env{'user.name'};
                   8876:             }
                   8877:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8878:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8879:                 $result = 'error: no_host';
                   8880:             } else {
                   8881:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8882:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8883: 
                   8884:                 my $namevalue='';
                   8885:                 foreach my $key (keys(%{$storehash})) {
                   8886:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8887:                 }
                   8888:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  8889:                 unless ($namespace eq 'courserequests') {
                   8890:                     $datakey = &escape($datakey);
                   8891:                 }
1.1105    raeburn  8892:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8893:                                   $namevalue,$uhome);
1.1013    raeburn  8894:             }
                   8895:         } else {
                   8896:             $result = 'error: data to store was not a hash reference'; 
                   8897:         }
                   8898:     } else {
                   8899:         $result= 'error: invalid requestkey'; 
                   8900:     }
                   8901:     return $result;
                   8902: }
                   8903: 
1.21      www      8904: # ---------------------------------------------------------- Assign Custom Role
                   8905: 
                   8906: sub assigncustomrole {
1.957     raeburn  8907:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8908:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8909:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8910: }
                   8911: 
                   8912: # ----------------------------------------------------------------- Revoke Role
                   8913: 
                   8914: sub revokerole {
1.957     raeburn  8915:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8916:     my $now=time;
1.965     raeburn  8917:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8918: }
                   8919: 
                   8920: # ---------------------------------------------------------- Revoke Custom Role
                   8921: 
                   8922: sub revokecustomrole {
1.957     raeburn  8923:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8924:     my $now=time;
1.357     www      8925:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8926:            $deleteflag,$selfenroll,$context);
1.17      www      8927: }
                   8928: 
1.533     banghart 8929: # ------------------------------------------------------------ Disk usage
1.535     albertel 8930: sub diskusage {
1.955     raeburn  8931:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8932:     $directorypath =~ s/\/$//;
                   8933:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8934:                        .&escape($getpropath).':'.&escape($uname).':'
                   8935:                        .&escape($udom),homeserver($uname,$udom));
                   8936:     if ($listing eq 'unknown_cmd') {
                   8937:         if ($getpropath) {
                   8938:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8939:         }
                   8940:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8941:     }
1.514     albertel 8942:     return $listing;
1.512     banghart 8943: }
                   8944: 
1.566     banghart 8945: sub is_locked {
1.1096    raeburn  8946:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8947:     my @check;
                   8948:     my $is_locked;
1.1093    raeburn  8949:     push (@check,$file_name);
1.613     albertel 8950:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8951: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8952:     my ($tmp)=keys(%locked);
                   8953:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8954:     
1.566     banghart 8955:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8956:         $is_locked = 'false';
                   8957:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8958:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8959:                $is_locked = 'true';
1.1096    raeburn  8960:                if (ref($which) eq 'ARRAY') {
                   8961:                    push(@{$which},$entry);
                   8962:                } else {
                   8963:                    last;
                   8964:                }
1.745     raeburn  8965:            }
                   8966:        }
1.566     banghart 8967:     } else {
                   8968:         $is_locked = 'false';
                   8969:     }
1.1093    raeburn  8970:     return $is_locked;
1.566     banghart 8971: }
                   8972: 
1.759     albertel 8973: sub declutter_portfile {
                   8974:     my ($file) = @_;
1.833     albertel 8975:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8976:     return $file;
                   8977: }
                   8978: 
1.559     banghart 8979: # ------------------------------------------------------------- Mark as Read Only
                   8980: 
                   8981: sub mark_as_readonly {
                   8982:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8983:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8984:     my ($tmp)=keys(%current_permissions);
                   8985:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8986:     foreach my $file (@{$files}) {
1.759     albertel 8987: 	$file = &declutter_portfile($file);
1.561     banghart 8988:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8989:     }
1.613     albertel 8990:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8991:     return;
                   8992: }
                   8993: 
1.572     banghart 8994: # ------------------------------------------------------------Save Selected Files
                   8995: 
                   8996: sub save_selected_files {
                   8997:     my ($user, $path, @files) = @_;
                   8998:     my $filename = $user."savedfiles";
1.573     banghart 8999:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9000:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9001:     foreach my $file (@files) {
1.620     albertel 9002:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9003:     }
                   9004:     foreach my $file (@other_files) {
1.574     banghart 9005:         print (OUT $file."\n");
1.572     banghart 9006:     }
1.574     banghart 9007:     close (OUT);
1.572     banghart 9008:     return 'ok';
                   9009: }
                   9010: 
1.574     banghart 9011: sub clear_selected_files {
                   9012:     my ($user) = @_;
                   9013:     my $filename = $user."savedfiles";
1.1117    foxr     9014:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9015:     print (OUT undef);
                   9016:     close (OUT);
                   9017:     return ("ok");    
                   9018: }
                   9019: 
1.572     banghart 9020: sub files_in_path {
                   9021:     my ($user, $path) = @_;
                   9022:     my $filename = $user."savedfiles";
                   9023:     my %return_files;
1.1117    foxr     9024:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9025:     while (my $line_in = <IN>) {
1.574     banghart 9026:         chomp ($line_in);
                   9027:         my @paths_and_file = split (m!/!, $line_in);
                   9028:         my $file_part = pop (@paths_and_file);
                   9029:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9030:         $path_part.='/';
                   9031:         my $path_and_file = $path_part.$file_part;
                   9032:         if ($path_part eq $path) {
                   9033:             $return_files{$file_part}= 'selected';
                   9034:         }
                   9035:     }
1.574     banghart 9036:     close (IN);
                   9037:     return (\%return_files);
1.572     banghart 9038: }
                   9039: 
                   9040: # called in portfolio select mode, to show files selected NOT in current directory
                   9041: sub files_not_in_path {
                   9042:     my ($user, $path) = @_;
                   9043:     my $filename = $user."savedfiles";
                   9044:     my @return_files;
                   9045:     my $path_part;
1.1117    foxr     9046:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9047:     while (my $line = <IN>) {
1.572     banghart 9048:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9049:         my @paths_and_file = split(m|/|, $line);
                   9050:         my $file_part = pop(@paths_and_file);
                   9051:         chomp($file_part);
                   9052:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9053:         $path_part .= '/';
                   9054:         my $path_and_file = $path_part.$file_part;
                   9055:         if ($path_part ne $path) {
1.800     albertel 9056:             push(@return_files, ($path_and_file));
1.572     banghart 9057:         }
                   9058:     }
1.800     albertel 9059:     close(OUT);
1.574     banghart 9060:     return (@return_files);
1.572     banghart 9061: }
                   9062: 
1.745     raeburn  9063: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9064: 
1.745     raeburn  9065: sub get_portfile_permissions {
                   9066:     my ($domain,$user) = @_;
1.613     albertel 9067:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9068:     my ($tmp)=keys(%current_permissions);
                   9069:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9070:     return \%current_permissions;
                   9071: }
                   9072: 
                   9073: #---------------------------------------------Get portfolio file access controls
                   9074: 
1.749     raeburn  9075: sub get_access_controls {
1.745     raeburn  9076:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9077:     my %access;
                   9078:     my $real_file = $file;
                   9079:     $file =~ s/\.meta$//;
1.745     raeburn  9080:     if (defined($file)) {
1.749     raeburn  9081:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9082:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9083:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9084:             }
                   9085:         }
1.745     raeburn  9086:     } else {
1.749     raeburn  9087:         foreach my $key (keys(%{$current_permissions})) {
                   9088:             if ($key =~ /\0accesscontrol$/) {
                   9089:                 if (defined($group)) {
                   9090:                     if ($key !~ m-^\Q$group\E/-) {
                   9091:                         next;
                   9092:                     }
                   9093:                 }
                   9094:                 my ($fullpath) = split(/\0/,$key);
                   9095:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9096:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9097:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9098:                     }
                   9099:                 }
                   9100:             }
                   9101:         }
                   9102:     }
                   9103:     return %access;
                   9104: }
                   9105: 
                   9106: sub modify_access_controls {
                   9107:     my ($file_name,$changes,$domain,$user)=@_;
                   9108:     my ($outcome,$deloutcome);
                   9109:     my %store_permissions;
                   9110:     my %new_values;
                   9111:     my %new_control;
                   9112:     my %translation;
                   9113:     my @deletions = ();
                   9114:     my $now = time;
                   9115:     if (exists($$changes{'activate'})) {
                   9116:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9117:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9118:             my $numnew = scalar(@newitems);
                   9119:             for (my $i=0; $i<$numnew; $i++) {
                   9120:                 my $newkey = $newitems[$i];
                   9121:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9122:                 if ($newkey =~ /^\d+:/) { 
                   9123:                     $newkey =~ s/^(\d+)/$newid/;
                   9124:                     $translation{$1} = $newid;
                   9125:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9126:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9127:                     $translation{$1} = $newid;
                   9128:                 }
1.749     raeburn  9129:                 $new_values{$file_name."\0".$newkey} = 
                   9130:                                           $$changes{'activate'}{$newitems[$i]};
                   9131:                 $new_control{$newkey} = $now;
                   9132:             }
                   9133:         }
                   9134:     }
                   9135:     my %todelete;
                   9136:     my %changed_items;
                   9137:     foreach my $action ('delete','update') {
                   9138:         if (exists($$changes{$action})) {
                   9139:             if (ref($$changes{$action}) eq 'HASH') {
                   9140:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9141:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9142:                     if ($action eq 'delete') { 
                   9143:                         $todelete{$itemnum} = 1;
                   9144:                     } else {
                   9145:                         $changed_items{$itemnum} = $key;
                   9146:                     }
                   9147:                 }
1.745     raeburn  9148:             }
                   9149:         }
1.749     raeburn  9150:     }
                   9151:     # get lock on access controls for file.
                   9152:     my $lockhash = {
                   9153:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9154:                                                        ':'.$env{'user.domain'},
                   9155:                    }; 
                   9156:     my $tries = 0;
                   9157:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9158:    
                   9159:     while (($gotlock ne 'ok') && $tries <3) {
                   9160:         $tries ++;
                   9161:         sleep 1;
                   9162:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9163:     }
                   9164:     if ($gotlock eq 'ok') {
                   9165:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9166:         my ($tmp)=keys(%curr_permissions);
                   9167:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9168:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9169:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9170:             if (ref($curr_controls) eq 'HASH') {
                   9171:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9172:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9173:                     if (defined($todelete{$itemnum})) {
                   9174:                         push(@deletions,$file_name."\0".$control_item);
                   9175:                     } else {
                   9176:                         if (defined($changed_items{$itemnum})) {
                   9177:                             $new_control{$changed_items{$itemnum}} = $now;
                   9178:                             push(@deletions,$file_name."\0".$control_item);
                   9179:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9180:                         } else {
                   9181:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9182:                         }
                   9183:                     }
1.745     raeburn  9184:                 }
                   9185:             }
                   9186:         }
1.970     raeburn  9187:         my ($group);
                   9188:         if (&is_course($domain,$user)) {
                   9189:             ($group,my $file) = split(/\//,$file_name,2);
                   9190:         }
1.749     raeburn  9191:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9192:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9193:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9194:         #  remove lock
                   9195:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9196:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9197:         my $sqlresult =
1.970     raeburn  9198:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9199:                                     $group);
1.749     raeburn  9200:     } else {
                   9201:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9202:     }
1.749     raeburn  9203:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9204: }
                   9205: 
1.827     raeburn  9206: sub make_public_indefinitely {
                   9207:     my ($requrl) = @_;
                   9208:     my $now = time;
                   9209:     my $action = 'activate';
                   9210:     my $aclnum = 0;
                   9211:     if (&is_portfolio_url($requrl)) {
                   9212:         my (undef,$udom,$unum,$file_name,$group) =
                   9213:             &parse_portfolio_url($requrl);
                   9214:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9215:         my %access_controls = &get_access_controls($current_perms,
                   9216:                                                    $group,$file_name);
                   9217:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9218:             my ($num,$scope,$end,$start) = 
                   9219:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9220:             if ($scope eq 'public') {
                   9221:                 if ($start <= $now && $end == 0) {
                   9222:                     $action = 'none';
                   9223:                 } else {
                   9224:                     $action = 'update';
                   9225:                     $aclnum = $num;
                   9226:                 }
                   9227:                 last;
                   9228:             }
                   9229:         }
                   9230:         if ($action eq 'none') {
                   9231:              return 'ok';
                   9232:         } else {
                   9233:             my %changes;
                   9234:             my $newend = 0;
                   9235:             my $newstart = $now;
                   9236:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9237:             $changes{$action}{$newkey} = {
                   9238:                 type => 'public',
                   9239:                 time => {
                   9240:                     start => $newstart,
                   9241:                     end   => $newend,
                   9242:                 },
                   9243:             };
                   9244:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9245:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9246:             return $outcome;
                   9247:         }
                   9248:     } else {
                   9249:         return 'invalid';
                   9250:     }
                   9251: }
                   9252: 
1.745     raeburn  9253: #------------------------------------------------------Get Marked as Read Only
                   9254: 
                   9255: sub get_marked_as_readonly {
                   9256:     my ($domain,$user,$what,$group) = @_;
                   9257:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9258:     my @readonly_files;
1.629     banghart 9259:     my $cmp1=$what;
                   9260:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9261:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9262:         if (defined($group)) {
                   9263:             if ($file_name !~ m-^\Q$group\E/-) {
                   9264:                 next;
                   9265:             }
                   9266:         }
1.561     banghart 9267:         if (ref($value) eq "ARRAY"){
                   9268:             foreach my $stored_what (@{$value}) {
1.629     banghart 9269:                 my $cmp2=$stored_what;
1.759     albertel 9270:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9271:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9272:                 }
1.629     banghart 9273:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9274:                     push(@readonly_files, $file_name);
1.745     raeburn  9275:                     last;
1.563     banghart 9276:                 } elsif (!defined($what)) {
                   9277:                     push(@readonly_files, $file_name);
1.745     raeburn  9278:                     last;
1.561     banghart 9279:                 }
                   9280:             }
1.745     raeburn  9281:         }
1.561     banghart 9282:     }
                   9283:     return @readonly_files;
                   9284: }
1.577     banghart 9285: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9286: 
1.577     banghart 9287: sub get_marked_as_readonly_hash {
1.745     raeburn  9288:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9289:     my %readonly_files;
1.745     raeburn  9290:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9291:         if (defined($group)) {
                   9292:             if ($file_name !~ m-^\Q$group\E/-) {
                   9293:                 next;
                   9294:             }
                   9295:         }
1.577     banghart 9296:         if (ref($value) eq "ARRAY"){
                   9297:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9298:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9299:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9300:                         if ($lock_descriptor eq 'graded') {
                   9301:                             $readonly_files{$file_name} = 'graded';
                   9302:                         } elsif ($lock_descriptor eq 'handback') {
                   9303:                             $readonly_files{$file_name} = 'handback';
                   9304:                         } else {
                   9305:                             if (!exists($readonly_files{$file_name})) {
                   9306:                                 $readonly_files{$file_name} = 'locked';
                   9307:                             }
                   9308:                         }
1.745     raeburn  9309:                     }
1.750     banghart 9310:                 } 
1.577     banghart 9311:             }
                   9312:         } 
                   9313:     }
                   9314:     return %readonly_files;
                   9315: }
1.559     banghart 9316: # ------------------------------------------------------------ Unmark as Read Only
                   9317: 
                   9318: sub unmark_as_readonly {
1.629     banghart 9319:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9320:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9321:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9322:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9323:     my $symb_crs = $what;
                   9324:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9325:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9326:     my ($tmp)=keys(%current_permissions);
                   9327:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9328:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9329:     foreach my $file (@readonly_files) {
1.759     albertel 9330: 	my $clean_file = &declutter_portfile($file);
                   9331: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9332: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9333:         my @new_locks;
                   9334:         my @del_keys;
                   9335:         if (ref($current_locks) eq "ARRAY"){
                   9336:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9337:                 my $compare=$locker;
1.749     raeburn  9338:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9339:                     $compare=join('',@{$locker});
1.746     raeburn  9340:                     if ($compare ne $symb_crs) {
                   9341:                         push(@new_locks, $locker);
                   9342:                     }
1.563     banghart 9343:                 }
                   9344:             }
1.650     albertel 9345:             if (scalar(@new_locks) > 0) {
1.563     banghart 9346:                 $current_permissions{$file} = \@new_locks;
                   9347:             } else {
                   9348:                 push(@del_keys, $file);
1.613     albertel 9349:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9350:                 delete($current_permissions{$file});
1.563     banghart 9351:             }
                   9352:         }
1.561     banghart 9353:     }
1.613     albertel 9354:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9355:     return;
                   9356: }
1.512     banghart 9357: 
1.17      www      9358: # ------------------------------------------------------------ Directory lister
                   9359: 
                   9360: sub dirlist {
1.955     raeburn  9361:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9362:     $uri=~s/^\///;
                   9363:     $uri=~s/\/$//;
1.253     stredwic 9364:     my ($udom, $uname);
1.955     raeburn  9365:     if ($getuserdir) {
1.253     stredwic 9366:         $udom = $userdomain;
                   9367:         $uname = $username;
1.955     raeburn  9368:     } else {
                   9369:         (undef,$udom,$uname)=split(/\//,$uri);
                   9370:         if(defined($userdomain)) {
                   9371:             $udom = $userdomain;
                   9372:         }
                   9373:         if(defined($username)) {
                   9374:             $uname = $username;
                   9375:         }
1.253     stredwic 9376:     }
1.955     raeburn  9377:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9378: 
1.955     raeburn  9379:     $dirRoot = $perlvar{'lonDocRoot'};
                   9380:     if (defined($getpropath)) {
                   9381:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9382:         $dirRoot =~ s/\/$//;
1.955     raeburn  9383:     } elsif (defined($getuserdir)) {
                   9384:         my $subdir=$uname.'__';
                   9385:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9386:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9387:                    ."/$udom/$subdir/$uname";
                   9388:     } elsif (defined($alternateRoot)) {
                   9389:         $dirRoot = $alternateRoot;
1.751     banghart 9390:     }
1.253     stredwic 9391: 
                   9392:     if($udom) {
                   9393:         if($uname) {
1.1135    raeburn  9394:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9395:             if ($uhome eq 'no_host') {
                   9396:                 return ([],'no_host');
                   9397:             }
1.955     raeburn  9398:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9399:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9400:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9401:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9402:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9403:             } else {
                   9404:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9405:             }
1.605     matthew  9406:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9407:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9408:                 @listing_results = split(/:/,$listing);
                   9409:             } else {
                   9410:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9411:             }
1.1135    raeburn  9412:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9413:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9414:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9415:                 return ([],$listing);
                   9416:             } else {
                   9417:                 return (\@listing_results);
1.1135    raeburn  9418:             }
1.955     raeburn  9419:         } elsif(!$alternateRoot) {
1.1136    raeburn  9420:             my (%allusers,%listerror);
1.841     albertel 9421: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9422:  	    foreach my $tryserver (keys(%servers)) {
                   9423:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9424:                                   &escape($udom),$tryserver);
                   9425:                 if ($listing eq 'unknown_cmd') {
                   9426: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9427: 				      $udom, $tryserver);
                   9428:                 } else {
                   9429:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9430:                 }
1.841     albertel 9431: 		if ($listing eq 'unknown_cmd') {
                   9432: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9433: 				      $udom, $tryserver);
                   9434: 		    @listing_results = split(/:/,$listing);
                   9435: 		} else {
                   9436: 		    @listing_results =
                   9437: 			map { &unescape($_); } split(/:/,$listing);
                   9438: 		}
1.1136    raeburn  9439:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9440:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9441:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9442:                     $listerror{$tryserver} = $listing;
                   9443:                 } else {
1.841     albertel 9444: 		    foreach my $line (@listing_results) {
                   9445: 			my ($entry) = split(/&/,$line,2);
                   9446: 			$allusers{$entry} = 1;
                   9447: 		    }
                   9448: 		}
1.253     stredwic 9449:             }
1.1136    raeburn  9450:             my @alluserslist=();
1.800     albertel 9451:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9452:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9453:             }
1.1136    raeburn  9454:             return (\@alluserslist);
1.253     stredwic 9455:         } else {
1.1136    raeburn  9456:             return ([],'missing username');
1.253     stredwic 9457:         }
1.955     raeburn  9458:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9459:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9460:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9461:         return (\@all_domains);
1.955     raeburn  9462:     } else {
1.1136    raeburn  9463:         return ([],'missing domain');
1.275     stredwic 9464:     }
                   9465: }
                   9466: 
                   9467: # --------------------------------------------- GetFileTimestamp
                   9468: # This function utilizes dirlist and returns the date stamp for
                   9469: # when it was last modified.  It will also return an error of -1
                   9470: # if an error occurs
                   9471: 
                   9472: sub GetFileTimestamp {
1.955     raeburn  9473:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9474:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9475:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9476:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9477:                                     undef,$getuserdir);
                   9478:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9479:         return -1;
                   9480:     }
                   9481:     if (ref($fileref) eq 'ARRAY') {
                   9482:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9483:         # @stats contains first the filename, then the stat output
                   9484:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9485:     } else {
                   9486:         return -1;
1.253     stredwic 9487:     }
1.26      www      9488: }
                   9489: 
1.712     albertel 9490: sub stat_file {
                   9491:     my ($uri) = @_;
1.787     albertel 9492:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9493: 
1.955     raeburn  9494:     my ($udom,$uname,$file);
1.712     albertel 9495:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9496: 	($udom,$uname,$file) =
1.811     albertel 9497: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9498: 	$file = 'userfiles/'.$file;
                   9499:     }
                   9500:     if ($uri =~ m-^/res/-) {
                   9501: 	($udom,$uname) = 
1.807     albertel 9502: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9503: 	$file = $uri;
                   9504:     }
                   9505: 
                   9506:     if (!$udom || !$uname || !$file) {
                   9507: 	# unable to handle the uri
                   9508: 	return ();
                   9509:     }
1.956     raeburn  9510:     my $getpropath;
                   9511:     if ($file =~ /^userfiles\//) {
                   9512:         $getpropath = 1;
                   9513:     }
1.1136    raeburn  9514:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9515:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9516:         return ();
                   9517:     } else {
                   9518:         if (ref($listref) eq 'ARRAY') {
                   9519:             my @stats = split('&',$listref->[0]);
                   9520: 	    shift(@stats); #filename is first
                   9521: 	    return @stats;
                   9522:         }
1.712     albertel 9523:     }
                   9524:     return ();
                   9525: }
                   9526: 
1.26      www      9527: # -------------------------------------------------------- Value of a Condition
                   9528: 
1.713     albertel 9529: # gets the value of a specific preevaluated condition
                   9530: #    stored in the string  $env{user.state.<cid>}
                   9531: # or looks up a condition reference in the bighash and if if hasn't
                   9532: # already been evaluated recurses into docondval to get the value of
                   9533: # the condition, then memoizing it to 
                   9534: #   $env{user.state.<cid>.<condition>}
1.40      www      9535: sub directcondval {
                   9536:     my $number=shift;
1.620     albertel 9537:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9538: 	&Apache::lonuserstate::evalstate();
                   9539:     }
1.713     albertel 9540:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9541: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9542:     } elsif ($number =~ /^_/) {
                   9543: 	my $sub_condition;
                   9544: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9545: 		&GDBM_READER(),0640)) {
                   9546: 	    $sub_condition=$bighash{'conditions'.$number};
                   9547: 	    untie(%bighash);
                   9548: 	}
                   9549: 	my $value = &docondval($sub_condition);
1.949     raeburn  9550: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9551: 	return $value;
                   9552:     }
1.620     albertel 9553:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9554:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9555:     } else {
                   9556:        return 2;
                   9557:     }
                   9558: }
                   9559: 
1.713     albertel 9560: # get the collection of conditions for this resource
1.26      www      9561: sub condval {
                   9562:     my $condidx=shift;
1.54      www      9563:     my $allpathcond='';
1.713     albertel 9564:     foreach my $cond (split(/\|/,$condidx)) {
                   9565: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9566: 	    $allpathcond.=
                   9567: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9568: 	}
1.191     harris41 9569:     }
1.54      www      9570:     $allpathcond=~s/\|$//;
1.713     albertel 9571:     return &docondval($allpathcond);
                   9572: }
                   9573: 
                   9574: #evaluates an expression of conditions
                   9575: sub docondval {
                   9576:     my ($allpathcond) = @_;
                   9577:     my $result=0;
                   9578:     if ($env{'request.course.id'}
                   9579: 	&& defined($allpathcond)) {
                   9580: 	my $operand='|';
                   9581: 	my @stack;
                   9582: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9583: 	    if ($chunk eq '(') {
                   9584: 		push @stack,($operand,$result);
                   9585: 	    } elsif ($chunk eq ')') {
                   9586: 		my $before=pop @stack;
                   9587: 		if (pop @stack eq '&') {
                   9588: 		    $result=$result>$before?$before:$result;
                   9589: 		} else {
                   9590: 		    $result=$result>$before?$result:$before;
                   9591: 		}
                   9592: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9593: 		$operand=$chunk;
                   9594: 	    } else {
                   9595: 		my $new=directcondval($chunk);
                   9596: 		if ($operand eq '&') {
                   9597: 		    $result=$result>$new?$new:$result;
                   9598: 		} else {
                   9599: 		    $result=$result>$new?$result:$new;
                   9600: 		}
                   9601: 	    }
                   9602: 	}
1.26      www      9603:     }
                   9604:     return $result;
1.421     albertel 9605: }
                   9606: 
                   9607: # ---------------------------------------------------- Devalidate courseresdata
                   9608: 
                   9609: sub devalidatecourseresdata {
                   9610:     my ($coursenum,$coursedomain)=@_;
                   9611:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9612:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9613: }
                   9614: 
1.763     www      9615: 
1.200     www      9616: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9617: #
                   9618: #  Parameters:
                   9619: #      $coursenum    - Number of the course.
                   9620: #      $coursedomain - Domain at which the course was created.
                   9621: #  Returns:
                   9622: #     A hash of the course parameters along (I think) with timestamps
                   9623: #     and version info.
1.877     foxr     9624: 
1.624     albertel 9625: sub get_courseresdata {
                   9626:     my ($coursenum,$coursedomain)=@_;
1.200     www      9627:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9628:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9629:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9630:     my %dumpreply;
1.417     albertel 9631:     unless (defined($cached)) {
1.624     albertel 9632: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9633: 	$result=\%dumpreply;
1.251     albertel 9634: 	my ($tmp) = keys(%dumpreply);
                   9635: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9636: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9637: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9638: 	    return $tmp;
1.416     albertel 9639: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9640: 	    $result=undef;
1.599     albertel 9641: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9642: 	}
                   9643:     }
1.624     albertel 9644:     return $result;
                   9645: }
                   9646: 
1.633     albertel 9647: sub devalidateuserresdata {
                   9648:     my ($uname,$udom)=@_;
                   9649:     my $hashid="$udom:$uname";
                   9650:     &devalidate_cache_new('userres',$hashid);
                   9651: }
                   9652: 
1.624     albertel 9653: sub get_userresdata {
                   9654:     my ($uname,$udom)=@_;
                   9655:     #most student don\'t have any data set, check if there is some data
                   9656:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9657: 
                   9658:     my $hashid="$udom:$uname";
                   9659:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9660:     if (!defined($cached)) {
                   9661: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9662: 	$result=\%resourcedata;
                   9663: 	&do_cache_new('userres',$hashid,$result,600);
                   9664:     }
                   9665:     my ($tmp)=keys(%$result);
                   9666:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9667: 	return $result;
                   9668:     }
                   9669:     #error 2 occurs when the .db doesn't exist
                   9670:     if ($tmp!~/error: 2 /) {
1.672     albertel 9671: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9672: 		 " Trying to get resource data for ".
                   9673: 		 $uname." at ".$udom.": ".
                   9674: 		 $tmp."</font>");
                   9675:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9676: 	#&EXT_cache_set($udom,$uname);
                   9677: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9678: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9679:     }
                   9680:     return $tmp;
                   9681: }
1.879     foxr     9682: #----------------------------------------------- resdata - return resource data
                   9683: #  Purpose:
                   9684: #    Return resource data for either users or for a course.
                   9685: #  Parameters:
                   9686: #     $name      - Course/user name.
                   9687: #     $domain    - Name of the domain the user/course is registered on.
                   9688: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9689: #     @which     - Array of names of resources desired.
                   9690: #  Returns:
                   9691: #     The value of the first reasource in @which that is found in the
                   9692: #     resource hash.
                   9693: #  Exceptional Conditions:
                   9694: #     If the $type passed in is not valid (not the string 'course' or 
                   9695: #     'user', an undefined  reference is returned.
                   9696: #     If none of the resources are found, an undef is returned
1.624     albertel 9697: sub resdata {
                   9698:     my ($name,$domain,$type,@which)=@_;
                   9699:     my $result;
                   9700:     if ($type eq 'course') {
                   9701: 	$result=&get_courseresdata($name,$domain);
                   9702:     } elsif ($type eq 'user') {
                   9703: 	$result=&get_userresdata($name,$domain);
                   9704:     }
                   9705:     if (!ref($result)) { return $result; }    
1.251     albertel 9706:     foreach my $item (@which) {
1.927     albertel 9707: 	if (defined($result->{$item->[0]})) {
                   9708: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9709: 	}
1.250     albertel 9710:     }
1.291     albertel 9711:     return undef;
1.200     www      9712: }
                   9713: 
1.1172.2.31  raeburn  9714: sub get_numsuppfiles {
                   9715:     my ($cnum,$cdom,$ignorecache)=@_;
                   9716:     my $hashid=$cnum.':'.$cdom;
                   9717:     my ($suppcount,$cached);
                   9718:     unless ($ignorecache) {
                   9719:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9720:     }
                   9721:     unless (defined($cached)) {
                   9722:         my $chome=&homeserver($cnum,$cdom);
                   9723:         unless ($chome eq 'no_host') {
                   9724:             ($suppcount,my $errors) = (0,0);
                   9725:             my $suppmap = 'supplemental.sequence';
                   9726:             ($suppcount,$errors) =
                   9727:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9728:         }
                   9729:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9730:     }
                   9731:     return $suppcount;
                   9732: }
                   9733: 
1.379     matthew  9734: #
                   9735: # EXT resource caching routines
                   9736: #
                   9737: 
                   9738: sub clear_EXT_cache_status {
1.383     albertel 9739:     &delenv('cache.EXT.');
1.379     matthew  9740: }
                   9741: 
                   9742: sub EXT_cache_status {
                   9743:     my ($target_domain,$target_user) = @_;
1.383     albertel 9744:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9745:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9746:         # We know already the user has no data
                   9747:         return 1;
                   9748:     } else {
                   9749:         return 0;
                   9750:     }
                   9751: }
                   9752: 
                   9753: sub EXT_cache_set {
                   9754:     my ($target_domain,$target_user) = @_;
1.383     albertel 9755:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9756:     #&appenv({$cachename => time});
1.379     matthew  9757: }
                   9758: 
1.28      www      9759: # --------------------------------------------------------- Value of a Variable
1.58      www      9760: sub EXT {
1.715     albertel 9761: 
1.1172.2.28  raeburn  9762:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9763:     unless ($varname) { return ''; }
1.218     albertel 9764:     #get real user name/domain, courseid and symb
                   9765:     my $courseid;
1.359     albertel 9766:     my $publicuser;
1.427     www      9767:     if ($symbparm) {
                   9768: 	$symbparm=&get_symb_from_alias($symbparm);
                   9769:     }
1.218     albertel 9770:     if (!($uname && $udom)) {
1.790     albertel 9771:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9772:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9773:     } else {
1.620     albertel 9774: 	$courseid=$env{'request.course.id'};
1.218     albertel 9775:     }
1.48      www      9776:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9777:     my $rest;
1.320     albertel 9778:     if (defined($therest[0])) {
1.48      www      9779:        $rest=join('.',@therest);
                   9780:     } else {
                   9781:        $rest='';
                   9782:     }
1.320     albertel 9783: 
1.57      www      9784:     my $qualifierrest=$qualifier;
                   9785:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9786:     my $spacequalifierrest=$space;
                   9787:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9788:     if ($realm eq 'user') {
1.48      www      9789: # --------------------------------------------------------------- user.resource
                   9790: 	if ($space eq 'resource') {
1.651     albertel 9791: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9792: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9793: 		 &&
1.744     albertel 9794: 		 ($symbparm eq &symbread()) ) {	
                   9795: 		# if we are in the middle of processing the resource the
                   9796: 		# get the value we are planning on committing
                   9797:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9798:                     return $Apache::lonhomework::results{$qualifierrest};
                   9799:                 } else {
                   9800:                     return $Apache::lonhomework::history{$qualifierrest};
                   9801:                 }
1.335     albertel 9802: 	    } else {
1.359     albertel 9803: 		my %restored;
1.620     albertel 9804: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9805: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9806: 		} else {
                   9807: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9808: 		}
1.335     albertel 9809: 		return $restored{$qualifierrest};
                   9810: 	    }
1.48      www      9811: # ----------------------------------------------------------------- user.access
                   9812:         } elsif ($space eq 'access') {
1.218     albertel 9813: 	    # FIXME - not supporting calls for a specific user
1.48      www      9814:             return &allowed($qualifier,$rest);
                   9815: # ------------------------------------------ user.preferences, user.environment
                   9816:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9817: 	    if (($uname eq $env{'user.name'}) &&
                   9818: 		($udom eq $env{'user.domain'})) {
                   9819: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9820: 	    } else {
1.359     albertel 9821: 		my %returnhash;
                   9822: 		if (!$publicuser) {
                   9823: 		    %returnhash=&userenvironment($udom,$uname,
                   9824: 						 $qualifierrest);
                   9825: 		}
1.218     albertel 9826: 		return $returnhash{$qualifierrest};
                   9827: 	    }
1.48      www      9828: # ----------------------------------------------------------------- user.course
                   9829:         } elsif ($space eq 'course') {
1.218     albertel 9830: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9831:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9832: # ------------------------------------------------------------------- user.role
                   9833:         } elsif ($space eq 'role') {
1.218     albertel 9834: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9835:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9836:             if ($qualifier eq 'value') {
                   9837: 		return $role;
                   9838:             } elsif ($qualifier eq 'extent') {
                   9839:                 return $where;
                   9840:             }
                   9841: # ----------------------------------------------------------------- user.domain
                   9842:         } elsif ($space eq 'domain') {
1.218     albertel 9843:             return $udom;
1.48      www      9844: # ------------------------------------------------------------------- user.name
                   9845:         } elsif ($space eq 'name') {
1.218     albertel 9846:             return $uname;
1.48      www      9847: # ---------------------------------------------------- Any other user namespace
1.29      www      9848:         } else {
1.359     albertel 9849: 	    my %reply;
                   9850: 	    if (!$publicuser) {
                   9851: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9852: 	    }
                   9853: 	    return $reply{$qualifierrest};
1.48      www      9854:         }
1.236     www      9855:     } elsif ($realm eq 'query') {
                   9856: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9857:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9858: 						[$spacequalifierrest]);
1.620     albertel 9859: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9860:    } elsif ($realm eq 'request') {
1.48      www      9861: # ------------------------------------------------------------- request.browser
                   9862:         if ($space eq 'browser') {
1.1145    bisitz   9863:             return $env{'browser.'.$qualifier};
1.57      www      9864: # ------------------------------------------------------------ request.filename
                   9865:         } else {
1.620     albertel 9866:             return $env{'request.'.$spacequalifierrest};
1.29      www      9867:         }
1.28      www      9868:     } elsif ($realm eq 'course') {
1.48      www      9869: # ---------------------------------------------------------- course.description
1.620     albertel 9870:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9871:     } elsif ($realm eq 'resource') {
1.165     www      9872: 
1.620     albertel 9873: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9874: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9875: 	}
1.693     albertel 9876: 
1.1172.2.30  raeburn  9877:         if ($qualifier eq '') {
                   9878: 	    if ($space eq 'title') {
                   9879: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9880: 	        return &gettitle($symbparm);
                   9881: 	    }
1.693     albertel 9882: 	
1.1172.2.30  raeburn  9883: 	    if ($space eq 'map') {
                   9884: 	        my ($map) = &decode_symb($symbparm);
                   9885: 	        return &symbread($map);
                   9886: 	    }
                   9887:             if ($space eq 'maptitle') {
                   9888:                 my ($map) = &decode_symb($symbparm);
                   9889:                 return &gettitle($map);
                   9890:             }
                   9891: 	    if ($space eq 'filename') {
                   9892: 	        if ($symbparm) {
                   9893: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9894: 	        }
                   9895: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9896: 	    }
1.1172.2.30  raeburn  9897: 
                   9898:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9899:                 if ($space eq 'visibleparts') {
                   9900:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9901:                     my $item;
                   9902:                     if (ref($navmap)) {
                   9903:                         my $res = $navmap->getBySymb($symbparm);
                   9904:                         my $parts = $res->parts();
                   9905:                         if (ref($parts) eq 'ARRAY') {
                   9906:                             $item = join(',',@{$parts});
                   9907:                         }
                   9908:                         undef($navmap);
                   9909:                     }
                   9910:                     return $item;
                   9911:                 }
                   9912:             }
                   9913:         }
1.693     albertel 9914: 
                   9915: 	my ($section, $group, @groups);
1.593     albertel 9916: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  9917:         if (($courseid eq '') && ($cid)) {
                   9918:             $courseid = $cid;
                   9919:         }
                   9920: 	if (($symbparm && $courseid) && 
                   9921: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      9922: 
1.218     albertel 9923: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9924: 
1.60      www      9925: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9926: 	    my $symbp=$symbparm;
1.735     albertel 9927: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9928: 
                   9929: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9930: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9931: 
1.620     albertel 9932: 	    if (($env{'user.name'} eq $uname) &&
                   9933: 		($env{'user.domain'} eq $udom)) {
                   9934: 		$section=$env{'request.course.sec'};
1.733     raeburn  9935:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9936:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9937: 	    } else {
1.539     albertel 9938: 		if (! defined($usection)) {
1.551     albertel 9939: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9940: 		} else {
                   9941: 		    $section = $usection;
                   9942: 		}
1.733     raeburn  9943:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9944: 	    }
                   9945: 
                   9946: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9947: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9948: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9949: 
1.593     albertel 9950: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9951: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9952: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9953: 
1.60      www      9954: # ----------------------------------------------------------- first, check user
1.624     albertel 9955: 
                   9956: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9957: 				       ([$courselevelr,'resource'],
                   9958: 					[$courselevelm,'map'     ],
                   9959: 					[$courselevel, 'course'  ]));
1.931     albertel 9960: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9961: 
1.594     albertel 9962: # ------------------------------------------------ second, check some of course
1.684     raeburn  9963:             my $coursereply;
1.691     raeburn  9964:             if (@groups > 0) {
                   9965:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9966:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9967:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9968:             }
1.96      www      9969: 
1.684     raeburn  9970: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9971: 				  $env{'course.'.$courseid.'.domain'},
                   9972: 				  'course',
                   9973: 				  ([$seclevelr,   'resource'],
                   9974: 				   [$seclevelm,   'map'     ],
                   9975: 				   [$seclevel,    'course'  ],
                   9976: 				   [$courselevelr,'resource']));
                   9977: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9978: 
1.60      www      9979: # ------------------------------------------------------ third, check map parms
1.218     albertel 9980: 	    my %parmhash=();
                   9981: 	    my $thisparm='';
                   9982: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9983: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9984: 		    &GDBM_READER(),0640)) {
1.218     albertel 9985: 		$thisparm=$parmhash{$symbparm};
                   9986: 		untie(%parmhash);
                   9987: 	    }
1.927     albertel 9988: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9989: 	}
1.594     albertel 9990: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9991: 
1.218     albertel 9992: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9993: 	my $filename;
                   9994: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9995: 	if ($symbparm) {
1.409     www      9996: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9997: 	} else {
1.620     albertel 9998: 	    $filename=$env{'request.filename'};
1.282     albertel 9999: 	}
                   10000: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10001: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10002: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10003: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10004: 
1.927     albertel 10005: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10006: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10007: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10008: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10009: 				     $env{'course.'.$courseid.'.domain'},
                   10010: 				     'course',
1.927     albertel 10011: 				     ([$courselevelm,'map'   ],
                   10012: 				      [$courselevel, 'course']));
                   10013: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10014: 	}
1.145     www      10015: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10016: 	unless ($space eq '0') {
1.336     albertel 10017: 	    my @parts=split(/_/,$space);
                   10018: 	    my $id=pop(@parts);
                   10019: 	    my $part=join('_',@parts);
                   10020: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10021: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10022: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10023: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10024: 	}
1.395     albertel 10025: 	if ($recurse) { return undef; }
                   10026: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10027: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10028: # ---------------------------------------------------- Any other user namespace
                   10029:     } elsif ($realm eq 'environment') {
                   10030: # ----------------------------------------------------------------- environment
1.620     albertel 10031: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10032: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10033: 	} else {
1.770     albertel 10034: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10035: 		return '';
                   10036: 	    }
1.219     albertel 10037: 	    my %returnhash=&userenvironment($udom,$uname,
                   10038: 					    $spacequalifierrest);
                   10039: 	    return $returnhash{$spacequalifierrest};
                   10040: 	}
1.28      www      10041:     } elsif ($realm eq 'system') {
1.48      www      10042: # ----------------------------------------------------------------- system.time
                   10043: 	if ($space eq 'time') {
                   10044: 	    return time;
                   10045:         }
1.696     albertel 10046:     } elsif ($realm eq 'server') {
                   10047: # ----------------------------------------------------------------- system.time
                   10048: 	if ($space eq 'name') {
                   10049: 	    return $ENV{'SERVER_NAME'};
                   10050:         }
1.28      www      10051:     }
1.48      www      10052:     return '';
1.61      www      10053: }
                   10054: 
1.927     albertel 10055: sub get_reply {
                   10056:     my ($reply_value) = @_;
1.940     raeburn  10057:     if (ref($reply_value) eq 'ARRAY') {
                   10058:         if (wantarray) {
                   10059: 	    return @$reply_value;
                   10060:         }
                   10061:         return $reply_value->[0];
                   10062:     } else {
                   10063:         return $reply_value;
1.927     albertel 10064:     }
                   10065: }
                   10066: 
1.691     raeburn  10067: sub check_group_parms {
                   10068:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10069:     my @groupitems = ();
                   10070:     my $resultitem;
1.927     albertel 10071:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10072:     foreach my $group (@{$groups}) {
                   10073:         foreach my $level (@levels) {
1.927     albertel 10074:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10075:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10076:         }
                   10077:     }
                   10078:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10079:                             $env{'course.'.$courseid.'.domain'},
                   10080:                                      'course',@groupitems);
                   10081:     return $coursereply;
                   10082: }
                   10083: 
                   10084: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10085:     my ($courseid,@groups) = @_;
                   10086:     @groups = sort(@groups);
1.691     raeburn  10087:     return @groups;
                   10088: }
                   10089: 
1.395     albertel 10090: sub packages_tab_default {
                   10091:     my ($uri,$varname)=@_;
                   10092:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10093: 
                   10094:     my (@extension,@specifics,$do_default);
                   10095:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10096: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10097: 	if ($pack_type eq 'default') {
                   10098: 	    $do_default=1;
                   10099: 	} elsif ($pack_type eq 'extension') {
                   10100: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10101: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10102: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10103: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10104: 	}
                   10105:     }
                   10106:     # first look for a package that matches the requested part id
                   10107:     foreach my $package (@specifics) {
                   10108: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10109: 	next if ($pack_part ne $part);
                   10110: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10111: 	    return $packagetab{"$pack_type&$name&default"};
                   10112: 	}
                   10113:     }
                   10114:     # look for any possible matching non extension_ package
                   10115:     foreach my $package (@specifics) {
                   10116: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10117: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10118: 	    return $packagetab{"$pack_type&$name&default"};
                   10119: 	}
1.585     albertel 10120: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10121: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10122: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10123: 	}
                   10124:     }
1.738     albertel 10125:     # look for any posible extension_ match
                   10126:     foreach my $package (@extension) {
                   10127: 	my ($package,$pack_type)=@{$package};
                   10128: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10129: 	    return $packagetab{"$pack_type&$name&default"};
                   10130: 	}
                   10131: 	if (defined($packagetab{$package."&$name&default"})) {
                   10132: 	    return $packagetab{$package."&$name&default"};
                   10133: 	}
                   10134:     }
                   10135:     # look for a global default setting
                   10136:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10137: 	return $packagetab{"default&$name&default"};
                   10138:     }
1.395     albertel 10139:     return undef;
                   10140: }
                   10141: 
1.334     albertel 10142: sub add_prefix_and_part {
                   10143:     my ($prefix,$part)=@_;
                   10144:     my $keyroot;
                   10145:     if (defined($prefix) && $prefix !~ /^__/) {
                   10146: 	# prefix that has a part already
                   10147: 	$keyroot=$prefix;
                   10148:     } elsif (defined($prefix)) {
                   10149: 	# prefix that is missing a part
                   10150: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10151:     } else {
                   10152: 	# no prefix at all
                   10153: 	if (defined($part)) { $keyroot='_'.$part; }
                   10154:     }
                   10155:     return $keyroot;
                   10156: }
                   10157: 
1.71      www      10158: # ---------------------------------------------------------------- Get metadata
                   10159: 
1.599     albertel 10160: my %metaentry;
1.1070    www      10161: my %importedpartids;
1.71      www      10162: sub metadata {
1.176     www      10163:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10164:     $uri=&declutter($uri);
1.288     albertel 10165:     # if it is a non metadata possible uri return quickly
1.529     albertel 10166:     if (($uri eq '') || 
                   10167: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10168: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10169:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10170: 	return undef;
                   10171:     }
1.1140    www      10172:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10173: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10174: 	return undef;
1.288     albertel 10175:     }
1.73      www      10176:     my $filename=$uri;
                   10177:     $uri=~s/\.meta$//;
1.172     www      10178: #
                   10179: # Is the metadata already cached?
1.177     www      10180: # Look at timestamp of caching
1.172     www      10181: # Everything is cached by the main uri, libraries are never directly cached
                   10182: #
1.428     albertel 10183:     if (!defined($liburi)) {
1.599     albertel 10184: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10185: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10186:     }
                   10187:     {
1.1069    www      10188: # Imported parts would go here
1.1070    www      10189:         my %importedids=();
                   10190:         my @origfileimportpartids=();
1.1069    www      10191:         my $importedparts=0;
1.172     www      10192: #
                   10193: # Is this a recursive call for a library?
                   10194: #
1.599     albertel 10195: #	if (! exists($metacache{$uri})) {
                   10196: #	    $metacache{$uri}={};
                   10197: #	}
1.924     albertel 10198: 	my $cachetime = 60*60;
1.171     www      10199:         if ($liburi) {
                   10200: 	    $liburi=&declutter($liburi);
                   10201:             $filename=$liburi;
1.401     bowersj2 10202:         } else {
1.599     albertel 10203: 	    &devalidate_cache_new('meta',$uri);
                   10204: 	    undef(%metaentry);
1.401     bowersj2 10205: 	}
1.140     www      10206:         my %metathesekeys=();
1.73      www      10207:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10208: 	my $metastring;
1.1140    www      10209: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10210: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10211: 	    $metastring = 
1.929     albertel 10212: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10213: 					  ('grade_target' => 'meta'));
                   10214: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10215: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10216:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10217: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10218: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10219: 	    $metastring=&getfile($file);
1.489     albertel 10220: 	}
1.208     albertel 10221:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10222:         my $token;
1.140     www      10223:         undef %metathesekeys;
1.71      www      10224:         while ($token=$parser->get_token) {
1.339     albertel 10225: 	    if ($token->[0] eq 'S') {
                   10226: 		if (defined($token->[2]->{'package'})) {
1.172     www      10227: #
                   10228: # This is a package - get package info
                   10229: #
1.339     albertel 10230: 		    my $package=$token->[2]->{'package'};
                   10231: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10232: 		    if (defined($token->[2]->{'id'})) { 
                   10233: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10234: 		    }
1.599     albertel 10235: 		    if ($metaentry{':packages'}) {
                   10236: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10237: 		    } else {
1.599     albertel 10238: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10239: 		    }
1.736     albertel 10240: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10241: 			my $part=$keyroot;
                   10242: 			$part=~s/^\_//;
1.736     albertel 10243: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10244: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10245: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10246: 			    # ignore package.tab specified default values
                   10247:                             # here &package_tab_default() will fetch those
                   10248: 			    if ($subp eq 'default') { next; }
1.736     albertel 10249: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10250: 			    my $unikey;
                   10251: 			    if ($pack =~ /_0$/) {
                   10252: 				$unikey='parameter_0_'.$name;
                   10253: 				$part=0;
                   10254: 			    } else {
                   10255: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10256: 			    }
1.339     albertel 10257: 			    if ($subp eq 'display') {
                   10258: 				$value.=' [Part: '.$part.']';
                   10259: 			    }
1.599     albertel 10260: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10261: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10262: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10263: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10264: 			    }
1.599     albertel 10265: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10266: 				$metaentry{':'.$unikey}=
                   10267: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10268: 			    }
1.339     albertel 10269: 			}
                   10270: 		    }
                   10271: 		} else {
1.172     www      10272: #
                   10273: # This is not a package - some other kind of start tag
1.339     albertel 10274: #
                   10275: 		    my $entry=$token->[1];
1.1068    www      10276: 		    my $unikey='';
1.175     www      10277: 
1.339     albertel 10278: 		    if ($entry eq 'import') {
1.175     www      10279: #
                   10280: # Importing a library here
1.339     albertel 10281: #
1.1067    www      10282:                         my $location=$parser->get_text('/import');
                   10283:                         my $dir=$filename;
                   10284:                         $dir=~s|[^/]*$||;
                   10285:                         $location=&filelocation($dir,$location);
1.1069    www      10286:                        
1.1068    www      10287:                         my $importmode=$token->[2]->{'importmode'};
                   10288:                         if ($importmode eq 'problem') {
1.1069    www      10289: # Import as problem/response
1.1068    www      10290:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10291:                         } elsif ($importmode eq 'part') {
                   10292: # Import as part(s)
1.1069    www      10293:                            $importedparts=1;
                   10294: # We need to get the original file and the imported file to get the part order correct
                   10295: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10296: # Load and inspect original file
1.1070    www      10297:                            if ($#origfileimportpartids<0) {
                   10298:                               undef(%importedpartids);
                   10299:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10300:                               my $origfile=&getfile($origfilelocation);
                   10301:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10302:                            }
                   10303: 
1.1069    www      10304: # Load and inspect imported file
                   10305:                            my $impfile=&getfile($location);
                   10306:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10307:                            if ($#impfilepartids>=0) {
                   10308: # This problem had parts
1.1070    www      10309:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10310:                            } else {
                   10311: # Importing by turning a single problem into a problem part
                   10312: # It gets the import-tags ID as part-ID
                   10313:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10314:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10315:                            }
1.1068    www      10316:                         } else {
                   10317: # Normal import
                   10318:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10319:                            if (defined($token->[2]->{'id'})) {
                   10320:                               $unikey.='_'.$token->[2]->{'id'};
                   10321:                            }
1.1067    www      10322:                         }
                   10323: 
1.339     albertel 10324: 			if ($depthcount<20) {
1.736     albertel 10325: 			    my $metadata = 
                   10326: 				&metadata($uri,'keys', $location,$unikey,
                   10327: 					  $depthcount+1);
                   10328: 			    foreach my $meta (split(',',$metadata)) {
                   10329: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10330: 				$metathesekeys{$meta}=1;
1.339     albertel 10331: 			    }
1.1068    www      10332: 			
                   10333:                         }
1.1067    www      10334: 		    } else {
                   10335: #
                   10336: # Not importing, some other kind of non-package, non-library start tag
                   10337: # 
                   10338:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10339:                         if (defined($token->[2]->{'id'})) {
                   10340:                             $unikey.='_'.$token->[2]->{'id'};
                   10341:                         }
1.339     albertel 10342: 			if (defined($token->[2]->{'name'})) { 
                   10343: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10344: 			}
                   10345: 			$metathesekeys{$unikey}=1;
1.736     albertel 10346: 			foreach my $param (@{$token->[3]}) {
                   10347: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10348: 				$token->[2]->{$param};
1.339     albertel 10349: 			}
                   10350: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10351: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10352: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10353: 		 # only ws inside the tag, and not in default, so use default
                   10354: 		 # as value
1.599     albertel 10355: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10356: 			} elsif ( $internaltext =~ /\S/ ) {
                   10357: 		  # something interesting inside the tag
                   10358: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10359: 			} else {
1.908     albertel 10360: 		  # no interesting values, don't set a default
1.339     albertel 10361: 			}
1.172     www      10362: # end of not-a-package not-a-library import
1.339     albertel 10363: 		    }
1.172     www      10364: # end of not-a-package start tag
1.339     albertel 10365: 		}
1.172     www      10366: # the next is the end of "start tag"
1.339     albertel 10367: 	    }
                   10368: 	}
1.483     albertel 10369: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10370: 	$extension = lc($extension);
                   10371: 	if ($extension eq 'htm') { $extension='html'; }
                   10372: 
1.737     albertel 10373: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10374: 	    #no specific packages #how's our extension
                   10375: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10376: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10377: 					 \%metathesekeys);
                   10378: 	}
1.883     albertel 10379: 
                   10380: 	if (!exists($metaentry{':packages'})
                   10381: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10382: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10383: 		#no specific packages well let's get default then
                   10384: 		if ($key!~/^default&/) { next; }
1.488     albertel 10385: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10386: 					     \%metathesekeys);
                   10387: 	    }
                   10388: 	}
1.338     www      10389: # are there custom rights to evaluate
1.599     albertel 10390: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10391: 
1.338     www      10392:     #
                   10393:     # Importing a rights file here
1.339     albertel 10394:     #
                   10395: 	    unless ($depthcount) {
1.599     albertel 10396: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10397: 		my $dir=$filename;
                   10398: 		$dir=~s|[^/]*$||;
                   10399: 		$location=&filelocation($dir,$location);
1.736     albertel 10400: 		my $rights_metadata =
                   10401: 		    &metadata($uri,'keys',$location,'_rights',
                   10402: 			      $depthcount+1);
                   10403: 		foreach my $rights (split(',',$rights_metadata)) {
                   10404: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10405: 		    $metathesekeys{$rights}=1;
1.339     albertel 10406: 		}
                   10407: 	    }
                   10408: 	}
1.737     albertel 10409: 	# uniqifiy package listing
                   10410: 	my %seen;
                   10411: 	my @uniq_packages =
                   10412: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10413: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10414: 
1.1070    www      10415:         if ($importedparts) {
                   10416: # We had imported parts and need to rebuild partorder
                   10417:            $metaentry{':partorder'}='';
                   10418:            $metathesekeys{'partorder'}=1;
                   10419:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10420:                if ($origfileimportpartids[$index] eq 'part') {
                   10421: # original part, part of the problem
                   10422:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10423:                } else {
                   10424: # we have imported parts at this position
                   10425:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10426:                }
                   10427:            }
                   10428:            $metaentry{':partorder'}=~s/^\,//;
                   10429:         }
                   10430: 
1.737     albertel 10431: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10432: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10433: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10434: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10435: # this is the end of "was not already recently cached
1.71      www      10436:     }
1.599     albertel 10437:     return $metaentry{':'.$what};
1.261     albertel 10438: }
                   10439: 
1.488     albertel 10440: sub metadata_create_package_def {
1.483     albertel 10441:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10442:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10443:     if ($subp eq 'default') { next; }
                   10444:     
1.599     albertel 10445:     if (defined($metaentry{':packages'})) {
                   10446: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10447:     } else {
1.599     albertel 10448: 	$metaentry{':packages'}=$package;
1.483     albertel 10449:     }
                   10450:     my $value=$packagetab{$key};
                   10451:     my $unikey;
                   10452:     $unikey='parameter_0_'.$name;
1.599     albertel 10453:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10454:     $$metathesekeys{$unikey}=1;
1.599     albertel 10455:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10456: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10457:     }
1.599     albertel 10458:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10459: 	$metaentry{':'.$unikey}=
                   10460: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10461:     }
                   10462: }
                   10463: 
1.261     albertel 10464: sub metadata_generate_part0 {
                   10465:     my ($metadata,$metacache,$uri) = @_;
                   10466:     my %allnames;
1.737     albertel 10467:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10468: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10469: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10470: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10471: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10472: 	    $allnames{$name}=$part;
                   10473: 	  }
                   10474: 	}
                   10475:     }
                   10476:     foreach my $name (keys(%allnames)) {
                   10477:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10478:       my $key=":parameter_0_$name";
1.261     albertel 10479:       $$metacache{"$key.part"}='0';
                   10480:       $$metacache{"$key.name"}=$name;
1.428     albertel 10481:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10482: 					   $allnames{$name}.'_'.$name.
                   10483: 					   '.type'};
1.428     albertel 10484:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10485: 			     '.display'};
1.644     www      10486:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10487:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10488:       $$metacache{"$key.display"}=$olddis;
                   10489:     }
1.71      www      10490: }
                   10491: 
1.764     albertel 10492: # ------------------------------------------------------ Devalidate title cache
                   10493: 
                   10494: sub devalidate_title_cache {
                   10495:     my ($url)=@_;
                   10496:     if (!$env{'request.course.id'}) { return; }
                   10497:     my $symb=&symbread($url);
                   10498:     if (!$symb) { return; }
                   10499:     my $key=$env{'request.course.id'}."\0".$symb;
                   10500:     &devalidate_cache_new('title',$key);
                   10501: }
                   10502: 
1.1014    droeschl 10503: # ------------------------------------------------- Get the title of a course
                   10504: 
                   10505: sub current_course_title {
                   10506:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10507: }
1.301     www      10508: # ------------------------------------------------- Get the title of a resource
                   10509: 
                   10510: sub gettitle {
                   10511:     my $urlsymb=shift;
                   10512:     my $symb=&symbread($urlsymb);
1.534     albertel 10513:     if ($symb) {
1.620     albertel 10514: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10515: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10516: 	if (defined($cached)) { 
                   10517: 	    return $result;
                   10518: 	}
1.534     albertel 10519: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10520: 	my $title='';
1.907     albertel 10521: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10522: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10523: 	} else {
                   10524: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10525: 		    &GDBM_READER(),0640)) {
                   10526: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10527: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10528: 		untie(%bighash);
                   10529: 	    }
1.534     albertel 10530: 	}
                   10531: 	$title=~s/\&colon\;/\:/gs;
                   10532: 	if ($title) {
1.1159    www      10533: # Remember both $symb and $title for dynamic metadata
                   10534:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10535:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10536: # Cache this title and then return it
1.599     albertel 10537: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10538: 	}
                   10539: 	$urlsymb=$url;
                   10540:     }
                   10541:     my $title=&metadata($urlsymb,'title');
                   10542:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10543:     return $title;
1.301     www      10544: }
1.613     albertel 10545: 
1.614     albertel 10546: sub get_slot {
                   10547:     my ($which,$cnum,$cdom)=@_;
                   10548:     if (!$cnum || !$cdom) {
1.790     albertel 10549: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10550: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10551: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10552:     }
1.703     albertel 10553:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10554:     my %slotinfo;
                   10555:     if (exists($remembered{$key})) {
                   10556: 	$slotinfo{$which} = $remembered{$key};
                   10557:     } else {
                   10558: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10559: 	&Apache::lonhomework::showhash(%slotinfo);
                   10560: 	my ($tmp)=keys(%slotinfo);
                   10561: 	if ($tmp=~/^error:/) { return (); }
                   10562: 	$remembered{$key} = $slotinfo{$which};
                   10563:     }
1.616     albertel 10564:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10565: 	return %{$slotinfo{$which}};
                   10566:     }
                   10567:     return $slotinfo{$which};
1.614     albertel 10568: }
1.1150    raeburn  10569: 
                   10570: sub get_reservable_slots {
                   10571:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10572:     my $now = time;
                   10573:     my $reservable_info;
                   10574:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10575:     if (exists($remembered{$key})) {
                   10576:         $reservable_info = $remembered{$key};
                   10577:     } else {
                   10578:         my %resv;
                   10579:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10580:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10581:         $reservable_info = \%resv;
                   10582:         $remembered{$key} = $reservable_info;
                   10583:     }
                   10584:     return $reservable_info;
                   10585: }
                   10586: 
                   10587: sub get_course_slots {
                   10588:     my ($cnum,$cdom) = @_;
                   10589:     my $hashid=$cnum.':'.$cdom;
                   10590:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10591:     if (defined($cached)) {
                   10592:         if (ref($result) eq 'HASH') {
                   10593:             return %{$result};
                   10594:         }
                   10595:     } else {
                   10596:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10597:         my ($tmp) = keys(%slots);
                   10598:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10599:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10600:             return %slots;
                   10601:         }
                   10602:     }
                   10603:     return;
                   10604: }
                   10605: 
                   10606: sub devalidate_slots_cache {
                   10607:     my ($cnum,$cdom)=@_;
                   10608:     my $hashid=$cnum.':'.$cdom;
                   10609:     &devalidate_cache_new('allslots',$hashid);
                   10610: }
                   10611: 
1.1172.2.8  raeburn  10612: sub get_coursechange {
                   10613:     my ($cdom,$cnum) = @_;
                   10614:     if ($cdom eq '' || $cnum eq '') {
                   10615:         return unless ($env{'request.course.id'});
                   10616:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10617:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10618:     }
                   10619:     my $hashid=$cdom.'_'.$cnum;
                   10620:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10621:     if ((defined($cached)) && ($change ne '')) {
                   10622:         return $change;
                   10623:     } else {
                   10624:         my %crshash;
                   10625:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10626:         if ($crshash{'internal.contentchange'} eq '') {
                   10627:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10628:             if ($change eq '') {
                   10629:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10630:                 $change = $crshash{'internal.created'};
                   10631:             }
                   10632:         } else {
                   10633:             $change = $crshash{'internal.contentchange'};
                   10634:         }
                   10635:         my $cachetime = 600;
                   10636:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10637:     }
                   10638:     return $change;
                   10639: }
                   10640: 
                   10641: sub devalidate_coursechange_cache {
                   10642:     my ($cnum,$cdom)=@_;
                   10643:     my $hashid=$cnum.':'.$cdom;
                   10644:     &devalidate_cache_new('crschange',$hashid);
                   10645: }
                   10646: 
1.31      www      10647: # ------------------------------------------------- Update symbolic store links
                   10648: 
                   10649: sub symblist {
                   10650:     my ($mapname,%newhash)=@_;
1.438     www      10651:     $mapname=&deversion(&declutter($mapname));
1.31      www      10652:     my %hash;
1.620     albertel 10653:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10654:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10655:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10656: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10657: 		next if ($url eq 'last_known'
                   10658: 			 && $env{'form.no_update_last_known'});
                   10659: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10660: 						    $newhash{$url}->[1],
                   10661: 						    $newhash{$url}->[0]);
1.191     harris41 10662:             }
1.31      www      10663:             if (untie(%hash)) {
                   10664: 		return 'ok';
                   10665:             }
                   10666:         }
                   10667:     }
                   10668:     return 'error';
1.212     www      10669: }
                   10670: 
                   10671: # --------------------------------------------------------------- Verify a symb
                   10672: 
                   10673: sub symbverify {
1.1172.2.11  raeburn  10674:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10675:     my $thisfn=$thisurl;
1.439     www      10676:     $thisfn=&declutter($thisfn);
1.215     www      10677: # direct jump to resource in page or to a sequence - will construct own symbs
                   10678:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10679: # check URL part
1.409     www      10680:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10681: 
1.431     www      10682:     unless ($url eq $thisfn) { return 0; }
1.213     www      10683: 
1.216     www      10684:     $symb=&symbclean($symb);
1.510     www      10685:     $thisurl=&deversion($thisurl);
1.439     www      10686:     $thisfn=&deversion($thisfn);
1.213     www      10687: 
                   10688:     my %bighash;
                   10689:     my $okay=0;
1.431     www      10690: 
1.620     albertel 10691:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10692:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10693:         my $noclutter;
1.1032    raeburn  10694:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10695:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10696:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10697:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10698:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10699:                 $noclutter = 1;
                   10700:             }
                   10701:         }
                   10702:         my $ids;
                   10703:         if ($noclutter) {
                   10704:             $ids=$bighash{'ids_'.$thisurl};
                   10705:         } else {
                   10706:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10707:         }
1.1102    raeburn  10708:         unless ($ids) {
1.1172.2.13  raeburn  10709:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10710:             $ids=$bighash{$idkey};
1.216     www      10711:         }
                   10712:         if ($ids) {
                   10713: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10714:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10715:                 $symb =~ s/\?.+$//;
                   10716:             }
1.800     albertel 10717: 	    foreach my $id (split(/\,/,$ids)) {
                   10718: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10719:                if (
                   10720:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10721:    eq $symb) {
1.1172.2.11  raeburn  10722:                    if (ref($encstate)) {
                   10723:                        $$encstate = $bighash{'encrypted_'.$id};
                   10724:                    }
1.1172.2.13  raeburn  10725:                    if (($env{'request.role.adv'}) ||
                   10726:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10727:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10728:                        $okay=1;
                   10729:                        last;
                   10730:                    }
                   10731:                }
                   10732:            }
1.216     www      10733:         }
1.213     www      10734: 	untie(%bighash);
                   10735:     }
                   10736:     return $okay;
1.31      www      10737: }
                   10738: 
1.210     www      10739: # --------------------------------------------------------------- Clean-up symb
                   10740: 
                   10741: sub symbclean {
                   10742:     my $symb=shift;
1.568     albertel 10743:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10744: # remove version from map
                   10745:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10746: 
1.210     www      10747: # remove version from URL
                   10748:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10749: 
1.507     www      10750: # remove wrapper
                   10751: 
1.510     www      10752:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10753:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10754:     return $symb;
1.409     www      10755: }
                   10756: 
                   10757: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10758: 
                   10759: sub encode_symb {
                   10760:     my ($map,$resid,$url)=@_;
                   10761:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10762: }
1.409     www      10763: 
                   10764: sub decode_symb {
1.568     albertel 10765:     my $symb=shift;
                   10766:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10767:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10768:     return (&fixversion($map),$resid,&fixversion($url));
                   10769: }
                   10770: 
                   10771: sub fixversion {
                   10772:     my $fn=shift;
1.609     banghart 10773:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10774:     my %bighash;
                   10775:     my $uri=&clutter($fn);
1.620     albertel 10776:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10777: # is this cached?
1.599     albertel 10778:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10779:     if (defined($cached)) { return $result; }
                   10780: # unfortunately not cached, or expired
1.620     albertel 10781:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10782: 	    &GDBM_READER(),0640)) {
                   10783:  	if ($bighash{'version_'.$uri}) {
                   10784:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10785:  	    unless (($version eq 'mostrecent') || 
                   10786: 		    ($version==&getversion($uri))) {
1.440     www      10787:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10788:  	    }
                   10789:  	}
                   10790:  	untie %bighash;
1.413     www      10791:     }
1.599     albertel 10792:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10793: }
                   10794: 
                   10795: sub deversion {
                   10796:     my $url=shift;
                   10797:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10798:     return $url;
1.210     www      10799: }
                   10800: 
1.31      www      10801: # ------------------------------------------------------ Return symb list entry
                   10802: 
                   10803: sub symbread {
1.249     www      10804:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10805:     my $cache_str;
                   10806:     if ($thisfn ne '') {
                   10807:         $cache_str='request.symbread.cached.'.$thisfn;
                   10808:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10809:             return $env{$cache_str};
                   10810:         }
1.1172.2.13  raeburn  10811:    } else {
1.242     www      10812: # no filename provided? try from environment
1.620     albertel 10813:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10814:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10815:         }
                   10816:         $thisfn=$env{'request.filename'};
1.44      www      10817:     }
1.569     albertel 10818:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10819: # is that filename actually a symb? Verify, clean, and return
                   10820:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10821: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10822: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10823: 	}
1.242     www      10824:     }
1.44      www      10825:     $thisfn=declutter($thisfn);
1.31      www      10826:     my %hash;
1.37      www      10827:     my %bighash;
                   10828:     my $syval='';
1.620     albertel 10829:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10830:         my $targetfn = $thisfn;
1.609     banghart 10831:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10832:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10833:         }
1.687     albertel 10834: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10835: 	    $targetfn=$1;
                   10836: 	}
1.620     albertel 10837:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10838:                       &GDBM_READER(),0640)) {
1.481     raeburn  10839: 	    $syval=$hash{$targetfn};
1.37      www      10840:             untie(%hash);
                   10841:         }
                   10842: # ---------------------------------------------------------- There was an entry
                   10843:         if ($syval) {
1.601     albertel 10844: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10845: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10846: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10847: 		    #return $env{$cache_str}='';
1.601     albertel 10848: 		#}    
                   10849: 		#$syval.=$1;
                   10850: 	    #}
1.37      www      10851:         } else {
                   10852: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10853:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10854:                             &GDBM_READER(),0640)) {
1.37      www      10855: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10856:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10857:               unless ($ids) { 
                   10858:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10859:               }
                   10860:               unless ($ids) {
                   10861: # alias?
                   10862: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10863:               }
1.37      www      10864:               if ($ids) {
                   10865: # ------------------------------------------------------------------- Has ID(s)
                   10866:                  my @possibilities=split(/\,/,$ids);
1.39      www      10867:                  if ($#possibilities==0) {
                   10868: # ----------------------------------------------- There is only one possibility
1.37      www      10869: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10870: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10871: 						    $resid,$thisfn);
1.249     www      10872:                  } elsif (!$donotrecurse) {
1.39      www      10873: # ------------------------------------------ There is more than one possibility
                   10874:                      my $realpossible=0;
1.800     albertel 10875:                      foreach my $id (@possibilities) {
                   10876: 			 my $file=$bighash{'src_'.$id};
1.39      www      10877:                          if (&allowed('bre',$file)) {
1.800     albertel 10878:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10879:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10880: 				$realpossible++;
1.626     albertel 10881:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10882: 						    $resid,$thisfn);
1.39      www      10883:                             }
                   10884: 			 }
1.191     harris41 10885:                      }
1.39      www      10886: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10887:                  } else {
                   10888:                      $syval='';
1.37      www      10889:                  }
                   10890: 	      }
                   10891:               untie(%bighash)
1.481     raeburn  10892:            }
1.31      www      10893:         }
1.62      www      10894:         if ($syval) {
1.620     albertel 10895: 	    return $env{$cache_str}=$syval;
1.62      www      10896:         }
1.31      www      10897:     }
1.949     raeburn  10898:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10899:     return $env{$cache_str}='';
1.31      www      10900: }
                   10901: 
                   10902: # ---------------------------------------------------------- Return random seed
                   10903: 
1.32      www      10904: sub numval {
                   10905:     my $txt=shift;
                   10906:     $txt=~tr/A-J/0-9/;
                   10907:     $txt=~tr/a-j/0-9/;
                   10908:     $txt=~tr/K-T/0-9/;
                   10909:     $txt=~tr/k-t/0-9/;
                   10910:     $txt=~tr/U-Z/0-5/;
                   10911:     $txt=~tr/u-z/0-5/;
                   10912:     $txt=~s/\D//g;
1.564     albertel 10913:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10914:     return int($txt);
1.368     albertel 10915: }
                   10916: 
1.484     albertel 10917: sub numval2 {
                   10918:     my $txt=shift;
                   10919:     $txt=~tr/A-J/0-9/;
                   10920:     $txt=~tr/a-j/0-9/;
                   10921:     $txt=~tr/K-T/0-9/;
                   10922:     $txt=~tr/k-t/0-9/;
                   10923:     $txt=~tr/U-Z/0-5/;
                   10924:     $txt=~tr/u-z/0-5/;
                   10925:     $txt=~s/\D//g;
                   10926:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10927:     my $total;
                   10928:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10929:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10930:     return int($total);
                   10931: }
                   10932: 
1.575     albertel 10933: sub numval3 {
                   10934:     use integer;
                   10935:     my $txt=shift;
                   10936:     $txt=~tr/A-J/0-9/;
                   10937:     $txt=~tr/a-j/0-9/;
                   10938:     $txt=~tr/K-T/0-9/;
                   10939:     $txt=~tr/k-t/0-9/;
                   10940:     $txt=~tr/U-Z/0-5/;
                   10941:     $txt=~tr/u-z/0-5/;
                   10942:     $txt=~s/\D//g;
                   10943:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10944:     my $total;
                   10945:     foreach my $val (@txts) { $total+=$val; }
                   10946:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10947:     return $total;
                   10948: }
                   10949: 
1.675     albertel 10950: sub digest {
                   10951:     my ($data)=@_;
                   10952:     my $digest=&Digest::MD5::md5($data);
                   10953:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10954:     my ($e,$f);
                   10955:     {
                   10956:         use integer;
                   10957:         $e=($a+$b);
                   10958:         $f=($c+$d);
                   10959:         if ($_64bit) {
                   10960:             $e=(($e<<32)>>32);
                   10961:             $f=(($f<<32)>>32);
                   10962:         }
                   10963:     }
                   10964:     if (wantarray) {
                   10965: 	return ($e,$f);
                   10966:     } else {
                   10967: 	my $g;
                   10968: 	{
                   10969: 	    use integer;
                   10970: 	    $g=($e+$f);
                   10971: 	    if ($_64bit) {
                   10972: 		$g=(($g<<32)>>32);
                   10973: 	    }
                   10974: 	}
                   10975: 	return $g;
                   10976:     }
                   10977: }
                   10978: 
1.368     albertel 10979: sub latest_rnd_algorithm_id {
1.675     albertel 10980:     return '64bit5';
1.366     albertel 10981: }
1.32      www      10982: 
1.503     albertel 10983: sub get_rand_alg {
                   10984:     my ($courseid)=@_;
1.790     albertel 10985:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10986:     if ($courseid) {
1.620     albertel 10987: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10988:     }
                   10989:     return &latest_rnd_algorithm_id();
                   10990: }
                   10991: 
1.562     albertel 10992: sub validCODE {
                   10993:     my ($CODE)=@_;
                   10994:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10995:     return 0;
                   10996: }
                   10997: 
1.491     albertel 10998: sub getCODE {
1.620     albertel 10999:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11000:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11001: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11002: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11003: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11004:     }
                   11005:     return undef;
                   11006: }
1.1133    foxr     11007: #
                   11008: #  Determines the random seed for a specific context:
                   11009: #
                   11010: # parameters:
                   11011: #   symb      - in course context the symb for the seed.
                   11012: #   course_id - The course id of the form domain_coursenum.
                   11013: #   domain    - Domain for the user.
                   11014: #   course    - Course for the user.
                   11015: #   cenv      - environment of the course.
                   11016: #
                   11017: # NOTE:
                   11018: #   All parameters are picked out of the environment if missing
                   11019: #   or not defined.
                   11020: #   If a symb cannot be determined the current time is used instead.
                   11021: #
                   11022: #  For a given well defined symb, courside, domain, username,
                   11023: #  and course environment, the seed is reproducible.
                   11024: #
1.31      www      11025: sub rndseed {
1.1133    foxr     11026:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11027:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11028:     if (!defined($symb)) {
1.366     albertel 11029: 	unless ($symb=$wsymb) { return time; }
                   11030:     }
1.1146    foxr     11031:     if (!defined $courseid) { 
                   11032: 	$courseid=$wcourseid; 
                   11033:     }
                   11034:     if (!defined $domain) { $domain=$wdomain; }
                   11035:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11036: 
                   11037:     my $which;
                   11038:     if (defined($cenv->{'rndseed'})) {
                   11039: 	$which = $cenv->{'rndseed'};
                   11040:     } else {
                   11041: 	$which =&get_rand_alg($courseid);
                   11042:     }
1.491     albertel 11043:     if (defined(&getCODE())) {
1.675     albertel 11044: 	if ($which eq '64bit5') {
                   11045: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11046: 	} elsif ($which eq '64bit4') {
1.575     albertel 11047: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11048: 	} else {
                   11049: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11050: 	}
1.675     albertel 11051:     } elsif ($which eq '64bit5') {
                   11052: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11053:     } elsif ($which eq '64bit4') {
                   11054: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11055:     } elsif ($which eq '64bit3') {
                   11056: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11057:     } elsif ($which eq '64bit2') {
                   11058: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11059:     } elsif ($which eq '64bit') {
                   11060: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11061:     }
                   11062:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11063: }
                   11064: 
                   11065: sub rndseed_32bit {
                   11066:     my ($symb,$courseid,$domain,$username)=@_;
                   11067:     {
                   11068: 	use integer;
                   11069: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11070: 	my $symbseed=numval($symb) << 22;
                   11071: 	my $namechck=unpack("%32C*",$username) << 17;
                   11072: 	my $nameseed=numval($username) << 12;
                   11073: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11074: 	my $courseseed=unpack("%32C*",$courseid);
                   11075: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11077: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11078: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11079: 	return $num;
                   11080:     }
                   11081: }
                   11082: 
                   11083: sub rndseed_64bit {
                   11084:     my ($symb,$courseid,$domain,$username)=@_;
                   11085:     {
                   11086: 	use integer;
                   11087: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11088: 	my $symbseed=numval($symb) << 10;
                   11089: 	my $namechck=unpack("%32S*",$username);
                   11090: 	
                   11091: 	my $nameseed=numval($username) << 21;
                   11092: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11093: 	my $courseseed=unpack("%32S*",$courseid);
                   11094: 	
                   11095: 	my $num1=$symbchck+$symbseed+$namechck;
                   11096: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11097: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11098: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11099: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11100: 	return "$num1,$num2";
1.155     albertel 11101:     }
1.366     albertel 11102: }
                   11103: 
1.443     albertel 11104: sub rndseed_64bit2 {
                   11105:     my ($symb,$courseid,$domain,$username)=@_;
                   11106:     {
                   11107: 	use integer;
                   11108: 	# strings need to be an even # of cahracters long, it it is odd the
                   11109:         # last characters gets thrown away
                   11110: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11111: 	my $symbseed=numval($symb) << 10;
                   11112: 	my $namechck=unpack("%32S*",$username.' ');
                   11113: 	
                   11114: 	my $nameseed=numval($username) << 21;
1.501     albertel 11115: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11116: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11117: 	
                   11118: 	my $num1=$symbchck+$symbseed+$namechck;
                   11119: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11120: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11121: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11122: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11123: 	return "$num1,$num2";
                   11124:     }
                   11125: }
                   11126: 
                   11127: sub rndseed_64bit3 {
                   11128:     my ($symb,$courseid,$domain,$username)=@_;
                   11129:     {
                   11130: 	use integer;
                   11131: 	# strings need to be an even # of cahracters long, it it is odd the
                   11132:         # last characters gets thrown away
                   11133: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11134: 	my $symbseed=numval2($symb) << 10;
                   11135: 	my $namechck=unpack("%32S*",$username.' ');
                   11136: 	
                   11137: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11138: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11139: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11140: 	
                   11141: 	my $num1=$symbchck+$symbseed+$namechck;
                   11142: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11143: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11144: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11145: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11146: 	
1.503     albertel 11147: 	return "$num1:$num2";
1.443     albertel 11148:     }
                   11149: }
                   11150: 
1.575     albertel 11151: sub rndseed_64bit4 {
                   11152:     my ($symb,$courseid,$domain,$username)=@_;
                   11153:     {
                   11154: 	use integer;
                   11155: 	# strings need to be an even # of cahracters long, it it is odd the
                   11156:         # last characters gets thrown away
                   11157: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11158: 	my $symbseed=numval3($symb) << 10;
                   11159: 	my $namechck=unpack("%32S*",$username.' ');
                   11160: 	
                   11161: 	my $nameseed=numval3($username) << 21;
                   11162: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11163: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11164: 	
                   11165: 	my $num1=$symbchck+$symbseed+$namechck;
                   11166: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11167: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11168: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11169: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11170: 	
1.575     albertel 11171: 	return "$num1:$num2";
                   11172:     }
                   11173: }
                   11174: 
1.675     albertel 11175: sub rndseed_64bit5 {
                   11176:     my ($symb,$courseid,$domain,$username)=@_;
                   11177:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11178:     return "$num1:$num2";
                   11179: }
                   11180: 
1.366     albertel 11181: sub rndseed_CODE_64bit {
                   11182:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11183:     {
1.366     albertel 11184: 	use integer;
1.443     albertel 11185: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11186: 	my $symbseed=numval2($symb);
1.491     albertel 11187: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11188: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11189: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11190: 	my $num1=$symbseed+$CODEchck;
                   11191: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11192: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11193: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11194: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11195: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11196: 	return "$num1:$num2";
1.366     albertel 11197:     }
                   11198: }
                   11199: 
1.575     albertel 11200: sub rndseed_CODE_64bit4 {
                   11201:     my ($symb,$courseid,$domain,$username)=@_;
                   11202:     {
                   11203: 	use integer;
                   11204: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11205: 	my $symbseed=numval3($symb);
                   11206: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11207: 	my $CODEseed=numval3(&getCODE());
                   11208: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11209: 	my $num1=$symbseed+$CODEchck;
                   11210: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11211: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11212: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11213: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11214: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11215: 	return "$num1:$num2";
                   11216:     }
                   11217: }
                   11218: 
1.675     albertel 11219: sub rndseed_CODE_64bit5 {
                   11220:     my ($symb,$courseid,$domain,$username)=@_;
                   11221:     my $code = &getCODE();
                   11222:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11223:     return "$num1:$num2";
                   11224: }
                   11225: 
1.366     albertel 11226: sub setup_random_from_rndseed {
                   11227:     my ($rndseed)=@_;
1.503     albertel 11228:     if ($rndseed =~/([,:])/) {
                   11229: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11230: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11231:     } else {
                   11232: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11233:     }
1.36      albertel 11234: }
                   11235: 
1.474     albertel 11236: sub latest_receipt_algorithm_id {
1.835     albertel 11237:     return 'receipt3';
1.474     albertel 11238: }
                   11239: 
1.480     www      11240: sub recunique {
                   11241:     my $fucourseid=shift;
                   11242:     my $unique;
1.835     albertel 11243:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11244: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11245: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11246:     } else {
                   11247: 	$unique=$perlvar{'lonReceipt'};
                   11248:     }
                   11249:     return unpack("%32C*",$unique);
                   11250: }
                   11251: 
                   11252: sub recprefix {
                   11253:     my $fucourseid=shift;
                   11254:     my $prefix;
1.835     albertel 11255:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11256: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11257: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11258:     } else {
                   11259: 	$prefix=$perlvar{'lonHostID'};
                   11260:     }
                   11261:     return unpack("%32C*",$prefix);
                   11262: }
                   11263: 
1.76      www      11264: sub ireceipt {
1.474     albertel 11265:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11266: 
                   11267:     my $return =&recprefix($fucourseid).'-';
                   11268: 
                   11269:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11270: 	$env{'request.state'} eq 'construct') {
                   11271: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11272: 	return $return;
                   11273:     }
                   11274: 
1.76      www      11275:     my $cuname=unpack("%32C*",$funame);
                   11276:     my $cudom=unpack("%32C*",$fudom);
                   11277:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11278:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11279:     my $cunique=&recunique($fucourseid);
1.474     albertel 11280:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11281:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11282: 
1.790     albertel 11283: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11284: 			       
                   11285: 	$return.= ($cunique%$cuname+
                   11286: 		   $cunique%$cudom+
                   11287: 		   $cusymb%$cuname+
                   11288: 		   $cusymb%$cudom+
                   11289: 		   $cucourseid%$cuname+
                   11290: 		   $cucourseid%$cudom+
                   11291: 		   $cpart%$cuname+
                   11292: 		   $cpart%$cudom);
                   11293:     } else {
                   11294: 	$return.= ($cunique%$cuname+
                   11295: 		   $cunique%$cudom+
                   11296: 		   $cusymb%$cuname+
                   11297: 		   $cusymb%$cudom+
                   11298: 		   $cucourseid%$cuname+
                   11299: 		   $cucourseid%$cudom);
                   11300:     }
                   11301:     return $return;
1.76      www      11302: }
                   11303: 
                   11304: sub receipt {
1.474     albertel 11305:     my ($part)=@_;
1.790     albertel 11306:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11307:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11308: }
1.260     ng       11309: 
1.790     albertel 11310: sub whichuser {
                   11311:     my ($passedsymb)=@_;
                   11312:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11313:     if (defined($env{'form.grade_symb'})) {
                   11314: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11315: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11316: 	if (!$allowed &&
                   11317: 	    exists($env{'request.course.sec'}) &&
                   11318: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11319: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11320: 			      '/'.$env{'request.course.sec'});
                   11321: 	}
                   11322: 	if ($allowed) {
                   11323: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11324: 	    $courseid=$tmp_courseid;
                   11325: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11326: 	    ($name)=&get_env_multiple('form.grade_username');
                   11327: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11328: 	}
                   11329:     }
                   11330:     if (!$passedsymb) {
                   11331: 	$symb=&symbread();
                   11332:     } else {
                   11333: 	$symb=$passedsymb;
                   11334:     }
                   11335:     $courseid=$env{'request.course.id'};
                   11336:     $domain=$env{'user.domain'};
                   11337:     $name=$env{'user.name'};
                   11338:     if ($name eq 'public' && $domain eq 'public') {
                   11339: 	if (!defined($env{'form.username'})) {
                   11340: 	    $env{'form.username'}.=time.rand(10000000);
                   11341: 	}
                   11342: 	$name.=$env{'form.username'};
                   11343:     }
                   11344:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11345: 
                   11346: }
                   11347: 
1.36      albertel 11348: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11349: # returns either the contents of the file or 
                   11350: # -1 if the file doesn't exist
1.481     raeburn  11351: #
                   11352: # if the target is a file that was uploaded via DOCS, 
                   11353: # a check will be made to see if a current copy exists on the local server,
                   11354: # if it does this will be served, otherwise a copy will be retrieved from
                   11355: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11356: # the local server.   
1.472     albertel 11357: 
1.36      albertel 11358: sub getfile {
1.538     albertel 11359:     my ($file) = @_;
1.609     banghart 11360:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11361:     &repcopy($file);
                   11362:     return &readfile($file);
                   11363: }
                   11364: 
                   11365: sub repcopy_userfile {
                   11366:     my ($file)=@_;
1.1142    raeburn  11367:     my $londocroot = $perlvar{'lonDocRoot'};
                   11368:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11369:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11370:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11371: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11372:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11373:     if (-e "$file") {
1.828     www      11374: # we already have a local copy, check it out
1.538     albertel 11375: 	my @fileinfo = stat($file);
1.828     www      11376: 	my $rtncode;
                   11377: 	my $info;
1.538     albertel 11378: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11379: 	if ($lwpresp ne 'ok') {
1.828     www      11380: # there is no such file anymore, even though we had a local copy
1.482     albertel 11381: 	    if ($rtncode eq '404') {
1.538     albertel 11382: 		unlink($file);
1.482     albertel 11383: 	    }
                   11384: 	    return -1;
                   11385: 	}
                   11386: 	if ($info < $fileinfo[9]) {
1.828     www      11387: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11388: 	    return 'ok';
1.828     www      11389: 	} else {
                   11390: # the file is outdated, get rid of it
                   11391: 	    unlink($file);
1.482     albertel 11392: 	}
1.828     www      11393:     }
                   11394: # one way or the other, at this point, we don't have the file
                   11395: # construct the correct path for the file
                   11396:     my @parts = ($cdom,$cnum); 
                   11397:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11398: 	push @parts, split(/\//,$1);
                   11399:     }
                   11400:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11401:     foreach my $part (@parts) {
                   11402: 	$path .= '/'.$part;
                   11403: 	if (!-e $path) {
                   11404: 	    mkdir($path,0770);
1.482     albertel 11405: 	}
                   11406:     }
1.828     www      11407: # now the path exists for sure
                   11408: # get a user agent
                   11409:     my $ua=new LWP::UserAgent;
                   11410:     my $transferfile=$file.'.in.transfer';
                   11411: # FIXME: this should flock
                   11412:     if (-e $transferfile) { return 'ok'; }
                   11413:     my $request;
                   11414:     $uri=~s/^\///;
1.980     raeburn  11415:     my $homeserver = &homeserver($cnum,$cdom);
                   11416:     my $protocol = $protocol{$homeserver};
                   11417:     $protocol = 'http' if ($protocol ne 'https');
                   11418:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11419:     my $response=$ua->request($request,$transferfile);
                   11420: # did it work?
                   11421:     if ($response->is_error()) {
                   11422: 	unlink($transferfile);
                   11423: 	&logthis("Userfile repcopy failed for $uri");
                   11424: 	return -1;
                   11425:     }
                   11426: # worked, rename the transfer file
                   11427:     rename($transferfile,$file);
1.607     raeburn  11428:     return 'ok';
1.481     raeburn  11429: }
                   11430: 
1.517     albertel 11431: sub tokenwrapper {
                   11432:     my $uri=shift;
1.980     raeburn  11433:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11434:     $uri=~s|^/||;
1.620     albertel 11435:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11436:     my $token=$1;
1.552     albertel 11437:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11438:     if ($udom && $uname && $file) {
                   11439: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11440:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11441:         my $homeserver = &homeserver($uname,$udom);
                   11442:         my $protocol = $protocol{$homeserver};
                   11443:         $protocol = 'http' if ($protocol ne 'https');
                   11444:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11445:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11446:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11447:     } else {
                   11448:         return '/adm/notfound.html';
                   11449:     }
                   11450: }
                   11451: 
1.828     www      11452: # call with reqtype HEAD: get last modification time
                   11453: # call with reqtype GET: get the file contents
                   11454: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11455: #
1.481     raeburn  11456: sub getuploaded {
                   11457:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11458:     $uri=~s/^\///;
1.980     raeburn  11459:     my $homeserver = &homeserver($cnum,$cdom);
                   11460:     my $protocol = $protocol{$homeserver};
                   11461:     $protocol = 'http' if ($protocol ne 'https');
                   11462:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11463:     my $ua=new LWP::UserAgent;
                   11464:     my $request=new HTTP::Request($reqtype,$uri);
                   11465:     my $response=$ua->request($request);
                   11466:     $$rtncode = $response->code;
1.482     albertel 11467:     if (! $response->is_success()) {
                   11468: 	return 'failed';
                   11469:     }      
                   11470:     if ($reqtype eq 'HEAD') {
1.486     www      11471: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11472:     } elsif ($reqtype eq 'GET') {
                   11473: 	$$info = $response->content;
1.472     albertel 11474:     }
1.482     albertel 11475:     return 'ok';
1.36      albertel 11476: }
                   11477: 
1.481     raeburn  11478: sub readfile {
                   11479:     my $file = shift;
                   11480:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11481:     my $fh;
                   11482:     open($fh,"<$file");
                   11483:     my $a='';
1.800     albertel 11484:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11485:     return $a;
                   11486: }
                   11487: 
1.36      albertel 11488: sub filelocation {
1.590     banghart 11489:     my ($dir,$file) = @_;
                   11490:     my $location;
                   11491:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11492: 
                   11493:     if ($file =~ m-^/adm/-) {
                   11494: 	$file=~s-^/adm/wrapper/-/-;
                   11495: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11496:     }
1.882     albertel 11497: 
1.1139    www      11498:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11499:         $location = $file;
1.609     banghart 11500:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11501:         my ($udom,$uname,$filename)=
1.811     albertel 11502:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11503:         my $home=&homeserver($uname,$udom);
                   11504:         my $is_me=0;
                   11505:         my @ids=&current_machine_ids();
                   11506:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11507:         if ($is_me) {
1.1117    foxr     11508:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11509:         } else {
                   11510:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11511:   	      $udom.'/'.$uname.'/'.$filename;
                   11512:         }
1.882     albertel 11513:     } elsif ($file =~ m-^/adm/-) {
                   11514: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11515:     } else {
                   11516:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11517:         $file=~s:^/(res|priv)/:/:;
                   11518:         my $space=$1;
1.590     banghart 11519:         if ( !( $file =~ m:^/:) ) {
                   11520:             $location = $dir. '/'.$file;
                   11521:         } else {
1.1142    raeburn  11522:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11523:         }
1.59      albertel 11524:     }
1.590     banghart 11525:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11526:     while ($location=~m{/\.\./}) {
                   11527: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11528: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11529: 	} else {
                   11530: 	    $location=~ s{/\.\./}{/}g;
                   11531: 	}
                   11532:     } #remove dir/..
1.590     banghart 11533:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11534:     return $location;
1.46      www      11535: }
1.36      albertel 11536: 
1.46      www      11537: sub hreflocation {
                   11538:     my ($dir,$file)=@_;
1.980     raeburn  11539:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11540: 	$file=filelocation($dir,$file);
1.700     albertel 11541:     } elsif ($file=~m-^/adm/-) {
                   11542: 	$file=~s-^/adm/wrapper/-/-;
                   11543: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11544:     }
                   11545:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11546: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11547:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11548: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11549: 	        {/uploaded/$1/$2/}x;
1.46      www      11550:     }
1.913     albertel 11551:     if ($file=~ m{^/userfiles/}) {
                   11552: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11553:     }
1.462     albertel 11554:     return $file;
1.465     albertel 11555: }
                   11556: 
1.1139    www      11557: 
                   11558: 
                   11559: 
                   11560: 
1.465     albertel 11561: sub current_machine_domains {
1.853     albertel 11562:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11563: }
                   11564: 
                   11565: sub machine_domains {
                   11566:     my ($hostname) = @_;
1.465     albertel 11567:     my @domains;
1.838     albertel 11568:     my %hostname = &all_hostnames();
1.465     albertel 11569:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11570: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11571: 	if ($hostname eq $name) {
1.844     albertel 11572: 	    push(@domains,&host_domain($id));
1.465     albertel 11573: 	}
                   11574:     }
                   11575:     return @domains;
                   11576: }
                   11577: 
                   11578: sub current_machine_ids {
1.853     albertel 11579:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11580: }
                   11581: 
                   11582: sub machine_ids {
                   11583:     my ($hostname) = @_;
                   11584:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11585:     my @ids;
1.888     albertel 11586:     my %name_to_host = &all_names();
1.889     albertel 11587:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11588: 	return @{ $name_to_host{$hostname} };
                   11589:     }
                   11590:     return;
1.31      www      11591: }
                   11592: 
1.824     raeburn  11593: sub additional_machine_domains {
                   11594:     my @domains;
                   11595:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11596:     while( my $line = <$fh>) {
                   11597:         $line =~ s/\s//g;
                   11598:         push(@domains,$line);
                   11599:     }
                   11600:     return @domains;
                   11601: }
                   11602: 
                   11603: sub default_login_domain {
                   11604:     my $domain = $perlvar{'lonDefDomain'};
                   11605:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11606:     foreach my $posdom (&current_machine_domains(),
                   11607:                         &additional_machine_domains()) {
                   11608:         if (lc($posdom) eq lc($testdomain)) {
                   11609:             $domain=$posdom;
                   11610:             last;
                   11611:         }
                   11612:     }
                   11613:     return $domain;
                   11614: }
                   11615: 
1.31      www      11616: # ------------------------------------------------------------- Declutters URLs
                   11617: 
                   11618: sub declutter {
                   11619:     my $thisfn=shift;
1.569     albertel 11620:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11621:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11622:     $thisfn=~s/^\///;
1.697     albertel 11623:     $thisfn=~s|^adm/wrapper/||;
                   11624:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11625:     $thisfn=~s/^res\///;
1.1172    bisitz   11626:     $thisfn=~s/^priv\///;
1.1032    raeburn  11627:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11628:         $thisfn=~s/\?.+$//;
                   11629:     }
1.268     www      11630:     return $thisfn;
                   11631: }
                   11632: 
                   11633: # ------------------------------------------------------------- Clutter up URLs
                   11634: 
                   11635: sub clutter {
                   11636:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11637:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11638: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11639:        $thisfn='/res'.$thisfn; 
                   11640:     }
1.1031    raeburn  11641:     if ($thisfn !~m|^/adm|) {
                   11642: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11643: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11644: 	} else {
                   11645: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11646: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11647: 	    if ($embstyle eq 'ssi'
                   11648: 		|| ($embstyle eq 'hdn')
                   11649: 		|| ($embstyle eq 'rat')
                   11650: 		|| ($embstyle eq 'prv')
                   11651: 		|| ($embstyle eq 'ign')) {
                   11652: 		#do nothing with these
                   11653: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11654: 		|| ($embstyle eq 'emb')
                   11655: 		|| ($embstyle eq 'wrp')) {
                   11656: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11657: 	    } elsif ($embstyle eq 'unk'
                   11658: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11659: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11660: 	    } else {
1.718     www      11661: #		&logthis("Got a blank emb style");
1.695     albertel 11662: 	    }
1.694     albertel 11663: 	}
                   11664:     }
1.31      www      11665:     return $thisfn;
1.12      www      11666: }
                   11667: 
1.787     albertel 11668: sub clutter_with_no_wrapper {
                   11669:     my $uri = &clutter(shift);
                   11670:     if ($uri =~ m-^/adm/-) {
                   11671: 	$uri =~ s-^/adm/wrapper/-/-;
                   11672: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11673:     }
                   11674:     return $uri;
                   11675: }
                   11676: 
1.557     albertel 11677: sub freeze_escape {
                   11678:     my ($value)=@_;
                   11679:     if (ref($value)) {
                   11680: 	$value=&nfreeze($value);
                   11681: 	return '__FROZEN__'.&escape($value);
                   11682:     }
                   11683:     return &escape($value);
                   11684: }
                   11685: 
1.11      www      11686: 
1.557     albertel 11687: sub thaw_unescape {
                   11688:     my ($value)=@_;
                   11689:     if ($value =~ /^__FROZEN__/) {
                   11690: 	substr($value,0,10,undef);
                   11691: 	$value=&unescape($value);
                   11692: 	return &thaw($value);
                   11693:     }
                   11694:     return &unescape($value);
                   11695: }
                   11696: 
1.436     albertel 11697: sub correct_line_ends {
                   11698:     my ($result)=@_;
                   11699:     $$result =~s/\r\n/\n/mg;
                   11700:     $$result =~s/\r/\n/mg;
1.415     albertel 11701: }
1.1       albertel 11702: # ================================================================ Main Program
                   11703: 
1.184     www      11704: sub goodbye {
1.204     albertel 11705:    &logthis("Starting Shut down");
1.443     albertel 11706: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11707:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11708: #converted
1.599     albertel 11709: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11710:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11711: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11712: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11713: #1.1 only
1.870     albertel 11714: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11715: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11716: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11717: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11718:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11719:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11720:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11721:    &flushcourselogs();
                   11722:    &logthis("Shutting down");
                   11723: }
                   11724: 
1.852     albertel 11725: sub get_dns {
1.1172.2.17  raeburn  11726:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11727:     if (!$ignore_cache) {
                   11728: 	my ($content,$cached)=
                   11729: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11730: 	if ($cached) {
1.1172.2.17  raeburn  11731: 	    &$func($content,$hashref);
1.869     albertel 11732: 	    return;
                   11733: 	}
                   11734:     }
                   11735: 
                   11736:     my %alldns;
1.852     albertel 11737:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11738:     foreach my $dns (<$config>) {
                   11739: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11740:         my $line = $1;
                   11741:         my ($host,$protocol) = split(/:/,$line);
                   11742:         if ($protocol ne 'https') {
                   11743:             $protocol = 'http';
                   11744:         }
                   11745: 	$alldns{$host} = $protocol;
1.869     albertel 11746:     }
                   11747:     while (%alldns) {
                   11748: 	my ($dns) = keys(%alldns);
1.852     albertel 11749: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11750:         $ua->timeout(30);
1.979     raeburn  11751: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11752: 	my $response=$ua->request($request);
1.979     raeburn  11753:         delete($alldns{$dns});
1.852     albertel 11754: 	next if ($response->is_error());
                   11755: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11756:         unless ($nocache) {
1.1172.2.23  raeburn  11757: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11758:         }
                   11759: 	&$func(\@content,$hashref);
1.869     albertel 11760: 	return;
1.852     albertel 11761:     }
                   11762:     close($config);
1.871     albertel 11763:     my $which = (split('/',$url))[3];
                   11764:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11765:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11766:     my @content = <$config>;
1.1172.2.17  raeburn  11767:     &$func(\@content,$hashref);
                   11768:     return;
                   11769: }
                   11770: 
                   11771: # ------------------------------------------------------Get DNS checksums file
                   11772: sub parse_dns_checksums_tab {
                   11773:     my ($lines,$hashref) = @_;
                   11774:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11775:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11776:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11777:     my (%chksum,%revnum);
                   11778:     if (ref($lines) eq 'ARRAY') {
                   11779:         chomp(@{$lines});
1.1172.2.34! raeburn  11780:         my $version = shift(@{$lines});
        !          11781:         if ($version eq $release) {
1.1172.2.17  raeburn  11782:             foreach my $line (@{$lines}) {
1.1172.2.34! raeburn  11783:                 my ($file,$version,$shasum) = split(/,/,$line);
        !          11784:                 $chksum{$file} = $shasum;
        !          11785:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  11786:             }
                   11787:             if (ref($hashref) eq 'HASH') {
                   11788:                 %{$hashref} = (
                   11789:                                 sums     => \%chksum,
                   11790:                                 versions => \%revnum,
                   11791:                               );
                   11792:             }
                   11793:         }
                   11794:     }
1.869     albertel 11795:     return;
1.852     albertel 11796: }
1.1172.2.17  raeburn  11797: 
                   11798: sub fetch_dns_checksums {
                   11799:     my %checksums;
1.1172.2.34! raeburn  11800:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
        !          11801:     my $loncaparev = &get_server_loncaparev($machine_dom);
        !          11802:     my ($release,$timestamp) = split(/\-/,$loncaparev);
        !          11803:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  11804:              \%checksums);
                   11805:     return \%checksums;
                   11806: }
                   11807: 
1.327     albertel 11808: # ------------------------------------------------------------ Read domain file
                   11809: {
1.852     albertel 11810:     my $loaded;
1.846     albertel 11811:     my %domain;
                   11812: 
1.852     albertel 11813:     sub parse_domain_tab {
                   11814: 	my ($lines) = @_;
                   11815: 	foreach my $line (@$lines) {
                   11816: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11817: 
1.846     albertel 11818: 	    chomp($line);
1.852     albertel 11819: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11820: 	    my %this_domain;
                   11821: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11822: 			       'lang_def', 'city', 'longi', 'lati',
                   11823: 			       'primary') {
                   11824: 		$this_domain{$field} = shift(@elements);
                   11825: 	    }
                   11826: 	    $domain{$name} = \%this_domain;
1.852     albertel 11827: 	}
                   11828:     }
1.864     albertel 11829: 
                   11830:     sub reset_domain_info {
                   11831: 	undef($loaded);
                   11832: 	undef(%domain);
                   11833:     }
                   11834: 
1.852     albertel 11835:     sub load_domain_tab {
1.869     albertel 11836: 	my ($ignore_cache) = @_;
                   11837: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11838: 	my $fh;
                   11839: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11840: 	    my @lines = <$fh>;
                   11841: 	    &parse_domain_tab(\@lines);
1.448     albertel 11842: 	}
1.852     albertel 11843: 	close($fh);
                   11844: 	$loaded = 1;
1.327     albertel 11845:     }
1.846     albertel 11846: 
                   11847:     sub domain {
1.852     albertel 11848: 	&load_domain_tab() if (!$loaded);
                   11849: 
1.846     albertel 11850: 	my ($name,$what) = @_;
                   11851: 	return if ( !exists($domain{$name}) );
                   11852: 
                   11853: 	if (!$what) {
                   11854: 	    return $domain{$name}{'description'};
                   11855: 	}
                   11856: 	return $domain{$name}{$what};
                   11857:     }
1.974     raeburn  11858: 
                   11859:     sub domain_info {
                   11860:         &load_domain_tab() if (!$loaded);
                   11861:         return %domain;
                   11862:     }
                   11863: 
1.327     albertel 11864: }
                   11865: 
                   11866: 
1.1       albertel 11867: # ------------------------------------------------------------- Read hosts file
                   11868: {
1.838     albertel 11869:     my %hostname;
1.844     albertel 11870:     my %hostdom;
1.845     albertel 11871:     my %libserv;
1.852     albertel 11872:     my $loaded;
1.888     albertel 11873:     my %name_to_host;
1.1074    raeburn  11874:     my %internetdom;
1.1107    raeburn  11875:     my %LC_dns_serv;
1.852     albertel 11876: 
                   11877:     sub parse_hosts_tab {
                   11878: 	my ($file) = @_;
                   11879: 	foreach my $configline (@$file) {
                   11880: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11881:             chomp($configline);
                   11882: 	    if ($configline =~ /^\^/) {
                   11883:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11884:                     $LC_dns_serv{$1} = 1;
                   11885:                 }
                   11886:                 next;
                   11887:             }
1.1074    raeburn  11888: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11889: 	    $name=~s/\s//g;
                   11890: 	    if ($id && $domain && $role && $name) {
                   11891: 		$hostname{$id}=$name;
1.888     albertel 11892: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11893: 		$hostdom{$id}=$domain;
                   11894: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11895:                 if (defined($protocol)) {
                   11896:                     if ($protocol eq 'https') {
                   11897:                         $protocol{$id} = $protocol;
                   11898:                     } else {
                   11899:                         $protocol{$id} = 'http'; 
                   11900:                     }
1.968     raeburn  11901:                 } else {
1.969     raeburn  11902:                     $protocol{$id} = 'http';
1.968     raeburn  11903:                 }
1.1074    raeburn  11904:                 if (defined($intdom)) {
                   11905:                     $internetdom{$id} = $intdom;
                   11906:                 }
1.852     albertel 11907: 	    }
                   11908: 	}
                   11909:     }
1.864     albertel 11910:     
                   11911:     sub reset_hosts_info {
1.897     albertel 11912: 	&purge_remembered();
1.864     albertel 11913: 	&reset_domain_info();
                   11914: 	&reset_hosts_ip_info();
1.892     albertel 11915: 	undef(%name_to_host);
1.864     albertel 11916: 	undef(%hostname);
                   11917: 	undef(%hostdom);
                   11918: 	undef(%libserv);
                   11919: 	undef($loaded);
                   11920:     }
1.1       albertel 11921: 
1.852     albertel 11922:     sub load_hosts_tab {
1.869     albertel 11923: 	my ($ignore_cache) = @_;
                   11924: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11925: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11926: 	my @config = <$config>;
                   11927: 	&parse_hosts_tab(\@config);
                   11928: 	close($config);
                   11929: 	$loaded=1;
1.1       albertel 11930:     }
1.852     albertel 11931: 
1.838     albertel 11932:     sub hostname {
1.852     albertel 11933: 	&load_hosts_tab() if (!$loaded);
                   11934: 
1.838     albertel 11935: 	my ($lonid) = @_;
                   11936: 	return $hostname{$lonid};
                   11937:     }
1.845     albertel 11938: 
1.838     albertel 11939:     sub all_hostnames {
1.852     albertel 11940: 	&load_hosts_tab() if (!$loaded);
                   11941: 
1.838     albertel 11942: 	return %hostname;
                   11943:     }
1.845     albertel 11944: 
1.888     albertel 11945:     sub all_names {
                   11946: 	&load_hosts_tab() if (!$loaded);
                   11947: 
                   11948: 	return %name_to_host;
                   11949:     }
                   11950: 
1.974     raeburn  11951:     sub all_host_domain {
                   11952:         &load_hosts_tab() if (!$loaded);
                   11953:         return %hostdom;
                   11954:     }
                   11955: 
1.845     albertel 11956:     sub is_library {
1.852     albertel 11957: 	&load_hosts_tab() if (!$loaded);
                   11958: 
1.845     albertel 11959: 	return exists($libserv{$_[0]});
                   11960:     }
                   11961: 
                   11962:     sub all_library {
1.852     albertel 11963: 	&load_hosts_tab() if (!$loaded);
                   11964: 
1.845     albertel 11965: 	return %libserv;
                   11966:     }
                   11967: 
1.1062    droeschl 11968:     sub unique_library {
                   11969: 	#2x reverse removes all hostnames that appear more than once
                   11970:         my %unique = reverse &all_library();
                   11971:         return reverse %unique;
                   11972:     }
                   11973: 
1.841     albertel 11974:     sub get_servers {
1.852     albertel 11975: 	&load_hosts_tab() if (!$loaded);
                   11976: 
1.841     albertel 11977: 	my ($domain,$type) = @_;
                   11978: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11979: 	                                          : %hostname;
                   11980: 	my %result;
1.842     albertel 11981: 	if (ref($domain) eq 'ARRAY') {
                   11982: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11983: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11984: 		    $result{$host} = $hostname;
                   11985: 		}
                   11986: 	    }
                   11987: 	} else {
                   11988: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11989: 		if ($hostdom{$host} eq $domain) {
                   11990: 		    $result{$host} = $hostname;
                   11991: 		}
1.841     albertel 11992: 	    }
                   11993: 	}
                   11994: 	return %result;
                   11995:     }
1.845     albertel 11996: 
1.1062    droeschl 11997:     sub get_unique_servers {
                   11998:         my %unique = reverse &get_servers(@_);
                   11999: 	return reverse %unique;
                   12000:     }
                   12001: 
1.844     albertel 12002:     sub host_domain {
1.852     albertel 12003: 	&load_hosts_tab() if (!$loaded);
                   12004: 
1.844     albertel 12005: 	my ($lonid) = @_;
                   12006: 	return $hostdom{$lonid};
                   12007:     }
                   12008: 
1.841     albertel 12009:     sub all_domains {
1.852     albertel 12010: 	&load_hosts_tab() if (!$loaded);
                   12011: 
1.841     albertel 12012: 	my %seen;
                   12013: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12014: 	return @uniq;
                   12015:     }
1.1074    raeburn  12016: 
                   12017:     sub internet_dom {
                   12018:         &load_hosts_tab() if (!$loaded);
                   12019: 
                   12020:         my ($lonid) = @_;
                   12021:         return $internetdom{$lonid};
                   12022:     }
1.1107    raeburn  12023: 
                   12024:     sub is_LC_dns {
                   12025:         &load_hosts_tab() if (!$loaded);
                   12026: 
                   12027:         my ($hostname) = @_;
                   12028:         return exists($LC_dns_serv{$hostname});
                   12029:     }
                   12030: 
1.1       albertel 12031: }
                   12032: 
1.847     albertel 12033: { 
                   12034:     my %iphost;
1.856     albertel 12035:     my %name_to_ip;
                   12036:     my %lonid_to_ip;
1.869     albertel 12037: 
1.847     albertel 12038:     sub get_hosts_from_ip {
                   12039: 	my ($ip) = @_;
                   12040: 	my %iphosts = &get_iphost();
                   12041: 	if (ref($iphosts{$ip})) {
                   12042: 	    return @{$iphosts{$ip}};
                   12043: 	}
                   12044: 	return;
1.839     albertel 12045:     }
1.864     albertel 12046:     
                   12047:     sub reset_hosts_ip_info {
                   12048: 	undef(%iphost);
                   12049: 	undef(%name_to_ip);
                   12050: 	undef(%lonid_to_ip);
                   12051:     }
1.856     albertel 12052: 
                   12053:     sub get_host_ip {
                   12054: 	my ($lonid) = @_;
                   12055: 	if (exists($lonid_to_ip{$lonid})) {
                   12056: 	    return $lonid_to_ip{$lonid};
                   12057: 	}
                   12058: 	my $name=&hostname($lonid);
                   12059:    	my $ip = gethostbyname($name);
                   12060: 	return if (!$ip || length($ip) ne 4);
                   12061: 	$ip=inet_ntoa($ip);
                   12062: 	$name_to_ip{$name}   = $ip;
                   12063: 	$lonid_to_ip{$lonid} = $ip;
                   12064: 	return $ip;
                   12065:     }
1.847     albertel 12066:     
                   12067:     sub get_iphost {
1.869     albertel 12068: 	my ($ignore_cache) = @_;
1.894     albertel 12069: 
1.869     albertel 12070: 	if (!$ignore_cache) {
                   12071: 	    if (%iphost) {
                   12072: 		return %iphost;
                   12073: 	    }
                   12074: 	    my ($ip_info,$cached)=
                   12075: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12076: 	    if ($cached) {
                   12077: 		%iphost      = %{$ip_info->[0]};
                   12078: 		%name_to_ip  = %{$ip_info->[1]};
                   12079: 		%lonid_to_ip = %{$ip_info->[2]};
                   12080: 		return %iphost;
                   12081: 	    }
                   12082: 	}
1.894     albertel 12083: 
                   12084: 	# get yesterday's info for fallback
                   12085: 	my %old_name_to_ip;
                   12086: 	my ($ip_info,$cached)=
                   12087: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12088: 	if ($cached) {
                   12089: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12090: 	}
                   12091: 
1.888     albertel 12092: 	my %name_to_host = &all_names();
                   12093: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12094: 	    my $ip;
                   12095: 	    if (!exists($name_to_ip{$name})) {
                   12096: 		$ip = gethostbyname($name);
                   12097: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12098: 		    if (defined($old_name_to_ip{$name})) {
                   12099: 			$ip = $old_name_to_ip{$name};
                   12100: 			&logthis("Can't find $name defaulting to old $ip");
                   12101: 		    } else {
                   12102: 			&logthis("Name $name no IP found");
                   12103: 			next;
                   12104: 		    }
                   12105: 		} else {
                   12106: 		    $ip=inet_ntoa($ip);
1.847     albertel 12107: 		}
                   12108: 		$name_to_ip{$name} = $ip;
                   12109: 	    } else {
                   12110: 		$ip = $name_to_ip{$name};
1.653     albertel 12111: 	    }
1.888     albertel 12112: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12113: 		$lonid_to_ip{$id} = $ip;
                   12114: 	    }
                   12115: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12116: 	}
1.1172.2.23  raeburn  12117: 	&do_cache_new('iphost','iphost',
                   12118: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12119: 		      48*60*60);
1.869     albertel 12120: 
1.847     albertel 12121: 	return %iphost;
1.598     albertel 12122:     }
                   12123: 
1.992     raeburn  12124:     #
                   12125:     #  Given a DNS returns the loncapa host name for that DNS 
                   12126:     # 
                   12127:     sub host_from_dns {
                   12128:         my ($dns) = @_;
                   12129:         my @hosts;
                   12130:         my $ip;
                   12131: 
1.993     raeburn  12132:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12133:             $ip = $name_to_ip{$dns};
                   12134:         }
                   12135:         if (!$ip) {
                   12136:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12137:             if (length($ip) == 4) { 
                   12138: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12139:             }
                   12140:         }
                   12141:         if ($ip) {
                   12142: 	    @hosts = get_hosts_from_ip($ip);
                   12143: 	    return $hosts[0];
                   12144:         }
                   12145:         return undef;
1.986     foxr     12146:     }
1.992     raeburn  12147: 
1.1074    raeburn  12148:     sub get_internet_names {
                   12149:         my ($lonid) = @_;
                   12150:         return if ($lonid eq '');
                   12151:         my ($idnref,$cached)=
                   12152:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12153:         if ($cached) {
                   12154:             return $idnref;
                   12155:         }
                   12156:         my $ip = &get_host_ip($lonid);
                   12157:         my @hosts = &get_hosts_from_ip($ip);
                   12158:         my %iphost = &get_iphost();
                   12159:         my (@idns,%seen);
                   12160:         foreach my $id (@hosts) {
                   12161:             my $dom = &host_domain($id);
                   12162:             my $prim_id = &domain($dom,'primary');
                   12163:             my $prim_ip = &get_host_ip($prim_id);
                   12164:             next if ($seen{$prim_ip});
                   12165:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12166:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12167:                     my $intdom = &internet_dom($id);
                   12168:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12169:                         push(@idns,$intdom);
                   12170:                     }
                   12171:                 }
                   12172:             }
                   12173:             $seen{$prim_ip} = 1;
                   12174:         }
1.1172.2.23  raeburn  12175:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12176:     }
                   12177: 
1.986     foxr     12178: }
                   12179: 
1.1079    raeburn  12180: sub all_loncaparevs {
                   12181:     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);
                   12182: }
                   12183: 
1.1172.2.27  raeburn  12184: # ------------------------------------------------------- Read loncaparev table
                   12185: {
                   12186:     sub load_loncaparevs {
                   12187:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12188:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12189:                 while (my $configline=<$config>) {
                   12190:                     chomp($configline);
                   12191:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12192:                     $loncaparevs{$hostid}=$loncaparev;
                   12193:                 }
                   12194:                 close($config);
                   12195:             }
                   12196:         }
                   12197:     }
                   12198: }
                   12199: 
                   12200: # ----------------------------------------------------- Read serverhostID table
                   12201: {
                   12202:     sub load_serverhomeIDs {
                   12203:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12204:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12205:                 while (my $configline=<$config>) {
                   12206:                     chomp($configline);
                   12207:                     my ($name,$id)=split(/:/,$configline);
                   12208:                     $serverhomeIDs{$name}=$id;
                   12209:                 }
                   12210:                 close($config);
                   12211:             }
                   12212:         }
                   12213:     }
                   12214: }
                   12215: 
                   12216: 
1.862     albertel 12217: BEGIN {
                   12218: 
                   12219: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12220:     unless ($readit) {
                   12221: {
                   12222:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12223:     %perlvar = (%perlvar,%{$configvars});
                   12224: }
                   12225: 
                   12226: 
1.1       albertel 12227: # ------------------------------------------------------ Read spare server file
                   12228: {
1.448     albertel 12229:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12230: 
                   12231:     while (my $configline=<$config>) {
                   12232:        chomp($configline);
1.284     matthew  12233:        if ($configline) {
1.784     albertel 12234: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12235: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12236: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12237:        }
                   12238:     }
1.448     albertel 12239:     close($config);
1.1       albertel 12240: }
1.11      www      12241: # ------------------------------------------------------------ Read permissions
                   12242: {
1.448     albertel 12243:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12244: 
                   12245:     while (my $configline=<$config>) {
1.448     albertel 12246: 	chomp($configline);
                   12247: 	if ($configline) {
                   12248: 	    my ($role,$perm)=split(/ /,$configline);
                   12249: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12250: 	}
1.11      www      12251:     }
1.448     albertel 12252:     close($config);
1.11      www      12253: }
                   12254: 
                   12255: # -------------------------------------------- Read plain texts for permissions
                   12256: {
1.448     albertel 12257:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12258: 
                   12259:     while (my $configline=<$config>) {
1.448     albertel 12260: 	chomp($configline);
                   12261: 	if ($configline) {
1.742     raeburn  12262: 	    my ($short,@plain)=split(/:/,$configline);
                   12263:             %{$prp{$short}} = ();
                   12264: 	    if (@plain > 0) {
                   12265:                 $prp{$short}{'std'} = $plain[0];
                   12266:                 for (my $i=1; $i<@plain; $i++) {
                   12267:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12268:                 }
                   12269:             }
1.448     albertel 12270: 	}
1.135     www      12271:     }
1.448     albertel 12272:     close($config);
1.135     www      12273: }
                   12274: 
                   12275: # ---------------------------------------------------------- Read package table
                   12276: {
1.448     albertel 12277:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12278: 
                   12279:     while (my $configline=<$config>) {
1.483     albertel 12280: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12281: 	chomp($configline);
                   12282: 	my ($short,$plain)=split(/:/,$configline);
                   12283: 	my ($pack,$name)=split(/\&/,$short);
                   12284: 	if ($plain ne '') {
                   12285: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12286: 	    $packagetab{$short}=$plain; 
                   12287: 	}
1.11      www      12288:     }
1.448     albertel 12289:     close($config);
1.329     matthew  12290: }
                   12291: 
1.1172.2.27  raeburn  12292: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12293: 
1.1172.2.27  raeburn  12294: &load_loncaparevs();
                   12295: 
                   12296: # ------------------------------------------------------- Read serverhostID table
                   12297: 
                   12298: &load_serverhomeIDs();
1.1074    raeburn  12299: 
1.1172.2.27  raeburn  12300: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12301: {
                   12302:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12303:     if (-e $file) {
                   12304:         my $parser = HTML::LCParser->new($file);
                   12305:         while (my $token = $parser->get_token()) {
                   12306:             if ($token->[0] eq 'S') {
                   12307:                 my $item = $token->[1];
                   12308:                 my $name = $token->[2]{'name'};
                   12309:                 my $value = $token->[2]{'value'};
                   12310:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12311:                     my $release = $parser->get_text();
                   12312:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12313:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12314:                 }
                   12315:             }
                   12316:         }
                   12317:     }
1.1073    raeburn  12318: }
                   12319: 
1.1138    raeburn  12320: # ---------------------------------------------------------- Read managers table
                   12321: {
                   12322:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12323:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12324:             while (my $configline=<$config>) {
                   12325:                 chomp($configline);
                   12326:                 next if ($configline =~ /^\#/);
                   12327:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12328:                     $managerstab{$configline} = 1;
                   12329:                 }
                   12330:             }
                   12331:             close($config);
                   12332:         }
                   12333:     }
                   12334: }
                   12335: 
1.329     matthew  12336: # ------------- set up temporary directory
                   12337: {
1.1117    foxr     12338:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12339: 
1.11      www      12340: }
                   12341: 
1.794     albertel 12342: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12343: 				'compress_threshold'=> 20_000,
                   12344:  			        });
1.185     www      12345: 
1.281     www      12346: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12347: $dumpcount=0;
1.958     www      12348: $locknum=0;
1.22      www      12349: 
1.163     harris41 12350: &logtouch();
1.672     albertel 12351: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12352: $readit=1;
1.564     albertel 12353:     {
                   12354: 	use integer;
                   12355: 	my $test=(2**32)+1;
1.568     albertel 12356: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12357: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12358:     }
1.1172.2.18  raeburn  12359: 
                   12360:     {
                   12361:         eval {
                   12362:             ($apache) =
                   12363:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12364:         };
                   12365:         if ($@) {
                   12366:            $apache = 1.3;
                   12367:         }
                   12368:     }
                   12369: 
1.195     www      12370: }
1.1       albertel 12371: }
1.179     www      12372: 
1.1       albertel 12373: 1;
1.191     harris41 12374: __END__
                   12375: 
1.243     albertel 12376: =pod
                   12377: 
1.191     harris41 12378: =head1 NAME
                   12379: 
1.243     albertel 12380: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12381: 
                   12382: =head1 SYNOPSIS
                   12383: 
1.243     albertel 12384: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12385: 
                   12386:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12387: 
1.243     albertel 12388: Common parameters:
                   12389: 
                   12390: =over 4
                   12391: 
                   12392: =item *
                   12393: 
                   12394: $uname : an internal username (if $cname expecting a course Id specifically)
                   12395: 
                   12396: =item *
                   12397: 
                   12398: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12399: 
                   12400: =item *
                   12401: 
                   12402: $symb : a resource instance identifier
                   12403: 
                   12404: =item *
                   12405: 
                   12406: $namespace : the name of a .db file that contains the data needed or
                   12407: being set.
                   12408: 
                   12409: =back
                   12410: 
1.394     bowersj2 12411: =head1 OVERVIEW
1.191     harris41 12412: 
1.394     bowersj2 12413: lonnet provides subroutines which interact with the
                   12414: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12415: about classes, users, and resources.
1.243     albertel 12416: 
                   12417: For many of these objects you can also use this to store data about
                   12418: them or modify them in various ways.
1.191     harris41 12419: 
1.394     bowersj2 12420: =head2 Symbs
1.191     harris41 12421: 
1.394     bowersj2 12422: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12423: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12424: map, the resource number of the resource in the map, and the URL of
                   12425: the resource itself. The latter is somewhat redundant, but might help
                   12426: if maps change.
                   12427: 
                   12428: An example is
                   12429: 
                   12430:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12431: 
                   12432: The respective map entry is
                   12433: 
                   12434:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12435:   title="Problem 2">
                   12436:  </resource>
                   12437: 
                   12438: Symbs are used by the random number generator, as well as to store and
                   12439: restore data specific to a certain instance of for example a problem.
                   12440: 
                   12441: =head2 Storing And Retrieving Data
                   12442: 
                   12443: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12444: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12445: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12446: is is the non-critical message twin of cstore. These functions are for
                   12447: handlers to store a perl hash to a user's permanent data space in an
                   12448: easy manner, and to retrieve it again on another call. It is expected
                   12449: that a handler would use this once at the beginning to retrieve data,
                   12450: and then again once at the end to send only the new data back.
                   12451: 
                   12452: The data is stored in the user's data directory on the user's
                   12453: homeserver under the ID of the course.
                   12454: 
                   12455: The hash that is returned by restore will have all of the previous
                   12456: value for all of the elements of the hash.
                   12457: 
                   12458: Example:
                   12459: 
                   12460:  #creating a hash
                   12461:  my %hash;
                   12462:  $hash{'foo'}='bar';
                   12463: 
                   12464:  #storing it
                   12465:  &Apache::lonnet::cstore(\%hash);
                   12466: 
                   12467:  #changing a value
                   12468:  $hash{'foo'}='notbar';
                   12469: 
                   12470:  #adding a new value
                   12471:  $hash{'bar'}='foo';
                   12472:  &Apache::lonnet::cstore(\%hash);
                   12473: 
                   12474:  #retrieving the hash
                   12475:  my %history=&Apache::lonnet::restore();
                   12476: 
                   12477:  #print the hash
                   12478:  foreach my $key (sort(keys(%history))) {
                   12479:    print("\%history{$key} = $history{$key}");
                   12480:  }
                   12481: 
                   12482: Will print out:
1.191     harris41 12483: 
1.394     bowersj2 12484:  %history{1:foo} = bar
                   12485:  %history{1:keys} = foo:timestamp
                   12486:  %history{1:timestamp} = 990455579
                   12487:  %history{2:bar} = foo
                   12488:  %history{2:foo} = notbar
                   12489:  %history{2:keys} = foo:bar:timestamp
                   12490:  %history{2:timestamp} = 990455580
                   12491:  %history{bar} = foo
                   12492:  %history{foo} = notbar
                   12493:  %history{timestamp} = 990455580
                   12494:  %history{version} = 2
                   12495: 
                   12496: Note that the special hash entries C<keys>, C<version> and
                   12497: C<timestamp> were added to the hash. C<version> will be equal to the
                   12498: total number of versions of the data that have been stored. The
                   12499: C<timestamp> attribute will be the UNIX time the hash was
                   12500: stored. C<keys> is available in every historical section to list which
                   12501: keys were added or changed at a specific historical revision of a
                   12502: hash.
                   12503: 
                   12504: B<Warning>: do not store the hash that restore returns directly. This
                   12505: will cause a mess since it will restore the historical keys as if the
                   12506: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12507: 
1.394     bowersj2 12508: Calling convention:
1.191     harris41 12509: 
1.1172.2.27  raeburn  12510:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12511:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12512: 
1.394     bowersj2 12513: For more detailed information, see lonnet specific documentation.
1.191     harris41 12514: 
1.394     bowersj2 12515: =head1 RETURN MESSAGES
1.191     harris41 12516: 
1.394     bowersj2 12517: =over 4
1.191     harris41 12518: 
1.394     bowersj2 12519: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12520: 
1.394     bowersj2 12521: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12522: when the connection is brought back up
1.191     harris41 12523: 
1.394     bowersj2 12524: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12525: for later delivery
1.191     harris41 12526: 
1.967     bisitz   12527: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12528: 
1.394     bowersj2 12529: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12530: that was requested
1.191     harris41 12531: 
1.243     albertel 12532: =back
1.191     harris41 12533: 
1.243     albertel 12534: =head1 PUBLIC SUBROUTINES
1.191     harris41 12535: 
1.243     albertel 12536: =head2 Session Environment Functions
1.191     harris41 12537: 
1.243     albertel 12538: =over 4
1.191     harris41 12539: 
1.394     bowersj2 12540: =item * 
                   12541: X<appenv()>
1.949     raeburn  12542: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12543: the user envirnoment file, and will be restored for each access this
1.620     albertel 12544: user makes during this session, also modifies the %env for the current
1.949     raeburn  12545: process. Optional rolesarrayref - if defined contains a reference to an array
                   12546: of roles which are exempt from the restriction on modifying user.role entries 
                   12547: in the user's environment.db and in %env.    
1.191     harris41 12548: 
                   12549: =item *
1.394     bowersj2 12550: X<delenv()>
1.987     raeburn  12551: B<delenv($delthis,$regexp)>: removes all items from the session
                   12552: environment file that begin with $delthis. If the 
                   12553: optional second arg - $regexp - is true, $delthis is treated as a 
                   12554: regular expression, otherwise \Q$delthis\E is used. 
                   12555: The values are also deleted from the current processes %env.
1.191     harris41 12556: 
1.795     albertel 12557: =item * get_env_multiple($name) 
                   12558: 
                   12559: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12560: values may be defined and end up as an array ref.
                   12561: 
                   12562: returns an array of values
                   12563: 
1.243     albertel 12564: =back
                   12565: 
                   12566: =head2 User Information
1.191     harris41 12567: 
1.243     albertel 12568: =over 4
1.191     harris41 12569: 
                   12570: =item *
1.394     bowersj2 12571: X<queryauthenticate()>
                   12572: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12573: authentication scheme
                   12574: 
                   12575: =item *
1.394     bowersj2 12576: X<authenticate()>
1.1073    raeburn  12577: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12578: authenticate user from domain's lib servers (first use the current
                   12579: one). C<$upass> should be the users password.
1.1073    raeburn  12580: $checkdefauth is optional (value is 1 if a check should be made to
                   12581:    authenticate user using default authentication method, and allow
                   12582:    account creation if username does not have account in the domain).
                   12583: $clientcancheckhost is optional (value is 1 if checking whether the
                   12584:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12585: 
                   12586: =item *
1.394     bowersj2 12587: X<homeserver()>
                   12588: B<homeserver($uname,$udom)>: find the server which has
                   12589: the user's directory and files (there must be only one), this caches
                   12590: the answer, and also caches if there is a borken connection.
1.191     harris41 12591: 
                   12592: =item *
1.394     bowersj2 12593: X<idget()>
                   12594: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12595: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12596: username, and only 1 username per ID in a specific domain) (returns
                   12597: hash: id=>name,id=>name)
1.191     harris41 12598: 
                   12599: =item *
1.394     bowersj2 12600: X<idrget()>
                   12601: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12602: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12603: 
                   12604: =item *
1.394     bowersj2 12605: X<idput()>
                   12606: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12607: 
                   12608: =item *
1.394     bowersj2 12609: X<rolesinit()>
1.1169    droeschl 12610: B<rolesinit($udom,$username)>: get user privileges.
                   12611: returns user role, first access and timer interval hashes
1.243     albertel 12612: 
                   12613: =item *
1.1171    droeschl 12614: X<privileged()>
                   12615: B<privileged($username,$domain)>: returns a true if user has a
                   12616: privileged and active role (i.e. su or dc), false otherwise.
                   12617: 
                   12618: =item *
1.551     albertel 12619: X<getsection()>
                   12620: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12621: course $cname, return section name/number or '' for "not in course"
                   12622: and '-1' for "no section"
                   12623: 
                   12624: =item *
1.394     bowersj2 12625: X<userenvironment()>
                   12626: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12627: passed in @what from the requested user's environment, returns a hash
                   12628: 
1.858     raeburn  12629: =item * 
                   12630: X<userlog_query()>
1.859     albertel 12631: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12632: activity.log file. %filters defines filters applied when parsing the
                   12633: log file. These can be start or end timestamps, or the type of action
                   12634: - log to look for Login or Logout events, check for Checkin or
                   12635: Checkout, role for role selection. The response is in the form
                   12636: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12637: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12638: 
1.243     albertel 12639: =back
                   12640: 
                   12641: =head2 User Roles
                   12642: 
                   12643: =over 4
                   12644: 
                   12645: =item *
                   12646: 
1.810     raeburn  12647: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12648:  F: full access
                   12649:  U,I,K: authentication modes (cxx only)
                   12650:  '': forbidden
                   12651:  1: user needs to choose course
                   12652:  2: browse allowed
1.766     albertel 12653:  A: passphrase authentication needed
1.243     albertel 12654: 
                   12655: =item *
                   12656: 
1.1172.2.13  raeburn  12657: constructaccess($url,$setpriv) : check for access to construction space URL
                   12658: 
                   12659: See if the owner domain and name in the URL match those in the
                   12660: expected environment.  If so, return three element list
                   12661: ($ownername,$ownerdomain,$ownerhome).
                   12662: 
                   12663: Otherwise return the null string.
                   12664: 
                   12665: If second argument 'setpriv' is true, it assigns the privileges,
                   12666: and returns the same three element list, unless the owner has
                   12667: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12668: in which case the null string is returned.
                   12669: 
                   12670: =item *
                   12671: 
1.243     albertel 12672: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12673: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12674: and course level
                   12675: 
                   12676: =item *
                   12677: 
1.988     raeburn  12678: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12679: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12680: $type is Course (default) or Community.
1.988     raeburn  12681: If $forcedefault evaluates to true, text returned will be default 
                   12682: text for $type. Otherwise, if this is a course, the text returned 
                   12683: will be a custom name for the role (if defined in the course's 
                   12684: environment).  If no custom name is defined the default is returned.
                   12685:    
1.832     raeburn  12686: =item *
                   12687: 
1.1172.2.23  raeburn  12688: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12689: All arguments are optional. Returns a hash of a roles, either for
                   12690: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12691: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12692: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12693: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12694: For each key, value is set to colon-separated start and end times for
                   12695: the role.  If no username and domain are specified, will default to
1.934     raeburn  12696: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12697: of role statuses (active, future or previous), roles 
                   12698: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12699: to restrict the list of roles reported. If no array ref is 
                   12700: provided for types, will default to return only active roles.
1.834     albertel 12701: 
1.1172.2.13  raeburn  12702: =item *
                   12703: 
                   12704: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12705: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12706: 
                   12707: Additional optional arguments are: $type (if role checking is to be restricted
                   12708: to certain user status types -- previous (expired roles), active (currently
                   12709: available roles) or future (roles available in the future), and
                   12710: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12711: have active Domain Coordinator role in course's domain or in additional
                   12712: domains (specified in 'Domains to check for privileged users' in course
                   12713: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12714: 
                   12715: =item *
                   12716: 
                   12717: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12718: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12719: $possdomains and $possroles are optional array refs -- to domains to check and
                   12720: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12721: users' roles.db to check for a dc or su role in any domain. This can be
                   12722: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12723: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12724: this then allows &privileged_by_domain() to be used, which caches the identity
                   12725: of privileged users, eliminating the need for repeated calls to &dump().
                   12726: 
                   12727: =item *
                   12728: 
                   12729: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12730: where the outer hash keys are domains specified in the $possdomains array ref,
                   12731: next inner hash keys are privileged roles specified in the $roles array ref,
                   12732: and the innermost hash contains key = value pairs for username:domain = end:start
                   12733: for active or future "privileged" users with that role in that domain. To avoid
                   12734: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12735: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12736: 
1.243     albertel 12737: =back
                   12738: 
                   12739: =head2 User Modification
                   12740: 
                   12741: =over 4
                   12742: 
                   12743: =item *
                   12744: 
1.957     raeburn  12745: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12746: user for the level given by URL.  Optional start and end dates (leave empty
                   12747: string or zero for "no date")
1.191     harris41 12748: 
                   12749: =item *
                   12750: 
1.243     albertel 12751: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12752: change a users, password, possible return values are: ok,
                   12753: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12754: refused
1.191     harris41 12755: 
                   12756: =item *
                   12757: 
1.243     albertel 12758: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12759: 
                   12760: =item *
                   12761: 
1.1058    raeburn  12762: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12763:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12764: 
                   12765: will update user information (firstname,middlename,lastname,generation,
                   12766: permanentemail), and if forceid is true, student/employee ID also.
                   12767: A user's institutional affiliation(s) can also be updated.
                   12768: User information fields will not be overwritten with empty entries 
                   12769: unless the field is included in the $candelete array reference.
                   12770: This array is included when a single user is modified via "Manage Users",
                   12771: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12772: 
                   12773: =item *
                   12774: 
1.286     matthew  12775: modifystudent
                   12776: 
1.957     raeburn  12777: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12778: The course id is resolved based on the current user's environment.  
                   12779: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12780: associated with a course.
                   12781: 
1.297     matthew  12782: This call is essentially a wrapper for lonnet::modifyuser and
                   12783: lonnet::modify_student_enrollment
1.286     matthew  12784: 
                   12785: Inputs: 
                   12786: 
                   12787: =over 4
                   12788: 
1.957     raeburn  12789: =item B<$udom> Student's loncapa domain
1.286     matthew  12790: 
1.957     raeburn  12791: =item B<$uname> Student's loncapa login name
1.286     matthew  12792: 
1.964     bisitz   12793: =item B<$uid> Student/Employee ID
1.286     matthew  12794: 
1.957     raeburn  12795: =item B<$umode> Student's authentication mode
1.286     matthew  12796: 
1.957     raeburn  12797: =item B<$upass> Student's password
1.286     matthew  12798: 
1.957     raeburn  12799: =item B<$first> Student's first name
1.286     matthew  12800: 
1.957     raeburn  12801: =item B<$middle> Student's middle name
1.286     matthew  12802: 
1.957     raeburn  12803: =item B<$last> Student's last name
1.286     matthew  12804: 
1.957     raeburn  12805: =item B<$gene> Student's generation
1.286     matthew  12806: 
1.957     raeburn  12807: =item B<$usec> Student's section in course
1.286     matthew  12808: 
                   12809: =item B<$end> Unix time of the roles expiration
                   12810: 
                   12811: =item B<$start> Unix time of the roles start date
                   12812: 
                   12813: =item B<$forceid> If defined, allow $uid to be changed
                   12814: 
                   12815: =item B<$desiredhome> server to use as home server for student
                   12816: 
1.957     raeburn  12817: =item B<$email> Student's permanent e-mail address
                   12818: 
                   12819: =item B<$type> Type of enrollment (auto or manual)
                   12820: 
1.963     raeburn  12821: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12822: 
                   12823: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12824: 
1.963     raeburn  12825: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12826: 
1.963     raeburn  12827: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12828: 
1.1172.2.19  raeburn  12829: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12830: 
                   12831: =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  12832: 
1.286     matthew  12833: =back
1.297     matthew  12834: 
                   12835: =item *
                   12836: 
                   12837: modify_student_enrollment
                   12838: 
1.1172.2.31  raeburn  12839: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12840: 'role.request.course' must be defined for this function to proceed.
                   12841: 
                   12842: Inputs:
                   12843: 
                   12844: =over 4
                   12845: 
1.1172.2.31  raeburn  12846: =item $udom, student's domain
1.297     matthew  12847: 
1.1172.2.31  raeburn  12848: =item $uname, student's name
1.297     matthew  12849: 
1.1172.2.31  raeburn  12850: =item $uid, student's user id
1.297     matthew  12851: 
1.1172.2.31  raeburn  12852: =item $first, student's first name
1.297     matthew  12853: 
                   12854: =item $middle
                   12855: 
                   12856: =item $last
                   12857: 
                   12858: =item $gene
                   12859: 
                   12860: =item $usec
                   12861: 
                   12862: =item $end
                   12863: 
                   12864: =item $start
                   12865: 
1.957     raeburn  12866: =item $type
                   12867: 
                   12868: =item $locktype
                   12869: 
                   12870: =item $cid
                   12871: 
                   12872: =item $selfenroll
                   12873: 
                   12874: =item $context
                   12875: 
1.1172.2.19  raeburn  12876: =item $credits, number of credits student will earn from this class
                   12877: 
1.297     matthew  12878: =back
                   12879: 
1.191     harris41 12880: 
                   12881: =item *
                   12882: 
1.243     albertel 12883: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12884: custom role; give a custom role to a user for the level given by URL.  Specify
                   12885: name and domain of role author, and role name
1.191     harris41 12886: 
                   12887: =item *
                   12888: 
1.243     albertel 12889: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12890: 
                   12891: =item *
                   12892: 
1.243     albertel 12893: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12894: 
                   12895: =back
                   12896: 
                   12897: =head2 Course Infomation
                   12898: 
                   12899: =over 4
1.191     harris41 12900: 
                   12901: =item *
                   12902: 
1.1118    foxr     12903: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12904: specified course id, including all environment settings for the
                   12905: course, the description of the course will be in the hash under the
                   12906: key 'description'
1.191     harris41 12907: 
1.1118    foxr     12908: $options is an optional parameter that if supplied is a hash reference that controls
                   12909: what how this function works.  It has the following key/values:
                   12910: 
                   12911: =over 4
                   12912: 
                   12913: =item freshen_cache
                   12914: 
                   12915: If defined, and the environment cache for the course is valid, it is 
                   12916: returned in the returned hash.
                   12917: 
                   12918: =item one_time
                   12919: 
                   12920: If defined, the last cache time is set to _now_
                   12921: 
                   12922: =item user
                   12923: 
                   12924: If defined, the supplied username is used instead of the current user.
                   12925: 
                   12926: 
                   12927: =back
                   12928: 
1.191     harris41 12929: =item *
                   12930: 
1.624     albertel 12931: resdata($name,$domain,$type,@which) : request for current parameter
                   12932: setting for a specific $type, where $type is either 'course' or 'user',
                   12933: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  12934: answers for 10 minutes.
1.243     albertel 12935: 
1.877     foxr     12936: =item *
                   12937: 
                   12938: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12939: data base, returning a hash that is keyed by the resource name and has
                   12940: values that are the resource value.  I believe that the timestamps and
                   12941: versions are also returned.
                   12942: 
1.1172.2.31  raeburn  12943: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12944: supplemental content area. This routine caches the number of files for
                   12945: 10 minutes.
                   12946: 
1.243     albertel 12947: =back
                   12948: 
                   12949: =head2 Course Modification
                   12950: 
                   12951: =over 4
1.191     harris41 12952: 
                   12953: =item *
                   12954: 
1.243     albertel 12955: writecoursepref($courseid,%prefs) : write preferences (environment
                   12956: database) for a course
1.191     harris41 12957: 
                   12958: =item *
                   12959: 
1.1011    raeburn  12960: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12961: 
                   12962: =item *
                   12963: 
1.1038    raeburn  12964: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12965: 
1.1167    droeschl 12966: =item *
                   12967: 
                   12968: is_course($courseid), is_course($cdom, $cnum)
                   12969: 
                   12970: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12971: two component version $cdom, $cnum. It checks if the specified course exists.
                   12972: 
                   12973: Returns:
                   12974:     undef if the course doesn't exist, otherwise
                   12975:     in scalar context the combined courseid.
                   12976:     in list context the two components of the course identifier, domain and 
                   12977:     courseid.    
                   12978: 
1.243     albertel 12979: =back
                   12980: 
                   12981: =head2 Resource Subroutines
                   12982: 
                   12983: =over 4
1.191     harris41 12984: 
                   12985: =item *
                   12986: 
1.243     albertel 12987: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12988: 
                   12989: =item *
                   12990: 
1.243     albertel 12991: repcopy($filename) : subscribes to the requested file, and attempts to
                   12992: replicate from the owning library server, Might return
1.607     raeburn  12993: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12994: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12995: resource. Expects the local filesystem pathname
                   12996: (/home/httpd/html/res/....)
                   12997: 
                   12998: =back
                   12999: 
                   13000: =head2 Resource Information
                   13001: 
                   13002: =over 4
1.191     harris41 13003: 
                   13004: =item *
                   13005: 
1.1172.2.28  raeburn  13006: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13007: and returns the value of a variety of different possible values,
                   13008: $varname should be a request string, and the other parameters can be
                   13009: used to specify who and what one is asking about. Ordinarily, $cid 
                   13010: does not need to be specified, as it is retrived from 
                   13011: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13012: within lonuserstate::loadmap() when initializing a course, before
                   13013: $env{'request.course.id'} has been set, so it needs to be provided
                   13014: in that one case.
1.243     albertel 13015: 
                   13016: Possible values for $varname are environment.lastname (or other item
                   13017: from the envirnment hash), user.name (or someother aspect about the
                   13018: user), resource.0.maxtries (or some other part and parameter of a
                   13019: resource)
1.204     albertel 13020: 
                   13021: =item *
                   13022: 
1.243     albertel 13023: directcondval($number) : get current value of a condition; reads from a state
                   13024: string
1.204     albertel 13025: 
                   13026: =item *
                   13027: 
1.243     albertel 13028: condval($condidx) : value of condition index based on state
1.204     albertel 13029: 
                   13030: =item *
                   13031: 
1.243     albertel 13032: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13033: resource's metadata, $what should be either a specific key, or either
                   13034: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13035: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13036: 
                   13037: this function automatically caches all requests
1.191     harris41 13038: 
                   13039: =item *
                   13040: 
1.243     albertel 13041: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13042: network of library servers; returns file handle of where SQL and regex results
                   13043: will be stored for query
1.191     harris41 13044: 
                   13045: =item *
                   13046: 
1.243     albertel 13047: symbread($filename) : return symbolic list entry (filename argument optional);
                   13048: returns the data handle
1.191     harris41 13049: 
                   13050: =item *
                   13051: 
1.1172.2.17  raeburn  13052: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13053: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13054: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13055: on failure, user must be in a course, as it assumes the existence of
                   13056: the course initial hash, and uses $env('request.course.id'}.  The third
                   13057: arg is an optional reference to a scalar.  If this arg is passed in the
                   13058: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13059: encrypted; otherwise it will be null.
1.243     albertel 13060: 
1.191     harris41 13061: =item *
                   13062: 
1.243     albertel 13063: symbclean($symb) : removes versions numbers from a symb, returns the
                   13064: cleaned symb
1.191     harris41 13065: 
                   13066: =item *
                   13067: 
1.243     albertel 13068: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13069: course map, user must be in a course for it to work.
1.191     harris41 13070: 
                   13071: =item *
                   13072: 
1.243     albertel 13073: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13074: 
                   13075: =item *
                   13076: 
1.243     albertel 13077: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13078: a random seed, all arguments are optional, if they aren't sent it uses the
                   13079: environment to derive them. Note: if symb isn't sent and it can't get one
                   13080: from &symbread it will use the current time as its return value
1.191     harris41 13081: 
                   13082: =item *
                   13083: 
1.243     albertel 13084: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13085: unfakeable, receipt
1.191     harris41 13086: 
                   13087: =item *
                   13088: 
1.620     albertel 13089: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.243     albertel 13093: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13094: 
                   13095: =item *
                   13096: 
1.243     albertel 13097: 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 13098: 
                   13099: =item *
                   13100: 
1.243     albertel 13101: 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 13102: 
                   13103: =item *
                   13104: 
1.243     albertel 13105: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13106: 
                   13107: =item *
                   13108: 
1.243     albertel 13109: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13110: forcing spreadsheet to reevaluate the resource scores next time.
                   13111: 
1.1172.2.13  raeburn  13112: =item *
                   13113: 
                   13114: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13115: when viewing in course context.
                   13116: 
                   13117:  input: six args -- filename (decluttered), course number, course domain,
                   13118:                     url, symb (if registered) and group (if this is a
                   13119:                     group item -- e.g., bulletin board, group page etc.).
                   13120: 
                   13121:  output: array of five scalars --
                   13122:          $cfile -- url for file editing if editable on current server
                   13123:          $home -- homeserver of resource (i.e., for author if published,
                   13124:                                           or course if uploaded.).
                   13125:          $switchserver --  1 if server switch will be needed.
                   13126:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13127:          $forceview -- 1 if icon/link should be to go to view mode
                   13128: 
                   13129: =item *
                   13130: 
                   13131: is_course_upload($file,$cnum,$cdom)
                   13132: 
                   13133: Used in course context to determine if current file was uploaded to
                   13134: the course (i.e., would be found in /userfiles/docs on the course's
                   13135: homeserver.
                   13136: 
                   13137:   input: 3 args -- filename (decluttered), course number and course domain.
                   13138:   output: boolean -- 1 if file was uploaded.
                   13139: 
1.243     albertel 13140: =back
                   13141: 
                   13142: =head2 Storing/Retreiving Data
                   13143: 
                   13144: =over 4
1.191     harris41 13145: 
                   13146: =item *
                   13147: 
1.243     albertel 13148: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13149: for this url; hashref needs to be given and should be a \%hashname; the
                   13150: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13151: be derived from the env
1.191     harris41 13152: 
                   13153: =item *
                   13154: 
1.243     albertel 13155: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13156: uses critical subroutine
1.191     harris41 13157: 
                   13158: =item *
                   13159: 
1.243     albertel 13160: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13161: all args are optional
1.191     harris41 13162: 
                   13163: =item *
                   13164: 
1.717     albertel 13165: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13166: dumps the complete (or key matching regexp) namespace into a hash
                   13167: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13168: normally &store()ed into
                   13169: 
                   13170: $range should be either an integer '100' (give me the first 100
                   13171:                                            matching records)
                   13172:               or be  two integers sperated by a - with no spaces
                   13173:                  '30-50' (give me the 30th through the 50th matching
                   13174:                           records)
                   13175: 
                   13176: 
                   13177: =item *
                   13178: 
                   13179: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13180: replaces a &store() version of data with a replacement set of data
                   13181: for a particular resource in a namespace passed in the $storehash hash 
                   13182: reference
                   13183: 
                   13184: =item *
                   13185: 
1.243     albertel 13186: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13187: works very similar to store/cstore, but all data is stored in a
                   13188: temporary location and can be reset using tmpreset, $storehash should
                   13189: be a hash reference, returns nothing on success
1.191     harris41 13190: 
                   13191: =item *
                   13192: 
1.243     albertel 13193: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13194: similar to restore, but all data is stored in a temporary location and
                   13195: can be reset using tmpreset. Returns a hash of values on success,
                   13196: error string otherwise.
1.191     harris41 13197: 
                   13198: =item *
                   13199: 
1.243     albertel 13200: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13201: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13202: 
                   13203: =item *
                   13204: 
1.243     albertel 13205: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13206: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13207: 
                   13208: =item *
                   13209: 
1.243     albertel 13210: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13211: namesp ($udom and $uname are optional)
1.191     harris41 13212: 
                   13213: =item *
                   13214: 
1.702     albertel 13215: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13216: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13217: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13218: 
1.702     albertel 13219: $range should be either an integer '100' (give me the first 100
                   13220:                                            matching records)
                   13221:               or be  two integers sperated by a - with no spaces
                   13222:                  '30-50' (give me the 30th through the 50th matching
                   13223:                           records)
1.449     matthew  13224: =item *
                   13225: 
                   13226: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13227: $store can be a scalar, an array reference, or if the amount to be 
                   13228: incremented is > 1, a hash reference.
                   13229: 
                   13230: ($udom and $uname are optional)
1.191     harris41 13231: 
                   13232: =item *
                   13233: 
1.243     albertel 13234: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13235: ($udom and $uname are optional)
1.191     harris41 13236: 
                   13237: =item *
                   13238: 
1.243     albertel 13239: cput($namespace,$storehash,$udom,$uname) : critical put
                   13240: ($udom and $uname are optional)
1.191     harris41 13241: 
                   13242: =item *
                   13243: 
1.748     albertel 13244: newput($namespace,$storehash,$udom,$uname) :
                   13245: 
                   13246: Attempts to store the items in the $storehash, but only if they don't
                   13247: currently exist, if this succeeds you can be certain that you have 
                   13248: successfully created a new key value pair in the $namespace db.
                   13249: 
                   13250: 
                   13251: Args:
                   13252:  $namespace: name of database to store values to
                   13253:  $storehash: hashref to store to the db
                   13254:  $udom: (optional) domain of user containing the db
                   13255:  $uname: (optional) name of user caontaining the db
                   13256: 
                   13257: Returns:
                   13258:  'ok' -> succeeded in storing all keys of $storehash
                   13259:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13260:                         least <key> already existed in the db (other
                   13261:                         requested keys may also already exist)
1.967     bisitz   13262:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13263:  'con_lost' -> unable to contact request server
                   13264:  'refused' -> action was not allowed by remote machine
                   13265: 
                   13266: 
                   13267: =item *
                   13268: 
1.243     albertel 13269: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13270: reference filled in from namesp (encrypts the return communication)
                   13271: ($udom and $uname are optional)
1.191     harris41 13272: 
                   13273: =item *
                   13274: 
1.243     albertel 13275: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13276: critical subroutine
                   13277: 
1.806     raeburn  13278: =item *
                   13279: 
1.860     raeburn  13280: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13281: array reference filled in from namespace found in domain level on either
                   13282: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13283: 
                   13284: =item *
                   13285: 
1.860     raeburn  13286: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13287: domain level either on specified domain server ($uhome) or primary domain 
                   13288: server ($udom and $uhome are optional)
1.806     raeburn  13289: 
1.943     raeburn  13290: =item * 
                   13291: 
                   13292: get_domain_defaults($target_domain) : returns hash with defaults for
                   13293: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13294: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13295: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13296: Values are retrieved from cache (if current), or from domain's configuration.db
                   13297: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13298: or lonTabs/domain.tab. 
                   13299: 
                   13300: %domdefaults = &get_auth_defaults($target_domain);
                   13301: 
1.243     albertel 13302: =back
                   13303: 
                   13304: =head2 Network Status Functions
                   13305: 
                   13306: =over 4
1.191     harris41 13307: 
                   13308: =item *
                   13309: 
1.1137    raeburn  13310: dirlist() : return directory list based on URI (first arg).
                   13311: 
                   13312: Inputs: 1 required, 5 optional.
                   13313: 
                   13314: =over
                   13315: 
                   13316: =item 
                   13317: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13318: 
                   13319: =item
                   13320: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13321: 
                   13322: =item
                   13323: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13324: 
                   13325: =item
                   13326: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13327: 
                   13328: =item
                   13329: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13330: 
                   13331: =item 
                   13332: $alternateRoot - path to prepend in place of path from $uri.
                   13333: 
                   13334: =back
                   13335: 
                   13336: Returns: Array of up to two items.
                   13337: 
                   13338: =over
                   13339: 
                   13340: a reference to an array of files/subdirectories
                   13341: 
                   13342: =over
                   13343: 
                   13344: Each element in the array of files/subdirectories is a & separated list of
                   13345: item name and the result of running stat on the item.  If dirlist was requested
                   13346: for a file instead of a directory, the item name will be ''. For a directory 
                   13347: listing, if the item is a metadata file, the element will end &N&M 
                   13348: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13349: default copyright set (1).  
                   13350: 
                   13351: =back
                   13352: 
                   13353: a scalar containing error condition (if encountered).
                   13354: 
                   13355: =over
                   13356: 
                   13357: =item 
                   13358: no_host (no homeserver identified for $username:$domain).
                   13359: 
                   13360: =item 
                   13361: no_such_host (server contacted for listing not identified as valid host).
                   13362: 
                   13363: =item 
                   13364: con_lost (connection to remote server failed).
                   13365: 
                   13366: =item 
                   13367: refused (invalid $username:$domain received on lond side).
                   13368: 
                   13369: =item 
                   13370: no_such_dir (directory at specified path on lond side does not exist). 
                   13371: 
                   13372: =item 
                   13373: empty (directory at specified path on lond side is empty).
                   13374: 
                   13375: =over
                   13376: 
                   13377: This is currently not encountered because the &ls3, &ls2, 
                   13378: &ls (_handler) routines on the lond side do not filter out
                   13379: . and .. from a directory listing. 
                   13380: 
                   13381: =back
                   13382: 
                   13383: =back
                   13384: 
                   13385: =back
1.191     harris41 13386: 
                   13387: =item *
                   13388: 
1.243     albertel 13389: spareserver() : find server with least workload from spare.tab
                   13390: 
1.986     foxr     13391: 
                   13392: =item *
                   13393: 
                   13394: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13395: if there is no corresponding loncapa host.
                   13396: 
1.243     albertel 13397: =back
                   13398: 
1.986     foxr     13399: 
1.243     albertel 13400: =head2 Apache Request
                   13401: 
                   13402: =over 4
1.191     harris41 13403: 
                   13404: =item *
                   13405: 
1.243     albertel 13406: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13407: localhost, posts hash
                   13408: 
                   13409: =back
                   13410: 
                   13411: =head2 Data to String to Data
                   13412: 
                   13413: =over 4
1.191     harris41 13414: 
                   13415: =item *
                   13416: 
1.243     albertel 13417: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13418: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13419: 
                   13420: =item *
                   13421: 
1.243     albertel 13422: hashref2str($hashref) : convert a hashref into a string complete with
                   13423: escaping and '=' and '&' separators, supports elements that are
                   13424: arrayrefs and hashrefs
1.191     harris41 13425: 
                   13426: =item *
                   13427: 
1.243     albertel 13428: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13429: with escaping and '&' separators, supports elements that are arrayrefs
                   13430: and hashrefs
1.191     harris41 13431: 
                   13432: =item *
                   13433: 
1.243     albertel 13434: str2hash($string) : convert string to hash using unescaping and
                   13435: splitting on '=' and '&', supports elements that are arrayrefs and
                   13436: hashrefs
1.191     harris41 13437: 
                   13438: =item *
                   13439: 
1.243     albertel 13440: str2array($string) : convert string to hash using unescaping and
                   13441: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13442: 
                   13443: =back
                   13444: 
                   13445: =head2 Logging Routines
                   13446: 
                   13447: 
                   13448: These routines allow one to make log messages in the lonnet.log and
                   13449: lonnet.perm logfiles.
1.191     harris41 13450: 
1.1119    foxr     13451: =over 4
                   13452: 
1.191     harris41 13453: =item *
                   13454: 
1.243     albertel 13455: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13456: 
                   13457: =item *
                   13458: 
1.243     albertel 13459: logthis() : append message to the normal lonnet.log file, it gets
                   13460: preiodically rolled over and deleted.
1.191     harris41 13461: 
                   13462: =item *
                   13463: 
1.243     albertel 13464: logperm() : append a permanent message to lonnet.perm.log, this log
                   13465: file never gets deleted by any automated portion of the system, only
                   13466: messages of critical importance should go in here.
                   13467: 
1.1119    foxr     13468: 
1.243     albertel 13469: =back
                   13470: 
                   13471: =head2 General File Helper Routines
                   13472: 
                   13473: =over 4
1.191     harris41 13474: 
                   13475: =item *
                   13476: 
1.481     raeburn  13477: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13478: (a) files in /uploaded
                   13479:   (i) If a local copy of the file exists - 
                   13480:       compares modification date of local copy with last-modified date for 
                   13481:       definitive version stored on home server for course. If local copy is 
                   13482:       stale, requests a new version from the home server and stores it. 
                   13483:       If the original has been removed from the home server, then local copy 
                   13484:       is unlinked.
                   13485:   (ii) If local copy does not exist -
                   13486:       requests the file from the home server and stores it. 
                   13487:   
                   13488:   If $caller is 'uploadrep':  
                   13489:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13490:     for request for files originally uploaded via DOCS. 
                   13491:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13492:   
                   13493:   Otherwise:
                   13494:      This indicates a call from the content generation phase of the request.
                   13495:      -  returns the entire contents of the file or -1.
                   13496:      
                   13497: (b) files in /res
                   13498:    - returns the entire contents of a file or -1; 
                   13499:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13500: 
1.712     albertel 13501: 
                   13502: =item *
                   13503: 
                   13504: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13505:                   reference
                   13506: 
                   13507: returns either a stat() list of data about the file or an empty list
                   13508: if the file doesn't exist or couldn't find out about it (connection
                   13509: problems or user unknown)
                   13510: 
1.191     harris41 13511: =item *
                   13512: 
1.243     albertel 13513: filelocation($dir,$file) : returns file system location of a file
                   13514: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13515: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13516: and a file of ../bob will become /a/bob)
1.191     harris41 13517: 
                   13518: =item *
                   13519: 
                   13520: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13521: filelocation except for hrefs
                   13522: 
                   13523: =item *
                   13524: 
                   13525: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13526: 
1.243     albertel 13527: =back
                   13528: 
1.608     albertel 13529: =head2 Usererfile file routines (/uploaded*)
                   13530: 
                   13531: =over 4
                   13532: 
                   13533: =item *
                   13534: 
                   13535: userfileupload(): main rotine for putting a file in a user or course's
                   13536:                   filespace, arguments are,
                   13537: 
1.620     albertel 13538:  formname - required - this is the name of the element in $env where the
1.608     albertel 13539:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13540:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13541:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13542:  context - if coursedoc, store the file in the course of the active role
                   13543:              of the current user; 
                   13544:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13545:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13546:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13547:          if undefined, it will be placed in "unknown"
                   13548: 
                   13549:  (This routine calls clean_filename() to remove any dangerous
                   13550:  characters from the filename, and then calls finuserfileupload() to
                   13551:  complete the transaction)
                   13552: 
                   13553:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13554:  and /adm/notfound.html if unsuccessful
                   13555: 
                   13556: =item *
                   13557: 
                   13558: clean_filename(): routine for cleaing a filename up for storage in
                   13559:                  userfile space, argument is:
                   13560: 
                   13561:  filename - proposed filename
                   13562: 
                   13563: returns: the new clean filename
                   13564: 
                   13565: =item *
                   13566: 
1.1090    raeburn  13567: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13568: userspace, probably shouldn't be called directly
                   13569: 
                   13570:   docuname: username or courseid of destination for the file
                   13571:   docudom: domain of user/course of destination for the file
                   13572:   formname: same as for userfileupload()
1.1090    raeburn  13573:   fname: filename (including subdirectories) for the file
                   13574:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13575:   allfiles: reference to hash used to store objects found by parser
                   13576:   codebase: reference to hash used for codebases of java objects found by parser
                   13577:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13578:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13579:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13580:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13581:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13582:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13583:   mimetype: reference to scalar to accommodate mime type determined
                   13584:             from File::MMagic if $parser = parse.
1.608     albertel 13585: 
                   13586:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13587:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13588:  was 'overwrite').
                   13589:  
1.608     albertel 13590: 
                   13591: =item *
                   13592: 
                   13593: renameuserfile(): renames an existing userfile to a new name
                   13594: 
                   13595:   Args:
                   13596:    docuname: username or courseid of destination for the file
                   13597:    docudom: domain of user/course of destination for the file
                   13598:    old: current file name (including any subdirs under userfiles)
                   13599:    new: desired file name (including any subdirs under userfiles)
                   13600: 
                   13601: =item *
                   13602: 
                   13603: mkdiruserfile(): creates a directory is a userfiles dir
                   13604: 
                   13605:   Args:
                   13606:    docuname: username or courseid of destination for the file
                   13607:    docudom: domain of user/course of destination for the file
                   13608:    dir: dir to create (including any subdirs under userfiles)
                   13609: 
                   13610: =item *
                   13611: 
                   13612: removeuserfile(): removes a file that exists in userfiles
                   13613: 
                   13614:   Args:
                   13615:    docuname: username or courseid of destination for the file
                   13616:    docudom: domain of user/course of destination for the file
                   13617:    fname: filname to delete (including any subdirs under userfiles)
                   13618: 
                   13619: =item *
                   13620: 
                   13621: removeuploadedurl(): convience function for removeuserfile()
                   13622: 
                   13623:   Args:
                   13624:    url:  a full /uploaded/... url to delete
                   13625: 
1.747     albertel 13626: =item * 
                   13627: 
                   13628: get_portfile_permissions():
                   13629:   Args:
                   13630:     domain: domain of user or course contain the portfolio files
                   13631:     user: name of user or num of course contain the portfolio files
                   13632:   Returns:
                   13633:     hashref of a dump of the proper file_permissions.db
                   13634:    
                   13635: 
                   13636: =item * 
                   13637: 
                   13638: get_access_controls():
                   13639: 
                   13640: Args:
                   13641:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13642:   group: (optional) the group you want the files associated with
                   13643:   file: (optional) the file you want access info on
                   13644: 
                   13645: Returns:
1.749     raeburn  13646:     a hash (keys are file names) of hashes containing
                   13647:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13648:         values are XML containing access control settings (see below) 
1.747     albertel 13649: 
                   13650: Internal notes:
                   13651: 
1.749     raeburn  13652:  access controls are stored in file_permissions.db as key=value pairs.
                   13653:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13654:         where scope -> public,guest,course,group,domains or users.
                   13655:               end -> UNIX time for end of access (0 -> no end date)
                   13656:               start -> UNIX time for start of access
                   13657: 
                   13658:     value -> XML description of access control
                   13659:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13660:             <start></start>
                   13661:             <end></end>
                   13662: 
                   13663:             <password></password>  for scope type = guest
                   13664: 
                   13665:             <domain></domain>     for scope type = course or group
                   13666:             <number></number>
                   13667:             <roles id="">
                   13668:              <role></role>
                   13669:              <access></access>
                   13670:              <section></section>
                   13671:              <group></group>
                   13672:             </roles>
                   13673: 
                   13674:             <dom></dom>         for scope type = domains
                   13675: 
                   13676:             <users>             for scope type = users
                   13677:              <user>
                   13678:               <uname></uname>
                   13679:               <udom></udom>
                   13680:              </user>
                   13681:             </users>
                   13682:            </scope> 
                   13683:               
                   13684:  Access data is also aggregated for each file in an additional key=value pair:
                   13685:  key -> path to file/file_name\0accesscontrol 
                   13686:  value -> reference to hash
                   13687:           hash contains key = value pairs
                   13688:           where key = uniqueID:scope_end_start
                   13689:                 value = UNIX time record was last updated
                   13690: 
                   13691:           Used to improve speed of look-ups of access controls for each file.  
                   13692:  
                   13693:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13694: 
1.1172.2.13  raeburn  13695: =item *
                   13696: 
1.749     raeburn  13697: modify_access_controls():
                   13698: 
                   13699: Modifies access controls for a portfolio file
                   13700: Args
                   13701: 1. file name
                   13702: 2. reference to hash of required changes,
                   13703: 3. domain
                   13704: 4. username
                   13705:   where domain,username are the domain of the portfolio owner 
                   13706:   (either a user or a course) 
                   13707: 
                   13708: Returns:
                   13709: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13710: 2. result of deletions ('ok' or 'error', with error message).
                   13711: 3. reference to hash of any new or updated access controls.
                   13712: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13713:    key = integer (inbound ID)
1.1172.2.13  raeburn  13714:    value = uniqueID
                   13715: 
                   13716: =item *
                   13717: 
                   13718: get_timebased_id():
                   13719: 
                   13720: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13721: course via the Course Editor (e.g., folders, composite pages,
                   13722: group bulletin boards).
                   13723: 
                   13724: Args: (first three required; six others optional)
                   13725: 
                   13726: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13727:    docssequence, or name of group
                   13728: 
                   13729: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13730:    e.g., num, boardids
                   13731: 
                   13732: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13733:    file will be named nohist_namespace.db
                   13734: 
                   13735: 4. cdom: domain of course; default is current course domain from %env
                   13736: 
                   13737: 5. cnum: course number; default is current course number from %env
                   13738: 
                   13739: 6. idtype: set to concat if an additional digit is to be appended to the
                   13740:    unix timestamp to form the suffix, if the plain timestamp is already
                   13741:    in use.  Default is to not do this, but simply increment the unix
                   13742:    timestamp by 1 until a unique key is obtained.
                   13743: 
                   13744: 7. who: holder of locking key; defaults to user:domain for user.
                   13745: 
                   13746: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13747:    retrying); default is 3.
                   13748: 
                   13749: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13750: 
                   13751: Returns:
                   13752: 
                   13753: 1. suffix obtained (numeric)
                   13754: 
                   13755: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13756: 
                   13757: 3. error: contains (localized) error message if an error occurred.
                   13758: 
1.747     albertel 13759: 
1.608     albertel 13760: =back
                   13761: 
1.243     albertel 13762: =head2 HTTP Helper Routines
                   13763: 
                   13764: =over 4
                   13765: 
1.191     harris41 13766: =item *
                   13767: 
                   13768: escape() : unpack non-word characters into CGI-compatible hex codes
                   13769: 
                   13770: =item *
                   13771: 
                   13772: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13773: 
1.243     albertel 13774: =back
                   13775: 
                   13776: =head1 PRIVATE SUBROUTINES
                   13777: 
                   13778: =head2 Underlying communication routines (Shouldn't call)
                   13779: 
                   13780: =over 4
                   13781: 
                   13782: =item *
                   13783: 
                   13784: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13785: 
                   13786: =item *
                   13787: 
                   13788: reply() : uses subreply to send a message to remote machine, logs all failures
                   13789: 
                   13790: =item *
                   13791: 
                   13792: critical() : passes a critical message to another server; if cannot
                   13793: get through then place message in connection buffer directory and
                   13794: returns con_delayed, if incapable of saving message, returns
                   13795: con_failed
                   13796: 
                   13797: =item *
                   13798: 
                   13799: reconlonc() : tries to reconnect lonc client processes.
                   13800: 
                   13801: =back
                   13802: 
                   13803: =head2 Resource Access Logging
                   13804: 
                   13805: =over 4
                   13806: 
                   13807: =item *
                   13808: 
                   13809: flushcourselogs() : flush (save) buffer logs and access logs
                   13810: 
                   13811: =item *
                   13812: 
                   13813: courselog($what) : save message for course in hash
                   13814: 
                   13815: =item *
                   13816: 
                   13817: courseacclog($what) : save message for course using &courselog().  Perform
                   13818: special processing for specific resource types (problems, exams, quizzes, etc).
                   13819: 
1.191     harris41 13820: =item *
                   13821: 
                   13822: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13823: as a PerlChildExitHandler
1.243     albertel 13824: 
                   13825: =back
                   13826: 
                   13827: =head2 Other
                   13828: 
                   13829: =over 4
                   13830: 
                   13831: =item *
                   13832: 
                   13833: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13834: 
                   13835: =back
                   13836: 
                   13837: =cut
1.877     foxr     13838: 

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