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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.21! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.20 2013/03/11 13:24:09 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.1117    foxr      100: 
1.1090    raeburn   101: use File::Copy;
1.676     albertel  102: 
1.195     www       103: my $readit;
1.550     foxr      104: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  105: 
1.619     albertel  106: require Exporter;
                    107: 
                    108: our @ISA = qw (Exporter);
                    109: our @EXPORT = qw(%env);
                    110: 
1.1172.2.9  raeburn   111: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       112: {
                    113:     my $logid;
1.1172.2.9  raeburn   114:     sub write_log {
                    115: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    116:         if ($context eq 'course') {
                    117:             if (($cnum eq '') || ($cdom eq '')) {
                    118:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    119:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    120:             }
1.957     raeburn   121:         }
1.1172.2.13  raeburn   122: 	$logid ++;
1.957     raeburn   123:         my $now = time();
                    124: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   125:         my $logentry = {
                    126:                          $id => {
                    127:                                   'exe_uname' => $env{'user.name'},
                    128:                                   'exe_udom'  => $env{'user.domain'},
                    129:                                   'exe_time'  => $now,
                    130:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    131:                                   'delflag'   => $delflag,
                    132:                                   'logentry'  => $storehash,
                    133:                                   'uname'     => $uname,
                    134:                                   'udom'      => $udom,
                    135:                                 }
                    136:                        };
                    137:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       138:     }
                    139: }
1.1       albertel  140: 
1.163     harris41  141: sub logtouch {
                    142:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  143:     unless (-e "$execdir/logs/lonnet.log") {	
                    144: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  145: 	close $fh;
                    146:     }
                    147:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    148:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    149: }
                    150: 
1.1       albertel  151: sub logthis {
                    152:     my $message=shift;
                    153:     my $execdir=$perlvar{'lonDaemons'};
                    154:     my $now=time;
                    155:     my $local=localtime($now);
1.448     albertel  156:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      157: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    158: 	print $fh $logstring;
1.448     albertel  159: 	close($fh);
                    160:     }
1.1       albertel  161:     return 1;
                    162: }
                    163: 
                    164: sub logperm {
                    165:     my $message=shift;
                    166:     my $execdir=$perlvar{'lonDaemons'};
                    167:     my $now=time;
                    168:     my $local=localtime($now);
1.448     albertel  169:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    170: 	print $fh "$now:$message:$local\n";
                    171: 	close($fh);
                    172:     }
1.1       albertel  173:     return 1;
                    174: }
                    175: 
1.850     albertel  176: sub create_connection {
1.853     albertel  177:     my ($hostname,$lonid) = @_;
1.851     albertel  178:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  179: 				     Type    => SOCK_STREAM,
                    180: 				     Timeout => 10);
                    181:     return 0 if (!$client);
1.890     albertel  182:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  183:     my $result = <$client>;
                    184:     chomp($result);
                    185:     return 1 if ($result eq 'done');
                    186:     return 0;
                    187: }
                    188: 
1.983     raeburn   189: sub get_server_timezone {
                    190:     my ($cnum,$cdom) = @_;
                    191:     my $home=&homeserver($cnum,$cdom);
                    192:     if ($home ne 'no_host') {
                    193:         my $cachetime = 24*3600;
                    194:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    195:         if (defined($cached)) {
                    196:             return $timezone;
                    197:         } else {
                    198:             my $timezone = &reply('servertimezone',$home);
                    199:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    200:         }
                    201:     }
                    202: }
1.850     albertel  203: 
1.1106    raeburn   204: sub get_server_distarch {
                    205:     my ($lonhost,$ignore_cache) = @_;
                    206:     if (defined($lonhost)) {
                    207:         if (!defined(&hostname($lonhost))) {
                    208:             return;
                    209:         }
                    210:         my $cachetime = 12*3600;
                    211:         if (!$ignore_cache) {
                    212:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    213:             if (defined($cached)) {
                    214:                 return $distarch;
                    215:             }
                    216:         }
                    217:         my $rep = &reply('serverdistarch',$lonhost);
                    218:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    219:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    220:                 $rep eq '') {
                    221:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    222:         }
                    223:     }
                    224:     return;
                    225: }
                    226: 
1.993     raeburn   227: sub get_server_loncaparev {
1.1073    raeburn   228:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   229:     if (defined($lonhost)) {
                    230:         if (!defined(&hostname($lonhost))) {
                    231:             undef($lonhost);
                    232:         }
                    233:     }
                    234:     if (!defined($lonhost)) {
                    235:         if (defined(&domain($dom,'primary'))) {
                    236:             $lonhost=&domain($dom,'primary');
                    237:             if ($lonhost eq 'no_host') {
                    238:                 undef($lonhost);
                    239:             }
                    240:         }
                    241:     }
                    242:     if (defined($lonhost)) {
1.1073    raeburn   243:         my $cachetime = 12*3600;
                    244:         if (!$ignore_cache) {
                    245:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    246:             if (defined($cached)) {
                    247:                 return $loncaparev;
                    248:             }
                    249:         }
                    250:         my ($answer,$loncaparev);
                    251:         my @ids=&current_machine_ids();
                    252:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    253:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   254:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   255:                 $loncaparev = $1;
                    256:             }
                    257:         } else {
                    258:             $answer = &reply('serverloncaparev',$lonhost);
                    259:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    260:                 if ($caller eq 'loncron') {
                    261:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   262:                     $ua->timeout(4);
1.1073    raeburn   263:                     my $protocol = $protocol{$lonhost};
                    264:                     $protocol = 'http' if ($protocol ne 'https');
                    265:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    266:                     my $request=new HTTP::Request('GET',$url);
                    267:                     my $response=$ua->request($request);
                    268:                     unless ($response->is_error()) {
                    269:                         my $content = $response->content;
1.1081    raeburn   270:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   271:                             $loncaparev = $1;
                    272:                         }
                    273:                     }
                    274:                 } else {
                    275:                     $loncaparev = $loncaparevs{$lonhost};
                    276:                 }
1.1081    raeburn   277:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   278:                 $loncaparev = $1;
                    279:             }
1.993     raeburn   280:         }
1.1073    raeburn   281:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   282:     }
                    283: }
                    284: 
1.1074    raeburn   285: sub get_server_homeID {
                    286:     my ($hostname,$ignore_cache,$caller) = @_;
                    287:     unless ($ignore_cache) {
                    288:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    289:         if (defined($cached)) {
                    290:             return $serverhomeID;
                    291:         }
                    292:     }
                    293:     my $cachetime = 12*3600;
                    294:     my $serverhomeID;
                    295:     if ($caller eq 'loncron') { 
                    296:         my @machine_ids = &machine_ids($hostname);
                    297:         foreach my $id (@machine_ids) {
                    298:             my $response = &reply('serverhomeID',$id);
                    299:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    300:                 $serverhomeID = $response;
                    301:                 last;
                    302:             }
                    303:         }
                    304:         if ($serverhomeID eq '') {
                    305:             $serverhomeID = $machine_ids[-1];
                    306:         }
                    307:     } else {
                    308:         $serverhomeID = $serverhomeIDs{$hostname};
                    309:     }
                    310:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    311: }
                    312: 
1.1121    raeburn   313: sub get_remote_globals {
                    314:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   315:     my ($result,%returnhash,%whatneeded);
                    316:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   317:         foreach my $what (sort(keys(%{$whathash}))) {
                    318:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   319:             my ($response,$cached);
1.1121    raeburn   320:             unless ($ignore_cache) {
1.1125    raeburn   321:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   322:             }
                    323:             if (defined($cached)) {
1.1125    raeburn   324:                 $returnhash{$what} = $response;
1.1121    raeburn   325:             } else {
1.1125    raeburn   326:                 $whatneeded{$what} = 1;
1.1121    raeburn   327:             }
                    328:         }
1.1125    raeburn   329:         if (keys(%whatneeded) == 0) {
                    330:             $result = 'ok';
                    331:         } else {
1.1121    raeburn   332:             my $requested = &freeze_escape(\%whatneeded);
                    333:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   334:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    335:                 ($rep eq 'unknown_cmd')) {
                    336:                 $result = $rep;
                    337:             } else {
                    338:                 $result = 'ok';
1.1121    raeburn   339:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   340:                 foreach my $item (@pairs) {
                    341:                     my ($key,$value)=split(/=/,$item,2);
                    342:                     my $what = &unescape($key);
                    343:                     my $hashid = $lonhost.'-'.$what;
                    344:                     $returnhash{$what}=&thaw_unescape($value);
                    345:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   346:                 }
                    347:             }
                    348:         }
                    349:     }
1.1125    raeburn   350:     return ($result,\%returnhash);
1.1121    raeburn   351: }
                    352: 
1.1124    raeburn   353: sub remote_devalidate_cache {
                    354:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   355:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   356:     return $response;
                    357: }
                    358: 
1.1       albertel  359: # -------------------------------------------------- Non-critical communication
                    360: sub subreply {
                    361:     my ($cmd,$server)=@_;
1.838     albertel  362:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      363:     #
                    364:     #  With loncnew process trimming, there's a timing hole between lonc server
                    365:     #  process exit and the master server picking up the listen on the AF_UNIX
                    366:     #  socket.  In that time interval, a lock file will exist:
                    367: 
                    368:     my $lockfile=$peerfile.".lock";
                    369:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    370: 	sleep(1);
                    371:     }
                    372:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      373:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      374:     #
1.550     foxr      375:     #   We'll give the connection a few tries before abandoning it.  If
                    376:     #   connection is not possible, we'll con_lost back to the client.
                    377:     #   
                    378:     my $client;
                    379:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    380: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    381: 				      Type    => SOCK_STREAM,
                    382: 				      Timeout => 10);
1.869     albertel  383: 	if ($client) {
1.550     foxr      384: 	    last;		# Connected!
1.850     albertel  385: 	} else {
1.853     albertel  386: 	    &create_connection(&hostname($server),$server);
1.550     foxr      387: 	}
1.850     albertel  388:         sleep(1);		# Try again later if failed connection.
1.550     foxr      389:     }
                    390:     my $answer;
                    391:     if ($client) {
1.704     albertel  392: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      393: 	$answer=<$client>;
                    394: 	if (!$answer) { $answer="con_lost"; }
                    395: 	chomp($answer);
                    396:     } else {
                    397: 	$answer = 'con_lost';	# Failed connection.
                    398:     }
1.1       albertel  399:     return $answer;
                    400: }
                    401: 
                    402: sub reply {
                    403:     my ($cmd,$server)=@_;
1.838     albertel  404:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  405:     my $answer=subreply($cmd,$server);
1.65      www       406:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  407:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       408:                 " $cmd to $server returned $answer</font>");
                    409:     }
1.1       albertel  410:     return $answer;
                    411: }
                    412: 
                    413: # ----------------------------------------------------------- Send USR1 to lonc
                    414: 
                    415: sub reconlonc {
1.891     albertel  416:     my ($lonid) = @_;
                    417:     my $hostname = &hostname($lonid);
                    418:     if ($lonid) {
                    419: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    420: 	if ($hostname && -e $peerfile) {
                    421: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    422: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    423: 					     Type    => SOCK_STREAM,
                    424: 					     Timeout => 10);
                    425: 	    if ($client) {
                    426: 		print $client ("reset_retries\n");
                    427: 		my $answer=<$client>;
                    428: 		#reset just this one.
                    429: 	    }
                    430: 	}
                    431: 	return;
                    432:     }
                    433: 
1.836     www       434:     &logthis("Trying to reconnect lonc");
1.1       albertel  435:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  436:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  437: 	my $loncpid=<$fh>;
                    438:         chomp($loncpid);
                    439:         if (kill 0 => $loncpid) {
                    440: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    441:             kill USR1 => $loncpid;
                    442:             sleep 1;
1.836     www       443:          } else {
1.12      www       444: 	    &logthis(
1.672     albertel  445:                "<font color=\"blue\">WARNING:".
1.12      www       446:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  447:         }
                    448:     } else {
1.836     www       449: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  450:     }
                    451: }
                    452: 
                    453: # ------------------------------------------------------ Critical communication
1.12      www       454: 
1.1       albertel  455: sub critical {
                    456:     my ($cmd,$server)=@_;
1.838     albertel  457:     unless (&hostname($server)) {
1.672     albertel  458:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       459:                " Critical message to unknown server ($server)</font>");
                    460:         return 'no_such_host';
                    461:     }
1.1       albertel  462:     my $answer=reply($cmd,$server);
                    463:     if ($answer eq 'con_lost') {
                    464: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  465: 	my $answer=reply($cmd,$server);
1.1       albertel  466:         if ($answer eq 'con_lost') {
                    467:             my $now=time;
                    468:             my $middlename=$cmd;
1.5       www       469:             $middlename=substr($middlename,0,16);
1.1       albertel  470:             $middlename=~s/\W//g;
                    471:             my $dfilename=
1.305     www       472:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    473:             $dumpcount++;
1.1       albertel  474:             {
1.448     albertel  475: 		my $dfh;
                    476: 		if (open($dfh,">$dfilename")) {
                    477: 		    print $dfh "$cmd\n"; 
                    478: 		    close($dfh);
                    479: 		}
1.1       albertel  480:             }
                    481:             sleep 2;
                    482:             my $wcmd='';
                    483:             {
1.448     albertel  484: 		my $dfh;
                    485: 		if (open($dfh,"<$dfilename")) {
                    486: 		    $wcmd=<$dfh>; 
                    487: 		    close($dfh);
                    488: 		}
1.1       albertel  489:             }
                    490:             chomp($wcmd);
1.7       www       491:             if ($wcmd eq $cmd) {
1.672     albertel  492: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       493:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  494:                 &logperm("D:$server:$cmd");
                    495: 	        return 'con_delayed';
                    496:             } else {
1.672     albertel  497:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       498:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  499:                 &logperm("F:$server:$cmd");
                    500:                 return 'con_failed';
                    501:             }
                    502:         }
                    503:     }
                    504:     return $answer;
1.405     albertel  505: }
                    506: 
1.755     albertel  507: # ------------------------------------------- check if return value is an error
                    508: 
                    509: sub error {
                    510:     my ($result) = @_;
1.756     albertel  511:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  512: 	if ($2 == 2) { return undef; }
                    513: 	return $1;
                    514:     }
                    515:     return undef;
                    516: }
                    517: 
1.783     albertel  518: sub convert_and_load_session_env {
                    519:     my ($lonidsdir,$handle)=@_;
                    520:     my @profile;
                    521:     {
1.917     albertel  522: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    523: 	if (!$opened) {
1.915     albertel  524: 	    return 0;
                    525: 	}
1.783     albertel  526: 	flock($idf,LOCK_SH);
                    527: 	@profile=<$idf>;
                    528: 	close($idf);
                    529:     }
                    530:     my %temp_env;
                    531:     foreach my $line (@profile) {
1.786     albertel  532: 	if ($line !~ m/=/) {
                    533: 	    return 0;
                    534: 	}
1.783     albertel  535: 	chomp($line);
                    536: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    537: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    538:     }
                    539:     unlink("$lonidsdir/$handle.id");
                    540:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    541: 	    0640)) {
                    542: 	%disk_env = %temp_env;
                    543: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    544: 	untie(%disk_env);
                    545:     }
1.786     albertel  546:     return 1;
1.783     albertel  547: }
                    548: 
1.374     www       549: # ------------------------------------------- Transfer profile into environment
1.780     albertel  550: my $env_loaded;
                    551: sub transfer_profile_to_env {
1.788     albertel  552:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    553:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       554: 
1.720     albertel  555:     if (!defined($lonidsdir)) {
                    556: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    557:     }
                    558:     if (!defined($handle)) {
                    559:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    560:     }
                    561: 
1.786     albertel  562:     my $convert;
                    563:     {
1.917     albertel  564:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    565: 	if (!$opened) {
1.915     albertel  566: 	    return;
                    567: 	}
1.786     albertel  568: 	flock($idf,LOCK_SH);
                    569: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    570: 		&GDBM_READER(),0640)) {
                    571: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    572: 	    untie(%disk_env);
                    573: 	} else {
                    574: 	    $convert = 1;
                    575: 	}
                    576:     }
                    577:     if ($convert) {
                    578: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    579: 	    &logthis("Failed to load session, or convert session.");
                    580: 	}
1.374     www       581:     }
1.783     albertel  582: 
1.786     albertel  583:     my %remove;
1.783     albertel  584:     while ( my $envname = each(%env) ) {
1.433     matthew   585:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    586:             if ($time < time-300) {
1.783     albertel  587:                 $remove{$key}++;
1.433     matthew   588:             }
                    589:         }
                    590:     }
1.783     albertel  591: 
1.619     albertel  592:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  593:     $env_loaded=1;
1.783     albertel  594:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   595:         &delenv($expired_key);
1.374     www       596:     }
1.1       albertel  597: }
                    598: 
1.916     albertel  599: # ---------------------------------------------------- Check for valid session 
                    600: sub check_for_valid_session {
1.1155    raeburn   601:     my ($r,$name) = @_;
1.916     albertel  602:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   603:     if ($name eq '') {
                    604:         $name = 'lonID';
                    605:     }
                    606:     my $lonid=$cookies{$name};
1.916     albertel  607:     return undef if (!$lonid);
                    608: 
                    609:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   610:     my $lonidsdir;
                    611:     if ($name eq 'lonDAV') {
                    612:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    613:     } else {
                    614:         $lonidsdir=$r->dir_config('lonIDsDir');
                    615:     }
1.916     albertel  616:     return undef if (!-e "$lonidsdir/$handle.id");
                    617: 
1.917     albertel  618:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    619:     return undef if (!$opened);
1.916     albertel  620: 
                    621:     flock($idf,LOCK_SH);
                    622:     my %disk_env;
                    623:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    624: 	    &GDBM_READER(),0640)) {
                    625: 	return undef;	
                    626:     }
                    627: 
                    628:     if (!defined($disk_env{'user.name'})
                    629: 	|| !defined($disk_env{'user.domain'})) {
                    630: 	return undef;
                    631:     }
1.1172.2.18  raeburn   632: 
                    633:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    634:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    635:             $r->user($disk_env{'user.name'});
                    636:         } else {
                    637:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    638:         }
                    639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
                    674:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    847:                 if ($uint_dom) {
                    848:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    849:                                                  $try_server));
                    850:                 }
                    851: 	        ($spare_server, $lowest_load) =
                    852: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    853:             }
1.1083    raeburn   854:         }
1.784     albertel  855: 
1.1123    raeburn   856:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    857: 
                    858:         if (!$found_server) {
                    859:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    860: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    861:                     if ($uint_dom) {
                    862:                         next unless (&spare_can_host($udom,$uint_dom,
                    863:                                                      $remotesessions,$try_server));
                    864:                     }
                    865: 	            ($spare_server, $lowest_load) =
                    866: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    867:                 }
                    868: 	    }
                    869:         }
1.784     albertel  870:     }
                    871: 
                    872:     if (!$want_server_name) {
1.968     raeburn   873:         my $protocol = 'http';
                    874:         if ($protocol{$spare_server} eq 'https') {
                    875:             $protocol = $protocol{$spare_server};
                    876:         }
1.1001    raeburn   877:         if (defined($spare_server)) {
                    878:             my $hostname = &hostname($spare_server);
1.1083    raeburn   879:             if (defined($hostname)) {
1.1001    raeburn   880: 	        $spare_server = $protocol.'://'.$hostname;
                    881:             }
                    882:         }
1.784     albertel  883:     }
                    884:     return $spare_server;
                    885: }
                    886: 
                    887: sub compare_server_load {
                    888:     my ($try_server, $spare_server, $lowest_load) = @_;
                    889: 
                    890:     my $loadans     = &reply('load',    $try_server);
                    891:     my $userloadans = &reply('userload',$try_server);
                    892: 
                    893:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   894: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  895:     }
                    896: 
                    897:     my $load;
                    898:     if ($loadans =~ /\d/) {
                    899: 	if ($userloadans =~ /\d/) {
                    900: 	    #both are numbers, pick the bigger one
                    901: 	    $load = ($loadans > $userloadans) ? $loadans 
                    902: 		                              : $userloadans;
1.411     albertel  903: 	} else {
1.784     albertel  904: 	    $load = $loadans;
1.411     albertel  905: 	}
1.784     albertel  906:     } else {
                    907: 	$load = $userloadans;
                    908:     }
                    909: 
                    910:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    911: 	$spare_server = $try_server;
                    912: 	$lowest_load  = $load;
1.370     albertel  913:     }
1.784     albertel  914:     return ($spare_server,$lowest_load);
1.202     matthew   915: }
1.914     albertel  916: 
                    917: # --------------------------- ask offload servers if user already has a session
                    918: sub find_existing_session {
                    919:     my ($udom,$uname) = @_;
1.1123    raeburn   920:     my $spareshash = &this_host_spares($udom);
                    921:     if (ref($spareshash) eq 'HASH') {
                    922:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    923:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    924:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    925:             }
                    926:         }
                    927:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    928:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    929:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    930:             }
                    931:         }
1.914     albertel  932:     }
                    933:     return;
                    934: }
                    935: 
                    936: # -------------------------------- ask if server already has a session for user
                    937: sub has_user_session {
                    938:     my ($lonid,$udom,$uname) = @_;
                    939:     my $result = &reply(join(':','userhassession',
                    940: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    941:     return 1 if ($result eq 'ok');
                    942: 
                    943:     return 0;
                    944: }
                    945: 
1.1076    raeburn   946: # --------- determine least loaded server in a user's domain which allows login
                    947: 
                    948: sub choose_server {
1.1115    raeburn   949:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   950:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   951:     my %servers = &get_servers($udom);
1.1076    raeburn   952:     my $lowest_load = 30000;
1.1151    raeburn   953:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   954:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   955:         my $loginvia;
                    956:         if ($checkloginvia) {
                    957:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   958:             if ($loginvia) {
                    959:                 my ($server,$path) = split(/:/,$loginvia);
                    960:                 ($login_host, $lowest_load) =
                    961:                     &compare_server_load($server, $login_host, $lowest_load);
                    962:                 if ($login_host eq $server) {
                    963:                     $portal_path = $path;
1.1151    raeburn   964:                     $isredirect = 1;
1.1116    raeburn   965:                 }
                    966:             } else {
                    967:                 ($login_host, $lowest_load) =
                    968:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    969:                 if ($login_host eq $lonhost) {
                    970:                     $portal_path = '';
1.1151    raeburn   971:                     $isredirect = ''; 
1.1116    raeburn   972:                 }
                    973:             }
                    974:         } else {
1.1076    raeburn   975:             ($login_host, $lowest_load) =
1.1116    raeburn   976:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   977:         }
                    978:     }
                    979:     if ($login_host ne '') {
1.1116    raeburn   980:         $hostname = &hostname($login_host);
1.1076    raeburn   981:     }
1.1151    raeburn   982:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   983: }
                    984: 
1.202     matthew   985: # --------------------------------------------- Try to change a user's password
                    986: 
                    987: sub changepass {
1.799     raeburn   988:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   989:     $currentpass = &escape($currentpass);
                    990:     $newpass     = &escape($newpass);
1.1030    raeburn   991:     my $lonhost = $perlvar{'lonHostID'};
                    992:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   993: 		       $server);
                    994:     if (! $answer) {
                    995: 	&logthis("No reply on password change request to $server ".
                    996: 		 "by $uname in domain $udom.");
                    997:     } elsif ($answer =~ "^ok") {
                    998:         &logthis("$uname in $udom successfully changed their password ".
                    999: 		 "on $server.");
                   1000:     } elsif ($answer =~ "^pwchange_failure") {
                   1001: 	&logthis("$uname in $udom was unable to change their password ".
                   1002: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1003: 		 "or pwchange");
                   1004:     } elsif ($answer =~ "^non_authorized") {
                   1005:         &logthis("$uname in $udom did not get their password correct when ".
                   1006: 		 "attempting to change it on $server.");
                   1007:     } elsif ($answer =~ "^auth_mode_error") {
                   1008:         &logthis("$uname in $udom attempted to change their password despite ".
                   1009: 		 "not being locally or internally authenticated on $server.");
                   1010:     } elsif ($answer =~ "^unknown_user") {
                   1011:         &logthis("$uname in $udom attempted to change their password ".
                   1012: 		 "on $server but were unable to because $server is not ".
                   1013: 		 "their home server.");
                   1014:     } elsif ($answer =~ "^refused") {
                   1015: 	&logthis("$server refused to change $uname in $udom password because ".
                   1016: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1017:     } elsif ($answer =~ "invalid_client") {
                   1018:         &logthis("$server refused to change $uname in $udom password because ".
                   1019:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1020:     }
                   1021:     return $answer;
1.1       albertel 1022: }
                   1023: 
1.169     harris41 1024: # ----------------------- Try to determine user's current authentication scheme
                   1025: 
                   1026: sub queryauthenticate {
                   1027:     my ($uname,$udom)=@_;
1.456     albertel 1028:     my $uhome=&homeserver($uname,$udom);
                   1029:     if (!$uhome) {
                   1030: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1031: 	return 'no_host';
                   1032:     }
                   1033:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1034:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1035: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1036:     }
1.456     albertel 1037:     return $answer;
1.169     harris41 1038: }
                   1039: 
1.1       albertel 1040: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1041: 
1.1       albertel 1042: sub authenticate {
1.1073    raeburn  1043:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1044:     $upass=&escape($upass);
                   1045:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1046:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1047:     my $newhome;
1.836     www      1048:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1049: # Maybe the machine was offline and only re-appeared again recently?
                   1050:         &reconlonc();
                   1051: # One more
1.952     raeburn  1052: 	$uhome=&homeserver($uname,$udom,1);
                   1053:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1054:             if (defined(&domain($udom,'primary'))) {
                   1055:                 $newhome=&domain($udom,'primary');
                   1056:             }
                   1057:             if ($newhome ne '') {
                   1058:                 $uhome = $newhome;
                   1059:             }
                   1060:         }
1.836     www      1061: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1062: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1063: 	    return 'no_host';
                   1064:         }
1.1       albertel 1065:     }
1.1073    raeburn  1066:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1067:     if ($answer eq 'authorized') {
1.952     raeburn  1068:         if ($newhome) {
                   1069:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1070:             return 'no_account_on_host'; 
                   1071:         } else {
                   1072:             &logthis("User $uname at $udom authorized by $uhome");
                   1073:             return $uhome;
                   1074:         }
1.471     albertel 1075:     }
                   1076:     if ($answer eq 'non_authorized') {
                   1077: 	&logthis("User $uname at $udom rejected by $uhome");
                   1078: 	return 'no_host'; 
1.9       www      1079:     }
1.471     albertel 1080:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1081:     return 'no_host';
                   1082: }
                   1083: 
1.1073    raeburn  1084: sub can_host_session {
1.1074    raeburn  1085:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1086:     my $canhost = 1;
1.1074    raeburn  1087:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1088:     if (ref($remotesessions) eq 'HASH') {
                   1089:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1090:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1091:                 $canhost = 0;
                   1092:             } else {
                   1093:                 $canhost = 1;
                   1094:             }
                   1095:         }
                   1096:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1097:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1098:                 $canhost = 1;
                   1099:             } else {
                   1100:                 $canhost = 0;
                   1101:             }
                   1102:         }
                   1103:         if ($canhost) {
                   1104:             if ($remotesessions->{'version'} ne '') {
                   1105:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1106:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1107:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1108:                         my $major = $1;
                   1109:                         my $minor = $2;
                   1110:                         if (($major < $reqmajor ) ||
                   1111:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1112:                             $canhost = 0;
                   1113:                         }
                   1114:                     } else {
                   1115:                         $canhost = 0;
                   1116:                     }
                   1117:                 }
                   1118:             }
                   1119:         }
                   1120:     }
                   1121:     if ($canhost) {
                   1122:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1123:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1124:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1125:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1126:                 if (($uint_dom ne '') && 
                   1127:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1128:                     $canhost = 0;
                   1129:                 } else {
                   1130:                     $canhost = 1;
                   1131:                 }
                   1132:             }
                   1133:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1134:                 if (($uint_dom ne '') && 
                   1135:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1136:                     $canhost = 1;
                   1137:                 } else {
                   1138:                     $canhost = 0;
                   1139:                 }
                   1140:             }
                   1141:         }
                   1142:     }
                   1143:     return $canhost;
                   1144: }
                   1145: 
1.1083    raeburn  1146: sub spare_can_host {
                   1147:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1148:     my $canhost=1;
                   1149:     my @intdoms;
                   1150:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1151:     if (ref($internet_names) eq 'ARRAY') {
                   1152:         @intdoms = @{$internet_names};
                   1153:     }
                   1154:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1155:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1156:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1157:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1158:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1159:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1160:                                      $remotesessions,
                   1161:                                      $defdomdefaults{'hostedsessions'});
                   1162:     }
                   1163:     return $canhost;
                   1164: }
                   1165: 
1.1123    raeburn  1166: sub this_host_spares {
                   1167:     my ($dom) = @_;
1.1126    raeburn  1168:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1169:     my @hosts = &current_machine_ids();
                   1170:     foreach my $lonhost (@hosts) {
                   1171:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1172:             $dom_in_use = $dom;
                   1173:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1174:             last;
                   1175:         }
                   1176:     }
1.1126    raeburn  1177:     if ($dom_in_use ne '') {
                   1178:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1179:     }
                   1180:     if (ref($result) ne 'HASH') {
                   1181:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1182:         $dom_in_use = &host_domain($lonhost_in_use);
                   1183:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1184:         if (ref($result) ne 'HASH') {
                   1185:             $result = \%spareid;
                   1186:         }
                   1187:     }
                   1188:     return $result;
                   1189: }
                   1190: 
                   1191: sub spares_for_offload  {
                   1192:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1193:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1194:     if (defined($cached)) {
                   1195:         return $result;
                   1196:     } else {
1.1126    raeburn  1197:         my $cachetime = 60*60*24;
                   1198:         my %domconfig =
                   1199:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1200:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1201:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1202:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1203:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1204:                 }
                   1205:             }
                   1206:         }
                   1207:     }
1.1126    raeburn  1208:     return;
1.1123    raeburn  1209: }
                   1210: 
1.1129    raeburn  1211: sub get_lonbalancer_config {
                   1212:     my ($servers) = @_;
                   1213:     my ($currbalancer,$currtargets);
                   1214:     if (ref($servers) eq 'HASH') {
                   1215:         foreach my $server (keys(%{$servers})) {
                   1216:             my %what = (
                   1217:                          spareid => 1,
                   1218:                          perlvar => 1,
                   1219:                        );
                   1220:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1221:             if ($result eq 'ok') {
                   1222:                 if (ref($returnhash) eq 'HASH') {
                   1223:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1224:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1225:                             $currbalancer = $server;
                   1226:                             $currtargets = {};
                   1227:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1228:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1229:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1230:                                 }
                   1231:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1232:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1233:                                 }
                   1234:                             }
                   1235:                             last;
                   1236:                         }
                   1237:                     }
                   1238:                 }
                   1239:             }
                   1240:         }
                   1241:     }
                   1242:     return ($currbalancer,$currtargets);
                   1243: }
                   1244: 
                   1245: sub check_loadbalancing {
                   1246:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1247:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1248:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1249:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1250:     my @hosts = &current_machine_ids();
1.1129    raeburn  1251:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1252:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1253:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1254:     my $serverhomedom = &host_domain($lonhost);
                   1255: 
                   1256:     my $cachetime = 60*60*24;
                   1257: 
                   1258:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1259:         $dom_in_use = $udom;
                   1260:         $homeintdom = 1;
                   1261:     } else {
                   1262:         $dom_in_use = $serverhomedom;
                   1263:     }
                   1264:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1265:     unless (defined($cached)) {
                   1266:         my %domconfig =
                   1267:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1268:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1269:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1270:         }
                   1271:     }
                   1272:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1273:         ($is_balancer,$currtargets,$currrules) =
                   1274:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1275:         if ($is_balancer) {
                   1276:             if (ref($currrules) eq 'HASH') {
                   1277:                 if ($homeintdom) {
                   1278:                     if ($uname ne '') {
                   1279:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1280:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1281:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1282:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1283:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1284:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1285:                             }
                   1286:                         }
                   1287:                         if ($rule_in_effect eq '') {
                   1288:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1289:                             if ($userenv{'inststatus'} ne '') {
                   1290:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1291:                                 my ($othertitle,$usertypes,$types) =
                   1292:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1293:                                 if (ref($types) eq 'ARRAY') {
                   1294:                                     foreach my $type (@{$types}) {
                   1295:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1296:                                             if (exists($currrules->{$type})) {
                   1297:                                                 $rule_in_effect = $currrules->{$type};
                   1298:                                             }
                   1299:                                         }
                   1300:                                     }
                   1301:                                 }
                   1302:                             } else {
                   1303:                                 if (exists($currrules->{'default'})) {
                   1304:                                     $rule_in_effect = $currrules->{'default'};
                   1305:                                 }
                   1306:                             }
                   1307:                         }
                   1308:                     } else {
                   1309:                         if (exists($currrules->{'default'})) {
                   1310:                             $rule_in_effect = $currrules->{'default'};
                   1311:                         }
                   1312:                     }
                   1313:                 } else {
                   1314:                     if ($currrules->{'_LC_external'} ne '') {
                   1315:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1316:                     }
                   1317:                 }
                   1318:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1319:                                                        $uname,$udom);
                   1320:             }
                   1321:         }
                   1322:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1323:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1324:         unless (defined($cached)) {
                   1325:             my %domconfig =
                   1326:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1327:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1328:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1329:             }
                   1330:         }
                   1331:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1332:             ($is_balancer,$currtargets,$currrules) =
                   1333:                 &check_balancer_result($result,@hosts);
                   1334:             if ($is_balancer) {
1.1129    raeburn  1335:                 if (ref($currrules) eq 'HASH') {
                   1336:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1337:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1338:                     }
                   1339:                 }
                   1340:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1341:                                                        $uname,$udom);
                   1342:             }
                   1343:         } else {
                   1344:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1345:                 $is_balancer = 1;
                   1346:                 $offloadto = &this_host_spares($dom_in_use);
                   1347:             }
                   1348:         }
                   1349:     } else {
                   1350:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1351:             $is_balancer = 1;
                   1352:             $offloadto = &this_host_spares($dom_in_use);
                   1353:         }
                   1354:     }
1.1172.2.5  raeburn  1355:     if ($is_balancer) {
                   1356:         my $lowest_load = 30000;
                   1357:         if (ref($offloadto) eq 'HASH') {
                   1358:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1359:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1360:                     ($otherserver,$lowest_load) =
                   1361:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1362:                 }
1.1129    raeburn  1363:             }
1.1172.2.5  raeburn  1364:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1365: 
1.1172.2.5  raeburn  1366:             if (!$found_server) {
                   1367:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1368:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1369:                         ($otherserver,$lowest_load) =
                   1370:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1371:                     }
                   1372:                 }
                   1373:             }
                   1374:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1375:             if (@{$offloadto} == 1) {
                   1376:                 $otherserver = $offloadto->[0];
                   1377:             } elsif (@{$offloadto} > 1) {
                   1378:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1379:                     ($otherserver,$lowest_load) =
                   1380:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1381:                 }
                   1382:             }
                   1383:         }
1.1172.2.5  raeburn  1384:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1385:             $is_balancer = 0;
                   1386:             if ($uname ne '' && $udom ne '') {
                   1387:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1388: 
                   1389:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1390:                              'user.loadbalcheck.time' => time});
                   1391:                 }
1.1129    raeburn  1392:             }
                   1393:         }
                   1394:     }
                   1395:     return ($is_balancer,$otherserver);
                   1396: }
                   1397: 
1.1172.2.12  raeburn  1398: sub check_balancer_result {
                   1399:     my ($result,@hosts) = @_;
                   1400:     my ($is_balancer,$currtargets,$currrules);
                   1401:     if (ref($result) eq 'HASH') {
                   1402:         if ($result->{'lonhost'} ne '') {
                   1403:             my $currbalancer = $result->{'lonhost'};
                   1404:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1405:                 $is_balancer = 1;
                   1406:                 $currtargets = $result->{'targets'};
                   1407:                 $currrules = $result->{'rules'};
                   1408:             }
                   1409:         } else {
                   1410:             foreach my $key (keys(%{$result})) {
                   1411:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1412:                     (ref($result->{$key}) eq 'HASH')) {
                   1413:                     $is_balancer = 1;
                   1414:                     $currrules = $result->{$key}{'rules'};
                   1415:                     $currtargets = $result->{$key}{'targets'};
                   1416:                     last;
                   1417:                 }
                   1418:             }
                   1419:         }
                   1420:     }
                   1421:     return ($is_balancer,$currtargets,$currrules);
                   1422: }
                   1423: 
1.1129    raeburn  1424: sub get_loadbalancer_targets {
                   1425:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1426:     my $offloadto;
1.1172.2.4  raeburn  1427:     if ($rule_in_effect eq 'none') {
                   1428:         return [$perlvar{'lonHostID'}];
                   1429:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1430:         $offloadto = $currtargets;
                   1431:     } else {
                   1432:         if ($rule_in_effect eq 'homeserver') {
                   1433:             my $homeserver = &homeserver($uname,$udom);
                   1434:             if ($homeserver ne 'no_host') {
                   1435:                 $offloadto = [$homeserver];
                   1436:             }
                   1437:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1438:             my %domconfig =
                   1439:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1440:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1441:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1442:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1443:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1444:                     }
                   1445:                 }
                   1446:             } else {
1.1172.2.7  raeburn  1447:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1448:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1449:                 if (&hostname($remotebalancer) ne '') {
                   1450:                     $offloadto = [$remotebalancer];
                   1451:                 }
                   1452:             }
                   1453:         } elsif (&hostname($rule_in_effect) ne '') {
                   1454:             $offloadto = [$rule_in_effect];
                   1455:         }
                   1456:     }
                   1457:     return $offloadto;
                   1458: }
                   1459: 
1.1127    raeburn  1460: sub internet_dom_servers {
                   1461:     my ($dom) = @_;
                   1462:     my (%uniqservers,%servers);
                   1463:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1464:     my @machinedoms = &machine_domains($primaryserver);
                   1465:     foreach my $mdom (@machinedoms) {
                   1466:         my %currservers = %servers;
                   1467:         my %server = &get_servers($mdom);
                   1468:         %servers = (%currservers,%server);
                   1469:     }
                   1470:     my %by_hostname;
                   1471:     foreach my $id (keys(%servers)) {
                   1472:         push(@{$by_hostname{$servers{$id}}},$id);
                   1473:     }
                   1474:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1475:         if (@{$by_hostname{$hostname}} > 1) {
                   1476:             my $match = 0;
                   1477:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1478:                 if (&host_domain($id) eq $dom) {
                   1479:                     $uniqservers{$id} = $hostname;
                   1480:                     $match = 1;
                   1481:                 }
                   1482:             }
                   1483:             unless ($match) {
                   1484:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1485:             }
                   1486:         } else {
                   1487:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1488:         }
                   1489:     }
                   1490:     return %uniqservers;
                   1491: }
                   1492: 
1.1       albertel 1493: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1494: 
1.599     albertel 1495: my %homecache;
1.1       albertel 1496: sub homeserver {
1.230     stredwic 1497:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1498:     my $index="$uname:$udom";
1.426     albertel 1499: 
1.599     albertel 1500:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1501: 
                   1502:     my %servers = &get_servers($udom,'library');
                   1503:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1504:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1505: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1506: 
                   1507: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1508: 	if ($answer eq 'found') {
                   1509: 	    delete($badServerCache{$tryserver}); 
                   1510: 	    return $homecache{$index}=$tryserver;
                   1511: 	} elsif ($answer eq 'no_host') {
                   1512: 	    $badServerCache{$tryserver}=1;
                   1513: 	}
1.1       albertel 1514:     }    
                   1515:     return 'no_host';
1.70      www      1516: }
                   1517: 
                   1518: # ------------------------------------- Find the usernames behind a list of IDs
                   1519: 
                   1520: sub idget {
                   1521:     my ($udom,@ids)=@_;
                   1522:     my %returnhash=();
                   1523:     
1.841     albertel 1524:     my %servers = &get_servers($udom,'library');
                   1525:     foreach my $tryserver (keys(%servers)) {
                   1526: 	my $idlist=join('&',@ids);
                   1527: 	$idlist=~tr/A-Z/a-z/; 
                   1528: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1529: 	my @answer=();
                   1530: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1531: 	    @answer=split(/\&/,$reply);
                   1532: 	}                    ;
                   1533: 	my $i;
                   1534: 	for ($i=0;$i<=$#ids;$i++) {
                   1535: 	    if ($answer[$i]) {
                   1536: 		$returnhash{$ids[$i]}=$answer[$i];
                   1537: 	    } 
                   1538: 	}
                   1539:     } 
1.70      www      1540:     return %returnhash;
                   1541: }
                   1542: 
                   1543: # ------------------------------------- Find the IDs behind a list of usernames
                   1544: 
                   1545: sub idrget {
                   1546:     my ($udom,@unames)=@_;
                   1547:     my %returnhash=();
1.800     albertel 1548:     foreach my $uname (@unames) {
                   1549:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1550:     }
1.70      www      1551:     return %returnhash;
                   1552: }
                   1553: 
                   1554: # ------------------------------- Store away a list of names and associated IDs
                   1555: 
                   1556: sub idput {
                   1557:     my ($udom,%ids)=@_;
                   1558:     my %servers=();
1.800     albertel 1559:     foreach my $uname (keys(%ids)) {
                   1560: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1561:         my $uhom=&homeserver($uname,$udom);
1.70      www      1562:         if ($uhom ne 'no_host') {
1.800     albertel 1563:             my $id=&escape($ids{$uname});
1.70      www      1564:             $id=~tr/A-Z/a-z/;
1.800     albertel 1565:             my $esc_unam=&escape($uname);
1.70      www      1566: 	    if ($servers{$uhom}) {
1.800     albertel 1567: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1568:             } else {
1.800     albertel 1569:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1570:             }
                   1571:         }
1.191     harris41 1572:     }
1.800     albertel 1573:     foreach my $server (keys(%servers)) {
                   1574:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1575:     }
1.344     www      1576: }
                   1577: 
1.1023    raeburn  1578: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1579: sub dump_dom {
1.1165    droeschl 1580:     my ($namespace, $udom, $regexp) = @_;
                   1581: 
                   1582:     $udom ||= $env{'user.domain'};
                   1583: 
                   1584:     return () unless $udom;
                   1585: 
                   1586:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1587: }
                   1588: 
1.1023    raeburn  1589: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1590: 
                   1591: sub get_dom {
1.860     raeburn  1592:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1593:     my $items='';
                   1594:     foreach my $item (@$storearr) {
                   1595:         $items.=&escape($item).'&';
                   1596:     }
                   1597:     $items=~s/\&$//;
1.860     raeburn  1598:     if (!$udom) {
                   1599:         $udom=$env{'user.domain'};
                   1600:         if (defined(&domain($udom,'primary'))) {
                   1601:             $uhome=&domain($udom,'primary');
                   1602:         } else {
1.874     albertel 1603:             undef($uhome);
1.860     raeburn  1604:         }
                   1605:     } else {
                   1606:         if (!$uhome) {
                   1607:             if (defined(&domain($udom,'primary'))) {
                   1608:                 $uhome=&domain($udom,'primary');
                   1609:             }
                   1610:         }
                   1611:     }
                   1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1613:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1614:         my %returnhash;
1.875     albertel 1615:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1616:             return %returnhash;
                   1617:         }
1.806     raeburn  1618:         my @pairs=split(/\&/,$rep);
                   1619:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1620:             return @pairs;
                   1621:         }
                   1622:         my $i=0;
                   1623:         foreach my $item (@$storearr) {
                   1624:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1625:             $i++;
                   1626:         }
                   1627:         return %returnhash;
                   1628:     } else {
1.880     banghart 1629:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1630:     }
                   1631: }
                   1632: 
                   1633: # -------------------------------------------- put items in domain db files 
                   1634: 
                   1635: sub put_dom {
1.860     raeburn  1636:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1637:     if (!$udom) {
                   1638:         $udom=$env{'user.domain'};
                   1639:         if (defined(&domain($udom,'primary'))) {
                   1640:             $uhome=&domain($udom,'primary');
                   1641:         } else {
1.874     albertel 1642:             undef($uhome);
1.860     raeburn  1643:         }
                   1644:     } else {
                   1645:         if (!$uhome) {
                   1646:             if (defined(&domain($udom,'primary'))) {
                   1647:                 $uhome=&domain($udom,'primary');
                   1648:             }
                   1649:         }
                   1650:     } 
                   1651:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1652:         my $items='';
                   1653:         foreach my $item (keys(%$storehash)) {
                   1654:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1655:         }
                   1656:         $items=~s/\&$//;
                   1657:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1658:     } else {
1.860     raeburn  1659:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1660:     }
                   1661: }
                   1662: 
1.1023    raeburn  1663: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1664: sub newput_dom {
1.1023    raeburn  1665:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1666:     my $result;
                   1667:     if (!$udom) {
                   1668:         $udom=$env{'user.domain'};
                   1669:     }
1.1023    raeburn  1670:     if ($udom) {
                   1671:         my $uname = &get_domainconfiguser($udom);
                   1672:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1673:     }
                   1674:     return $result;
                   1675: }
                   1676: 
1.1023    raeburn  1677: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1678: sub del_dom {
1.1023    raeburn  1679:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1680:     if (ref($storearr) eq 'ARRAY') {
                   1681:         if (!$udom) {
                   1682:             $udom=$env{'user.domain'};
                   1683:         }
1.1023    raeburn  1684:         if ($udom) {
                   1685:             my $uname = &get_domainconfiguser($udom); 
                   1686:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1687:         }
                   1688:     }
                   1689: }
                   1690: 
1.1023    raeburn  1691: # ----------------------------------construct domainconfig user for a domain 
                   1692: sub get_domainconfiguser {
                   1693:     my ($udom) = @_;
                   1694:     return $udom.'-domainconfig';
                   1695: }
                   1696: 
1.837     raeburn  1697: sub retrieve_inst_usertypes {
                   1698:     my ($udom) = @_;
                   1699:     my (%returnhash,@order);
1.989     raeburn  1700:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1701:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1702:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1703:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1704:         @order = @{$domdefs{'inststatusorder'}};
                   1705:     } else {
                   1706:         if (defined(&domain($udom,'primary'))) {
                   1707:             my $uhome=&domain($udom,'primary');
                   1708:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1709:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1710:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1711:                 return (\%returnhash,\@order);
                   1712:             }
                   1713:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1714:             my @pairs=split(/\&/,$hashitems);
                   1715:             foreach my $item (@pairs) {
                   1716:                 my ($key,$value)=split(/=/,$item,2);
                   1717:                 $key = &unescape($key);
                   1718:                 next if ($key =~ /^error: 2 /);
                   1719:                 $returnhash{$key}=&thaw_unescape($value);
                   1720:             }
                   1721:             my @esc_order = split(/\&/,$orderitems);
                   1722:             foreach my $item (@esc_order) {
                   1723:                 push(@order,&unescape($item));
                   1724:             }
                   1725:         } else {
                   1726:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1727:         }
                   1728:     }
                   1729:     return (\%returnhash,\@order);
                   1730: }
                   1731: 
1.868     raeburn  1732: sub is_domainimage {
                   1733:     my ($url) = @_;
                   1734:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1735:         if (&domain($1) ne '') {
                   1736:             return '1';
                   1737:         }
                   1738:     }
                   1739:     return;
                   1740: }
                   1741: 
1.899     raeburn  1742: sub inst_directory_query {
                   1743:     my ($srch) = @_;
                   1744:     my $udom = $srch->{'srchdomain'};
                   1745:     my %results;
                   1746:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1747:     my $outcome;
1.899     raeburn  1748:     if ($homeserver ne '') {
1.904     albertel 1749: 	my $queryid=&reply("querysend:instdirsearch:".
                   1750: 			   &escape($srch->{'srchby'}).':'.
                   1751: 			   &escape($srch->{'srchterm'}).':'.
                   1752: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1753: 	my $host=&hostname($homeserver);
                   1754: 	if ($queryid !~/^\Q$host\E\_/) {
                   1755: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1756: 	    return;
                   1757: 	}
                   1758: 	my $response = &get_query_reply($queryid);
                   1759: 	my $maxtries = 5;
                   1760: 	my $tries = 1;
                   1761: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1762: 	    $response = &get_query_reply($queryid);
                   1763: 	    $tries ++;
                   1764: 	}
                   1765: 
                   1766:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1767:             if ($response eq 'unavailable') {
                   1768:                 $outcome = $response;
                   1769:             } else {
                   1770:                 $outcome = 'ok';
                   1771:                 my @matches = split(/\n/,$response);
                   1772:                 foreach my $match (@matches) {
                   1773:                     my ($key,$value) = split(/=/,$match);
                   1774:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1775:                 }
1.899     raeburn  1776:             }
                   1777:         }
                   1778:     }
1.909     raeburn  1779:     return ($outcome,%results);
1.899     raeburn  1780: }
                   1781: 
                   1782: sub usersearch {
                   1783:     my ($srch) = @_;
                   1784:     my $dom = $srch->{'srchdomain'};
                   1785:     my %results;
                   1786:     my %libserv = &all_library();
                   1787:     my $query = 'usersearch';
                   1788:     foreach my $tryserver (keys(%libserv)) {
                   1789:         if (&host_domain($tryserver) eq $dom) {
                   1790:             my $host=&hostname($tryserver);
                   1791:             my $queryid=
1.911     raeburn  1792:                 &reply("querysend:".&escape($query).':'.
                   1793:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1794:                        &escape($srch->{'srchtype'}).':'.
                   1795:                        &escape($srch->{'srchterm'}),$tryserver);
                   1796:             if ($queryid !~/^\Q$host\E\_/) {
                   1797:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1798:                 next;
1.899     raeburn  1799:             }
                   1800:             my $reply = &get_query_reply($queryid);
                   1801:             my $maxtries = 1;
                   1802:             my $tries = 1;
                   1803:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1804:                 $reply = &get_query_reply($queryid);
                   1805:                 $tries ++;
                   1806:             }
                   1807:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1808:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1809:             } else {
1.911     raeburn  1810:                 my @matches;
                   1811:                 if ($reply =~ /\n/) {
                   1812:                     @matches = split(/\n/,$reply);
                   1813:                 } else {
                   1814:                     @matches = split(/\&/,$reply);
                   1815:                 }
1.899     raeburn  1816:                 foreach my $match (@matches) {
                   1817:                     my ($uname,$udom,%userhash);
1.911     raeburn  1818:                     foreach my $entry (split(/:/,$match)) {
                   1819:                         my ($key,$value) =
                   1820:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1821:                         $userhash{$key} = $value;
                   1822:                         if ($key eq 'username') {
                   1823:                             $uname = $value;
                   1824:                         } elsif ($key eq 'domain') {
                   1825:                             $udom = $value;
1.911     raeburn  1826:                         }
1.899     raeburn  1827:                     }
                   1828:                     $results{$uname.':'.$udom} = \%userhash;
                   1829:                 }
                   1830:             }
                   1831:         }
                   1832:     }
                   1833:     return %results;
                   1834: }
                   1835: 
1.912     raeburn  1836: sub get_instuser {
                   1837:     my ($udom,$uname,$id) = @_;
                   1838:     my $homeserver = &domain($udom,'primary');
                   1839:     my ($outcome,%results);
                   1840:     if ($homeserver ne '') {
                   1841:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1842:                            &escape($id).':'.&escape($udom),$homeserver);
                   1843:         my $host=&hostname($homeserver);
                   1844:         if ($queryid !~/^\Q$host\E\_/) {
                   1845:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1846:             return;
                   1847:         }
                   1848:         my $response = &get_query_reply($queryid);
                   1849:         my $maxtries = 5;
                   1850:         my $tries = 1;
                   1851:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1852:             $response = &get_query_reply($queryid);
                   1853:             $tries ++;
                   1854:         }
                   1855:         if (!&error($response) && $response ne 'refused') {
                   1856:             if ($response eq 'unavailable') {
                   1857:                 $outcome = $response;
                   1858:             } else {
                   1859:                 $outcome = 'ok';
                   1860:                 my @matches = split(/\n/,$response);
                   1861:                 foreach my $match (@matches) {
                   1862:                     my ($key,$value) = split(/=/,$match);
                   1863:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1864:                 }
                   1865:             }
                   1866:         }
                   1867:     }
                   1868:     my %userinfo;
                   1869:     if (ref($results{$uname}) eq 'HASH') {
                   1870:         %userinfo = %{$results{$uname}};
                   1871:     } 
                   1872:     return ($outcome,%userinfo);
                   1873: }
                   1874: 
                   1875: sub inst_rulecheck {
1.923     raeburn  1876:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1877:     my %returnhash;
                   1878:     if ($udom ne '') {
                   1879:         if (ref($rules) eq 'ARRAY') {
                   1880:             @{$rules} = map {&escape($_);} (@{$rules});
                   1881:             my $rulestr = join(':',@{$rules});
                   1882:             my $homeserver=&domain($udom,'primary');
                   1883:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1884:                 my $response;
                   1885:                 if ($item eq 'username') {                
                   1886:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1887:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1888:                                               $homeserver));
1.923     raeburn  1889:                 } elsif ($item eq 'id') {
                   1890:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1891:                                               ':'.&escape($id).':'.$rulestr,
                   1892:                                               $homeserver));
1.945     raeburn  1893:                 } elsif ($item eq 'selfcreate') {
                   1894:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1895:                                                &escape($udom).':'.&escape($uname).
                   1896:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1897:                 }
1.912     raeburn  1898:                 if ($response ne 'refused') {
                   1899:                     my @pairs=split(/\&/,$response);
                   1900:                     foreach my $item (@pairs) {
                   1901:                         my ($key,$value)=split(/=/,$item,2);
                   1902:                         $key = &unescape($key);
                   1903:                         next if ($key =~ /^error: 2 /);
                   1904:                         $returnhash{$key}=&thaw_unescape($value);
                   1905:                     }
                   1906:                 }
                   1907:             }
                   1908:         }
                   1909:     }
                   1910:     return %returnhash;
                   1911: }
                   1912: 
                   1913: sub inst_userrules {
1.923     raeburn  1914:     my ($udom,$check) = @_;
1.912     raeburn  1915:     my (%ruleshash,@ruleorder);
                   1916:     if ($udom ne '') {
                   1917:         my $homeserver=&domain($udom,'primary');
                   1918:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1919:             my $response;
                   1920:             if ($check eq 'id') {
                   1921:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1922:                                  $homeserver);
1.943     raeburn  1923:             } elsif ($check eq 'email') {
                   1924:                 $response=&reply('instemailrules:'.&escape($udom),
                   1925:                                  $homeserver);
1.923     raeburn  1926:             } else {
                   1927:                 $response=&reply('instuserrules:'.&escape($udom),
                   1928:                                  $homeserver);
                   1929:             }
1.912     raeburn  1930:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1931:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1932:                 ($response ne 'no_such_host')) {
                   1933:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1934:                 my @pairs=split(/\&/,$hashitems);
                   1935:                 foreach my $item (@pairs) {
                   1936:                     my ($key,$value)=split(/=/,$item,2);
                   1937:                     $key = &unescape($key);
                   1938:                     next if ($key =~ /^error: 2 /);
                   1939:                     $ruleshash{$key}=&thaw_unescape($value);
                   1940:                 }
                   1941:                 my @esc_order = split(/\&/,$orderitems);
                   1942:                 foreach my $item (@esc_order) {
                   1943:                     push(@ruleorder,&unescape($item));
                   1944:                 }
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return (\%ruleshash,\@ruleorder);
                   1949: }
                   1950: 
1.976     raeburn  1951: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1952: 
                   1953: sub get_domain_defaults {
                   1954:     my ($domain) = @_;
                   1955:     my $cachetime = 60*60*24;
                   1956:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1957:     if (defined($cached)) {
                   1958:         if (ref($result) eq 'HASH') {
                   1959:             return %{$result};
                   1960:         }
                   1961:     }
                   1962:     my %domdefaults;
                   1963:     my %domconfig =
1.989     raeburn  1964:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1965:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1966:                                   'coursedefaults','usersessions',
                   1967:                                   'requestauthor'],$domain);
1.943     raeburn  1968:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1969:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1970:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1971:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1972:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1973:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1974:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1975:     } else {
                   1976:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1977:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1978:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1979:     }
1.976     raeburn  1980:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1981:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1982:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1983:         } else {
                   1984:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1985:         } 
1.1172.2.6  raeburn  1986:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1987:         foreach my $item (@usertools) {
                   1988:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1989:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1990:             }
                   1991:         }
                   1992:     }
1.985     raeburn  1993:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1994:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1995:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1996:         }
                   1997:     }
1.1172.2.9  raeburn  1998:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   1999:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2000:     }
1.989     raeburn  2001:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2002:         foreach my $item ('inststatustypes','inststatusorder') {
                   2003:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2004:         }
                   2005:     }
1.1047    raeburn  2006:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2007:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2008:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2009:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2010:         }
                   2011:     }
1.1073    raeburn  2012:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2013:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2014:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2015:         }
                   2016:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2017:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2018:         }
                   2019:     }
1.943     raeburn  2020:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2021:                                   $cachetime);
                   2022:     return %domdefaults;
                   2023: }
                   2024: 
1.344     www      2025: # --------------------------------------------------- Assign a key to a student
                   2026: 
                   2027: sub assign_access_key {
1.364     www      2028: #
                   2029: # a valid key looks like uname:udom#comments
                   2030: # comments are being appended
                   2031: #
1.498     www      2032:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2033:     $kdom=
1.620     albertel 2034:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2035:     $knum=
1.620     albertel 2036:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2037:     $cdom=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2039:     $cnum=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2041:     $udom=$env{'user.name'} unless (defined($udom));
                   2042:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2043:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2044:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2045:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2046:                                                   # assigned to this person
                   2047:                                                   # - this should not happen,
1.345     www      2048:                                                   # unless something went wrong
                   2049:                                                   # the first time around
                   2050: # ready to assign
1.364     www      2051:         $logentry=$1.'; '.$logentry;
1.496     www      2052:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2053:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2054: # key now belongs to user
1.346     www      2055: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2056:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2057:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2058:                 return 'ok';
                   2059:             } else {
                   2060:                 return 
                   2061:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2062: 	    }
                   2063:         } else {
                   2064:             return 'error: Could not assign key, try again later.';
                   2065:         }
1.364     www      2066:     } elsif (!$existing{$ckey}) {
1.345     www      2067: # the key does not exist
                   2068: 	return 'error: The key does not exist';
                   2069:     } else {
                   2070: # the key is somebody else's
                   2071: 	return 'error: The key is already in use';
                   2072:     }
1.344     www      2073: }
                   2074: 
1.364     www      2075: # ------------------------------------------ put an additional comment on a key
                   2076: 
                   2077: sub comment_access_key {
                   2078: #
                   2079: # a valid key looks like uname:udom#comments
                   2080: # comments are being appended
                   2081: #
                   2082:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2083:     $cdom=
1.620     albertel 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2085:     $cnum=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2087:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2088:     if ($existing{$ckey}) {
                   2089:         $existing{$ckey}.='; '.$logentry;
                   2090: # ready to assign
1.367     www      2091:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2092:                                                  $cdom,$cnum) eq 'ok') {
                   2093: 	    return 'ok';
                   2094:         } else {
                   2095: 	    return 'error: Count not store comment.';
                   2096:         }
                   2097:     } else {
                   2098: # the key does not exist
                   2099: 	return 'error: The key does not exist';
                   2100:     }
                   2101: }
                   2102: 
1.344     www      2103: # ------------------------------------------------------ Generate a set of keys
                   2104: 
                   2105: sub generate_access_keys {
1.364     www      2106:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2107:     $cdom=
1.620     albertel 2108:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2109:     $cnum=
1.620     albertel 2110:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2111:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2112:     unless (($cdom) && ($cnum)) { return 0; }
                   2113:     if ($number>10000) { return 0; }
                   2114:     sleep(2); # make sure don't get same seed twice
                   2115:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2116:     my $total=0;
                   2117:     for (my $i=1;$i<=$number;$i++) {
                   2118:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2119:                   sprintf("%lx",int(100000*rand)).'-'.
                   2120:                   sprintf("%lx",int(100000*rand));
                   2121:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2122:        $newkey=~s/0/h/g; # and also 0 and O
                   2123:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2124:        if ($existing{$newkey}) {
                   2125:            $i--;
                   2126:        } else {
1.364     www      2127: 	  if (&put('accesskeys',
                   2128:               { $newkey => '# generated '.localtime().
1.620     albertel 2129:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2130:                            '; '.$logentry },
                   2131: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2132:               $total++;
                   2133: 	  }
                   2134:        }
                   2135:     }
1.620     albertel 2136:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2137:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2138:     return $total;
                   2139: }
                   2140: 
                   2141: # ------------------------------------------------------- Validate an accesskey
                   2142: 
                   2143: sub validate_access_key {
                   2144:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2145:     $cdom=
1.620     albertel 2146:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2147:     $cnum=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2149:     $udom=$env{'user.domain'} unless (defined($udom));
                   2150:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2151:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2152:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2153: }
                   2154: 
                   2155: # ------------------------------------- Find the section of student in a course
1.652     albertel 2156: sub devalidate_getsection_cache {
                   2157:     my ($udom,$unam,$courseid)=@_;
                   2158:     my $hashid="$udom:$unam:$courseid";
                   2159:     &devalidate_cache_new('getsection',$hashid);
                   2160: }
1.298     matthew  2161: 
1.815     albertel 2162: sub courseid_to_courseurl {
                   2163:     my ($courseid) = @_;
                   2164:     #already url style courseid
                   2165:     return $courseid if ($courseid =~ m{^/});
                   2166: 
                   2167:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2168: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2169: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2170: 	return "/$cdom/$cnum";
                   2171:     }
                   2172: 
                   2173:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2174:     if (exists($courseinfo{'num'})) {
                   2175: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2176:     }
                   2177: 
                   2178:     return undef;
                   2179: }
                   2180: 
1.298     matthew  2181: sub getsection {
                   2182:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2183:     my $cachetime=1800;
1.551     albertel 2184: 
                   2185:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2186:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2187:     if (defined($cached)) { return $result; }
                   2188: 
1.298     matthew  2189:     my %Pending; 
                   2190:     my %Expired;
                   2191:     #
                   2192:     # Each role can either have not started yet (pending), be active, 
                   2193:     #    or have expired.
                   2194:     #
                   2195:     # If there is an active role, we are done.
                   2196:     #
                   2197:     # If there is more than one role which has not started yet, 
                   2198:     #     choose the one which will start sooner
                   2199:     # If there is one role which has not started yet, return it.
                   2200:     #
                   2201:     # If there is more than one expired role, choose the one which ended last.
                   2202:     # If there is a role which has expired, return it.
                   2203:     #
1.815     albertel 2204:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2205:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2206:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2207:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2208:         my $section=$1;
                   2209:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2210:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2211:         my $now=time;
1.548     albertel 2212:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2213:             $Expired{$end}=$section;
                   2214:             next;
                   2215:         }
1.548     albertel 2216:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2217:             $Pending{$start}=$section;
                   2218:             next;
                   2219:         }
1.599     albertel 2220:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2221:     }
                   2222:     #
                   2223:     # Presumedly there will be few matching roles from the above
                   2224:     # loop and the sorting time will be negligible.
                   2225:     if (scalar(keys(%Pending))) {
                   2226:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2228:     } 
                   2229:     if (scalar(keys(%Expired))) {
                   2230:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2231:         my $time = pop(@sorted);
1.599     albertel 2232:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2233:     }
1.599     albertel 2234:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2235: }
1.70      www      2236: 
1.599     albertel 2237: sub save_cache {
                   2238:     &purge_remembered();
1.722     albertel 2239:     #&Apache::loncommon::validate_page();
1.620     albertel 2240:     undef(%env);
1.780     albertel 2241:     undef($env_loaded);
1.599     albertel 2242: }
1.452     albertel 2243: 
1.599     albertel 2244: my $to_remember=-1;
                   2245: my %remembered;
                   2246: my %accessed;
                   2247: my $kicks=0;
                   2248: my $hits=0;
1.849     albertel 2249: sub make_key {
                   2250:     my ($name,$id) = @_;
1.872     albertel 2251:     if (length($id) > 65 
                   2252: 	&& length(&escape($id)) > 200) {
                   2253: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2254:     }
1.849     albertel 2255:     return &escape($name.':'.$id);
                   2256: }
                   2257: 
1.599     albertel 2258: sub devalidate_cache_new {
                   2259:     my ($name,$id,$debug) = @_;
                   2260:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2261:     $id=&make_key($name,$id);
1.599     albertel 2262:     $memcache->delete($id);
                   2263:     delete($remembered{$id});
                   2264:     delete($accessed{$id});
                   2265: }
                   2266: 
                   2267: sub is_cached_new {
                   2268:     my ($name,$id,$debug) = @_;
1.849     albertel 2269:     $id=&make_key($name,$id);
1.599     albertel 2270:     if (exists($remembered{$id})) {
1.1133    foxr     2271: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2272: 	$accessed{$id}=[&gettimeofday()];
                   2273: 	$hits++;
                   2274: 	return ($remembered{$id},1);
                   2275:     }
                   2276:     my $value = $memcache->get($id);
                   2277:     if (!(defined($value))) {
                   2278: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2279: 	return (undef,undef);
1.416     albertel 2280:     }
1.599     albertel 2281:     if ($value eq '__undef__') {
                   2282: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2283: 	$value=undef;
                   2284:     }
                   2285:     &make_room($id,$value,$debug);
                   2286:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2287:     return ($value,1);
                   2288: }
                   2289: 
                   2290: sub do_cache_new {
                   2291:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2292:     $id=&make_key($name,$id);
1.599     albertel 2293:     my $setvalue=$value;
                   2294:     if (!defined($setvalue)) {
                   2295: 	$setvalue='__undef__';
                   2296:     }
1.623     albertel 2297:     if (!defined($time) ) {
                   2298: 	$time=600;
                   2299:     }
1.599     albertel 2300:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2301:     my $result = $memcache->set($id,$setvalue,$time);
                   2302:     if (! $result) {
1.872     albertel 2303: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2304: 	$memcache->disconnect_all();
1.872     albertel 2305:     }
1.600     albertel 2306:     # need to make a copy of $value
1.919     albertel 2307:     &make_room($id,$value,$debug);
1.599     albertel 2308:     return $value;
                   2309: }
                   2310: 
                   2311: sub make_room {
                   2312:     my ($id,$value,$debug)=@_;
1.919     albertel 2313: 
                   2314:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2315:                                     : $value;
1.599     albertel 2316:     if ($to_remember<0) { return; }
                   2317:     $accessed{$id}=[&gettimeofday()];
                   2318:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2319:     my $to_kick;
                   2320:     my $max_time=0;
                   2321:     foreach my $other (keys(%accessed)) {
                   2322: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2323: 	    $to_kick=$other;
                   2324: 	    $max_time=&tv_interval($accessed{$other});
                   2325: 	}
                   2326:     }
                   2327:     delete($remembered{$to_kick});
                   2328:     delete($accessed{$to_kick});
                   2329:     $kicks++;
                   2330:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2331:     return;
                   2332: }
                   2333: 
1.599     albertel 2334: sub purge_remembered {
1.604     albertel 2335:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2336:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2337:     undef(%remembered);
                   2338:     undef(%accessed);
1.428     albertel 2339: }
1.70      www      2340: # ------------------------------------- Read an entry from a user's environment
                   2341: 
                   2342: sub userenvironment {
                   2343:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2344:     my $items;
                   2345:     foreach my $item (@what) {
                   2346:         $items.=&escape($item).'&';
                   2347:     }
                   2348:     $items=~s/\&$//;
1.70      www      2349:     my %returnhash=();
1.1009    raeburn  2350:     my $uhome = &homeserver($unam,$udom);
                   2351:     unless ($uhome eq 'no_host') {
                   2352:         my @answer=split(/\&/, 
                   2353:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2354:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2355:             return %returnhash;
                   2356:         }
1.1009    raeburn  2357:         my $i;
                   2358:         for ($i=0;$i<=$#what;$i++) {
                   2359: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2360:         }
1.70      www      2361:     }
                   2362:     return %returnhash;
1.1       albertel 2363: }
                   2364: 
1.617     albertel 2365: # ---------------------------------------------------------- Get a studentphoto
                   2366: sub studentphoto {
                   2367:     my ($udom,$unam,$ext) = @_;
                   2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2369:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2370:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2371:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2372:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2373:             } else {
                   2374:                 my ($result,$perm_reqd)=
1.707     albertel 2375: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2376:                 if ($result eq 'ok') {
                   2377:                     if (!($perm_reqd eq 'yes')) {
                   2378:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2379:                     }
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:     } else {
                   2384:         my ($result,$perm_reqd) = 
1.707     albertel 2385: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2386:         if ($result eq 'ok') {
                   2387:             if (!($perm_reqd eq 'yes')) {
                   2388:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2389:             }
                   2390:         }
                   2391:     }
                   2392:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2393: }
                   2394: 
                   2395: sub retrievestudentphoto {
                   2396:     my ($udom,$unam,$ext,$type) = @_;
                   2397:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2398:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2399:     if ($ret eq 'ok') {
                   2400:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2401:         if ($type eq 'thumbnail') {
                   2402:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2403:         }
                   2404:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2405:         return $tokenurl;
                   2406:     } else {
                   2407:         if ($type eq 'thumbnail') {
                   2408:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2409:         } else { 
                   2410:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2411:         }
1.617     albertel 2412:     }
                   2413: }
                   2414: 
1.263     www      2415: # -------------------------------------------------------------------- New chat
                   2416: 
                   2417: sub chatsend {
1.724     raeburn  2418:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2419:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2421:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2422:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2423: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2424: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2425: }
                   2426: 
                   2427: # ------------------------------------------ Find current version of a resource
                   2428: 
                   2429: sub getversion {
                   2430:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2431:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2432:     return &currentversion(&filelocation('',$fname));
                   2433: }
                   2434: 
                   2435: sub currentversion {
                   2436:     my $fname=shift;
                   2437:     my $author=$fname;
                   2438:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2439:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2440:     my $home=&homeserver($uname,$udom);
1.292     www      2441:     if ($home eq 'no_host') { 
                   2442:         return -1; 
                   2443:     }
1.1112    www      2444:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2445:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2446: 	return -1;
                   2447:     }
1.1112    www      2448:     return $answer;
1.263     www      2449: }
                   2450: 
1.1111    www      2451: #
                   2452: # Return special version number of resource if set by override, empty otherwise
                   2453: #
                   2454: sub usedversion {
                   2455:     my $fname=shift;
                   2456:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2457:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2458:     if ($urlversion) { return $urlversion; }
                   2459:     return '';
                   2460: }
                   2461: 
1.1       albertel 2462: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2463: 
1.1       albertel 2464: sub subscribe {
                   2465:     my $fname=shift;
1.761     raeburn  2466:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2467:     $fname=~s/[\n\r]//g;
1.1       albertel 2468:     my $author=$fname;
                   2469:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2470:     my ($udom,$uname)=split(/\//,$author);
                   2471:     my $home=homeserver($uname,$udom);
1.335     albertel 2472:     if ($home eq 'no_host') {
                   2473:         return 'not_found';
1.1       albertel 2474:     }
                   2475:     my $answer=reply("sub:$fname",$home);
1.64      www      2476:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2477: 	$answer.=' by '.$home;
                   2478:     }
1.1       albertel 2479:     return $answer;
                   2480: }
                   2481:     
1.8       www      2482: # -------------------------------------------------------------- Replicate file
                   2483: 
                   2484: sub repcopy {
                   2485:     my $filename=shift;
1.23      www      2486:     $filename=~s/\/+/\//g;
1.1142    raeburn  2487:     my $londocroot = $perlvar{'lonDocRoot'};
                   2488:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2489:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2490:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2491: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2492: 	return &repcopy_userfile($filename);
                   2493:     }
1.532     albertel 2494:     $filename=~s/[\n\r]//g;
1.8       www      2495:     my $transname="$filename.in.transfer";
1.828     www      2496: # FIXME: this should flock
1.607     raeburn  2497:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2498:     my $remoteurl=subscribe($filename);
1.64      www      2499:     if ($remoteurl =~ /^con_lost by/) {
                   2500: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2501:            return 'unavailable';
1.8       www      2502:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2503: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2504: 	   return 'not_found';
1.64      www      2505:     } elsif ($remoteurl =~ /^rejected by/) {
                   2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2507:            return 'forbidden';
1.20      www      2508:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2509:            return 'ok';
1.8       www      2510:     } else {
1.290     www      2511:         my $author=$filename;
                   2512:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:         my ($udom,$uname)=split(/\//,$author);
                   2514:         my $home=homeserver($uname,$udom);
                   2515:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2516:            my @parts=split(/\//,$filename);
                   2517:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2518:            if ($path ne "$londocroot/res") {
1.8       www      2519:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2520: 	       return 'bad_request';
1.8       www      2521:            }
                   2522:            my $count;
                   2523:            for ($count=5;$count<$#parts;$count++) {
                   2524:                $path.="/$parts[$count]";
                   2525:                if ((-e $path)!=1) {
                   2526: 		   mkdir($path,0777);
                   2527:                }
                   2528:            }
                   2529:            my $ua=new LWP::UserAgent;
                   2530:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2531:            my $response=$ua->request($request,$transname);
                   2532:            if ($response->is_error()) {
                   2533: 	       unlink($transname);
                   2534:                my $message=$response->status_line;
1.672     albertel 2535:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2536:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2537:                return 'unavailable';
1.8       www      2538:            } else {
1.16      www      2539: 	       if ($remoteurl!~/\.meta$/) {
                   2540:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2541:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2542:                   if ($mresponse->is_error()) {
                   2543: 		      unlink($filename.'.meta');
                   2544:                       &logthis(
1.672     albertel 2545:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2546:                   }
                   2547: 	       }
1.8       www      2548:                rename($transname,$filename);
1.607     raeburn  2549:                return 'ok';
1.8       www      2550:            }
1.290     www      2551:        }
1.8       www      2552:     }
1.330     www      2553: }
                   2554: 
                   2555: # ------------------------------------------------ Get server side include body
                   2556: sub ssi_body {
1.381     albertel 2557:     my ($filelink,%form)=@_;
1.606     matthew  2558:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2559:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2560:     }
1.953     www      2561:     my $output='';
                   2562:     my $response;
1.980     raeburn  2563:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2564:        ($output,$response)=&externalssi($filelink);
1.953     www      2565:     } else {
1.1004    droeschl 2566:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2567:        $filelink .= 'inhibitmenu=yes';
1.953     www      2568:        ($output,$response)=&ssi($filelink,%form);
                   2569:     }
1.778     albertel 2570:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2571:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2572:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2573:     if (wantarray) {
                   2574:         return ($output, $response);
                   2575:     } else {
                   2576:         return $output;
                   2577:     }
1.8       www      2578: }
                   2579: 
1.15      www      2580: # --------------------------------------------------------- Server Side Include
                   2581: 
1.782     albertel 2582: sub absolute_url {
                   2583:     my ($host_name) = @_;
                   2584:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2585:     if ($host_name eq '') {
                   2586: 	$host_name = $ENV{'SERVER_NAME'};
                   2587:     }
                   2588:     return $protocol.$host_name;
                   2589: }
                   2590: 
1.942     foxr     2591: #
                   2592: #   Server side include.
                   2593: # Parameters:
                   2594: #  fn     Possibly encrypted resource name/id.
                   2595: #  form   Hash that describes how the rendering should be done
                   2596: #         and other things.
1.944     foxr     2597: # Returns:
1.950     raeburn  2598: #   Scalar context: The content of the response.
                   2599: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2600: #     
1.15      www      2601: sub ssi {
                   2602: 
1.944     foxr     2603:     my ($fn,%form)=@_;
1.15      www      2604:     my $ua=new LWP::UserAgent;
1.23      www      2605:     my $request;
1.711     albertel 2606: 
                   2607:     $form{'no_update_last_known'}=1;
1.895     albertel 2608:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2609:     if (%form) {
1.782     albertel 2610:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2611:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2612:     } else {
1.782     albertel 2613:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2614:     }
                   2615: 
1.15      www      2616:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2617:     my $response= $ua->request($request);
1.944     foxr     2618:     if (wantarray) {
1.1172.2.3  raeburn  2619: 	return ($response->content, $response);
1.944     foxr     2620:     } else {
1.1172.2.3  raeburn  2621: 	return $response->content;
1.942     foxr     2622:     }
1.324     www      2623: }
                   2624: 
                   2625: sub externalssi {
                   2626:     my ($url)=@_;
                   2627:     my $ua=new LWP::UserAgent;
                   2628:     my $request=new HTTP::Request('GET',$url);
                   2629:     my $response=$ua->request($request);
1.954     raeburn  2630:     if (wantarray) {
                   2631:         return ($response->content, $response);
                   2632:     } else {
                   2633:         return $response->content;
                   2634:     }
1.15      www      2635: }
1.254     www      2636: 
1.492     albertel 2637: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2638: 
                   2639: sub allowuploaded {
                   2640:     my ($srcurl,$url)=@_;
                   2641:     $url=&clutter(&declutter($url));
                   2642:     my $dir=$url;
                   2643:     $dir=~s/\/[^\/]+$//;
                   2644:     my %httpref=();
                   2645:     my $httpurl=&hreflocation('',$url);
                   2646:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2647:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2648: }
1.477     raeburn  2649: 
1.1172.2.13  raeburn  2650: #
                   2651: # Determine if the current user should be able to edit a particular resource,
                   2652: # when viewing in course context.
                   2653: # (a) When viewing resource used to determine if "Edit" item is included in
                   2654: #     Functions.
                   2655: # (b) When displaying folder contents in course editor, used to determine if
                   2656: #     "Edit" link will be displayed alongside resource.
                   2657: #
                   2658: #  input: six args -- filename (decluttered), course number, course domain,
                   2659: #                   url, symb (if registered) and group (if this is a group
                   2660: #                   item -- e.g., bulletin board, group page etc.).
                   2661: #  output: array of five scalars --
                   2662: #          $cfile -- url for file editing if editable on current server
                   2663: #          $home -- homeserver of resource (i.e., for author if published,
                   2664: #                                           or course if uploaded.).
                   2665: #          $switchserver --  1 if server switch will be needed.
                   2666: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2667: #          $forceview -- 1 if icon/link should be to go to view mode
                   2668: #
                   2669: 
                   2670: sub can_edit_resource {
                   2671:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2672:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2673: #
                   2674: # For aboutme pages user can only edit his/her own.
                   2675: #
                   2676:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2677:         my ($sdom,$sname) = ($1,$2);
                   2678:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2679:             $home = $env{'user.home'};
                   2680:             $cfile = $resurl;
                   2681:             if ($env{'form.forceedit'}) {
                   2682:                 $forceview = 1;
                   2683:             } else {
                   2684:                 $forceedit = 1;
                   2685:             }
                   2686:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2687:         } else {
                   2688:             return;
                   2689:         }
                   2690:     }
                   2691: 
                   2692:     if ($env{'request.course.id'}) {
                   2693:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2694:         if ($group ne '') {
                   2695: # if this is a group homepage or group bulletin board, check group privs
                   2696:             my $allowed = 0;
                   2697:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2698:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2699:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2700:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2701:                     $allowed = 1;
                   2702:                 }
                   2703:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2704:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2705:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2706:                     $allowed = 1;
                   2707:                 }
                   2708:             }
                   2709:             if ($allowed) {
                   2710:                 $home=&homeserver($cnum,$cdom);
                   2711:                 if ($env{'form.forceedit'}) {
                   2712:                     $forceview = 1;
                   2713:                 } else {
                   2714:                     $forceedit = 1;
                   2715:                 }
                   2716:                 $cfile = $resurl;
                   2717:             } else {
                   2718:                 return;
                   2719:             }
                   2720:         } else {
1.1172.2.15  raeburn  2721:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2722:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2723:                     return;
                   2724:                 }
                   2725:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2726: #
                   2727: # No edit allowed where CC has switched to student role.
                   2728: #
                   2729:                 return;
                   2730:             }
                   2731:         }
                   2732:     }
                   2733: 
                   2734:     if ($file ne '') {
                   2735:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2736:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2737:                 $uploaded = 1;
                   2738:                 $incourse = 1;
                   2739:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2740:                     $cfile = &hreflocation('',$file);
                   2741:                     if ($env{'form.forceedit'}) {
                   2742:                         $forceview = 1;
                   2743:                     } else {
                   2744:                         $forceedit = 1;
                   2745:                     }
                   2746:                 }
                   2747:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2748:                 $incourse = 1;
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2756:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2757:                     $incourse = 1;
                   2758:                     if ($env{'form.forceedit'}) {
                   2759:                         $forceview = 1;
                   2760:                     } else {
                   2761:                         $forceedit = 1;
                   2762:                     }
                   2763:                     $cfile = $resurl;
                   2764:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2765:                     $incourse = 1;
                   2766:                     $cfile = $resurl.'/smpedit';
                   2767:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2768:                     $incourse = 1;
                   2769:                     if ($env{'form.forceedit'}) {
                   2770:                         $forceview = 1;
                   2771:                     } else {
                   2772:                         $forceedit = 1;
                   2773:                     }
                   2774:                     $cfile = $resurl;
1.1172.2.15  raeburn  2775:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2776:                     $incourse = 1;
                   2777:                     if ($env{'form.forceedit'}) {
                   2778:                         $forceview = 1;
                   2779:                     } else {
                   2780:                         $forceedit = 1;
                   2781:                     }
                   2782:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2783:                 }
                   2784:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2785:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2786:                 if (&is_on_map($template)) {
                   2787:                     $incourse = 1;
                   2788:                     $forceview = 1;
                   2789:                     $cfile = $template;
                   2790:                 }
                   2791:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2792:                     $incourse = 1;
                   2793:                     if ($env{'form.forceedit'}) {
                   2794:                         $forceview = 1;
                   2795:                     } else {
                   2796:                         $forceedit = 1;
                   2797:                     }
                   2798:                     $cfile = $resurl;
                   2799:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2800:                 $incourse = 1;
                   2801:                 $forceview = 1;
                   2802:                 if ($symb) {
                   2803:                     my ($map,$id,$res)=&decode_symb($symb);
                   2804:                     $env{'request.symb'} = $symb;
                   2805:                     $cfile = &clutter($res);
                   2806:                 } else {
                   2807:                     $cfile = $env{'form.suppurl'};
                   2808:                     $cfile =~ s{^http://}{};
                   2809:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2810:                 }
                   2811:             }
                   2812:         }
                   2813:         if ($uploaded || $incourse) {
                   2814:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2815:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2816:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2817:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2818:             # Check that the user has permission to edit this resource
                   2819:             my $setpriv = 1;
                   2820:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2821:             if (defined($cfudom)) {
                   2822:                 $home=&homeserver($cfuname,$cfudom);
                   2823:                 $cfile=$file;
                   2824:             }
                   2825:         }
                   2826:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2827:             (($home ne '') && ($home ne 'no_host'))) {
                   2828:             my @ids=&current_machine_ids();
                   2829:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2830:                 $switchserver=1;
                   2831:             }
                   2832:         }
                   2833:     }
                   2834:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2835: }
                   2836: 
                   2837: sub is_course_upload {
                   2838:     my ($file,$cnum,$cdom) = @_;
                   2839:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2840:     $uploadpath =~ s{^\/}{};
                   2841:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2842:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2843:         return 1;
                   2844:     }
                   2845:     return;
                   2846: }
                   2847: 
                   2848: sub in_course {
                   2849:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2850:     if ($hideprivileged) {
                   2851:         my $skipuser;
                   2852:         if (&privileged($uname,$udom)) {
                   2853:             $skipuser = 1;
                   2854:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2855:             if ($coursehash{'nothideprivileged'}) {
                   2856:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2857:                     my $user;
                   2858:                     if ($item =~ /:/) {
                   2859:                         $user = $item;
                   2860:                     } else {
                   2861:                         $user = join(':',split(/[\@]/,$item));
                   2862:                     }
                   2863:                     if ($user eq $uname.':'.$udom) {
                   2864:                         undef($skipuser);
                   2865:                         last;
                   2866:                     }
                   2867:                 }
                   2868:             }
                   2869:             if ($skipuser) {
                   2870:                 return 0;
                   2871:             }
                   2872:         }
                   2873:     }
                   2874:     $type ||= 'any';
                   2875:     if (!defined($cdom) || !defined($cnum)) {
                   2876:         my $cid  = $env{'request.course.id'};
                   2877:         $cdom = $env{'course.'.$cid.'.domain'};
                   2878:         $cnum = $env{'course.'.$cid.'.num'};
                   2879:     }
                   2880:     my $typesref;
                   2881:     if (($type eq 'any') || ($type eq 'all')) {
                   2882:         $typesref = ['active','previous','future'];
                   2883:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2884:         $typesref = [$type];
                   2885:     }
                   2886:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2887:                               $typesref,undef,[$cdom]);
                   2888:     my ($tmp) = keys(%roles);
                   2889:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2890:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2891:     if (@course_roles > 0) {
                   2892:         return 1;
                   2893:     }
                   2894:     return 0;
                   2895: }
                   2896: 
1.478     albertel 2897: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2898: # input: action, courseID, current domain, intended
1.637     raeburn  2899: #        path to file, source of file, instruction to parse file for objects,
                   2900: #        ref to hash for embedded objects,
                   2901: #        ref to hash for codebase of java objects.
1.1095    raeburn  2902: #        reference to scalar to accommodate mime type determined
                   2903: #          from File::MMagic if $parser = parse.
1.637     raeburn  2904: #
1.485     raeburn  2905: # output: url to file (if action was uploaddoc), 
                   2906: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2907: #
1.478     albertel 2908: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2909: # course.
1.477     raeburn  2910: #
1.478     albertel 2911: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2912: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2913: #          course's home server.
1.477     raeburn  2914: #
1.478     albertel 2915: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2916: #          be copied from $source (current location) to 
                   2917: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2918: #         and will then be copied to
                   2919: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2920: #         course's home server.
1.485     raeburn  2921: #
1.481     raeburn  2922: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2923: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2924: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2925: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2926: #         in course's home server.
1.637     raeburn  2927: #
1.477     raeburn  2928: 
                   2929: sub process_coursefile {
1.1095    raeburn  2930:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2931:         $mimetype)=@_;
1.477     raeburn  2932:     my $fetchresult;
1.638     albertel 2933:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2934:     if ($action eq 'propagate') {
1.638     albertel 2935:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2936: 			     $home);
1.481     raeburn  2937:     } else {
1.477     raeburn  2938:         my $fpath = '';
                   2939:         my $fname = $file;
1.478     albertel 2940:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2941:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2942:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2943:         if ($action eq 'copy') {
                   2944:             if ($source eq '') {
                   2945:                 $fetchresult = 'no source file';
                   2946:                 return $fetchresult;
                   2947:             } else {
                   2948:                 my $destination = $filepath.'/'.$fname;
                   2949:                 rename($source,$destination);
                   2950:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2951:                                  $home);
1.481     raeburn  2952:             }
                   2953:         } elsif ($action eq 'uploaddoc') {
                   2954:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2955:             print $fh $env{'form.'.$source};
1.481     raeburn  2956:             close($fh);
1.637     raeburn  2957:             if ($parser eq 'parse') {
1.1024    raeburn  2958:                 my $mm = new File::MMagic;
1.1095    raeburn  2959:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2960:                 if ($type eq 'text/html') {
1.1024    raeburn  2961:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2962:                     unless ($parse_result eq 'ok') {
                   2963:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2964:                     }
1.637     raeburn  2965:                 }
1.1095    raeburn  2966:                 if (ref($mimetype)) {
                   2967:                     $$mimetype = $type;
                   2968:                 } 
1.637     raeburn  2969:             }
1.477     raeburn  2970:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2971:                                  $home);
1.481     raeburn  2972:             if ($fetchresult eq 'ok') {
                   2973:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2974:             } else {
                   2975:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2976:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2977:                 return '/adm/notfound.html';
                   2978:             }
1.477     raeburn  2979:         }
                   2980:     }
1.485     raeburn  2981:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2982:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2983:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2984:     }
                   2985:     return $fetchresult;
                   2986: }
                   2987: 
1.637     raeburn  2988: sub build_filepath {
                   2989:     my ($fpath) = @_;
                   2990:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2991:     unless ($fpath eq '') {
                   2992:         my @parts=split('/',$fpath);
                   2993:         foreach my $part (@parts) {
                   2994:             $filepath.= '/'.$part;
                   2995:             if ((-e $filepath)!=1) {
                   2996:                 mkdir($filepath,0777);
                   2997:             }
                   2998:         }
                   2999:     }
                   3000:     return $filepath;
                   3001: }
                   3002: 
                   3003: sub store_edited_file {
1.638     albertel 3004:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3005:     my $file = $primary_url;
                   3006:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3007:     my $fpath = '';
                   3008:     my $fname = $file;
                   3009:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3010:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3011:     my $filepath = &build_filepath($fpath);
                   3012:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3013:     print $fh $content;
                   3014:     close($fh);
1.638     albertel 3015:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3016:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3017: 			  $home);
1.637     raeburn  3018:     if ($$fetchresult eq 'ok') {
                   3019:         return '/uploaded/'.$fpath.'/'.$fname;
                   3020:     } else {
1.638     albertel 3021:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3022: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3023:         return '/adm/notfound.html';
                   3024:     }
                   3025: }
                   3026: 
1.531     albertel 3027: sub clean_filename {
1.831     albertel 3028:     my ($fname,$args)=@_;
1.315     www      3029: # Replace Windows backslashes by forward slashes
1.257     www      3030:     $fname=~s/\\/\//g;
1.831     albertel 3031:     if (!$args->{'keep_path'}) {
                   3032:         # Get rid of everything but the actual filename
                   3033: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3034:     }
1.315     www      3035: # Replace spaces by underscores
                   3036:     $fname=~s/\s+/\_/g;
                   3037: # Replace all other weird characters by nothing
1.831     albertel 3038:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3039: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3040: # numbers
                   3041:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3042:     return $fname;
                   3043: }
1.1051    raeburn  3044: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3045: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3046: # image with the same aspect ratio as the original, but with dimensions which do 
                   3047: # not exceed $resizewidth and $resizeheight.
                   3048:  
1.984     neumanie 3049: sub resizeImage {
1.1051    raeburn  3050:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3051:     my $ima = Image::Magick->new;
                   3052:     my $resized;
                   3053:     if (-e $img_path) {
                   3054:         $ima->Read($img_path);
                   3055:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3056:             my $width = $ima->Get('width');
                   3057:             my $height = $ima->Get('height');
                   3058:             if ($width > $resizewidth) {
                   3059: 	        my $factor = $width/$resizewidth;
                   3060:                 my $newheight = $height/$factor;
                   3061:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3062:                 $resized = 1;
                   3063:             }
                   3064:         }
                   3065:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3066:             my $width = $ima->Get('width');
                   3067:             my $height = $ima->Get('height');
                   3068:             if ($height > $resizeheight) {
                   3069:                 my $factor = $height/$resizeheight;
                   3070:                 my $newwidth = $width/$factor;
                   3071:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3072:                 $resized = 1;
                   3073:             }
                   3074:         }
                   3075:         if ($resized) {
                   3076:             $ima->Write($img_path);
                   3077:         }
                   3078:     }
                   3079:     return;
1.977     amueller 3080: }
                   3081: 
1.608     albertel 3082: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3083: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3084: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3085: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3086: #                                    canceloverwrite, or ''. 
                   3087: #                   if 'coursedoc': upload to the current course
                   3088: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3089: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3090: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3091: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3092: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3093: #        $allfiles - reference to hash for embedded objects
                   3094: #        $codebase - reference to hash for codebase of java objects
                   3095: #        $desuname - username for permanent storage of uploaded file
                   3096: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3097: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3098: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3099: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3100: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3101: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3102: #                    from File::MMagic.
1.858     raeburn  3103: # 
1.686     albertel 3104: # output: url of file in userspace, or error: <message> 
                   3105: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3106: 
1.531     albertel 3107: sub userfileupload {
1.1090    raeburn  3108:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3109:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3110:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3111:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3112:     $fname=&clean_filename($fname);
1.1090    raeburn  3113:     # See if there is anything left
1.257     www      3114:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3115:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3116:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3117:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3118:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3119:         my $now = time;
1.1090    raeburn  3120:         my $filepath;
1.1095    raeburn  3121:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3122:              $filepath = 'tmp/helprequests/'.$now;
                   3123:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3124:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3125:                          '_'.$env{'user.domain'}.'/pending';
                   3126:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3127:             my ($docuname,$docudom);
                   3128:             if ($destudom) {
                   3129:                 $docudom = $destudom;
                   3130:             } else {
                   3131:                 $docudom = $env{'user.domain'};
                   3132:             }
                   3133:             if ($destuname) {
                   3134:                 $docuname = $destuname;
                   3135:             } else {
                   3136:                 $docuname = $env{'user.name'};
                   3137:             }
                   3138:             if (exists($env{'form.group'})) {
                   3139:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3140:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3141:             }
                   3142:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3143:             if ($context eq 'canceloverwrite') {
                   3144:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3145:                 if (-e  $tempfile) {
                   3146:                     my @info = stat($tempfile);
                   3147:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3148:                         unlink($tempfile);
                   3149:                     }
                   3150:                 }
                   3151:                 return;
1.523     raeburn  3152:             }
                   3153:         }
1.1090    raeburn  3154:         # Create the directory if not present
1.741     raeburn  3155:         my @parts=split(/\//,$filepath);
                   3156:         my $fullpath = $perlvar{'lonDaemons'};
                   3157:         for (my $i=0;$i<@parts;$i++) {
                   3158:             $fullpath .= '/'.$parts[$i];
                   3159:             if ((-e $fullpath)!=1) {
                   3160:                 mkdir($fullpath,0777);
                   3161:             }
                   3162:         }
                   3163:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3164:         print $fh $env{'form.'.$formname};
                   3165:         close($fh);
1.1090    raeburn  3166:         if ($context eq 'existingfile') {
                   3167:             my @info = stat($fullpath.'/'.$fname);
                   3168:             return ($fullpath.'/'.$fname,$info[9]);
                   3169:         } else {
                   3170:             return $fullpath.'/'.$fname;
                   3171:         }
1.523     raeburn  3172:     }
1.995     raeburn  3173:     if ($subdir eq 'scantron') {
                   3174:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3175:     } else {
1.995     raeburn  3176:         $fname="$subdir/$fname";
                   3177:     }
1.1090    raeburn  3178:     if ($context eq 'coursedoc') {
1.638     albertel 3179: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3180: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3181:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3182:             return &finishuserfileupload($docuname,$docudom,
                   3183: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3184: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3185:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3186:         } else {
1.1172.2.21! raeburn  3187:             if ($env{'form.folder'}) {
        !          3188:                 $fname=$env{'form.folder'}.'/'.$fname;
        !          3189:             }
1.638     albertel 3190:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3191: 				       $fname,$formname,$parser,
1.1095    raeburn  3192: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3193:         }
1.719     banghart 3194:     } elsif (defined($destuname)) {
                   3195:         my $docuname=$destuname;
                   3196:         my $docudom=$destudom;
1.860     raeburn  3197: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3198: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3199:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3200:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3201:     } else {
1.638     albertel 3202:         my $docuname=$env{'user.name'};
                   3203:         my $docudom=$env{'user.domain'};
1.714     raeburn  3204:         if (exists($env{'form.group'})) {
                   3205:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3206:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3207:         }
1.860     raeburn  3208: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3209: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3210:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3211:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3212:     }
1.271     www      3213: }
                   3214: 
                   3215: sub finishuserfileupload {
1.860     raeburn  3216:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3217:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3218:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3219:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3220:   
1.860     raeburn  3221:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3222:     $file=$fname;
                   3223:     if ($fname=~m|/|) {
                   3224:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3225: 	$path.=$fnamepath.'/';
                   3226:     }
1.259     www      3227:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3228:     my $count;
                   3229:     for ($count=4;$count<=$#parts;$count++) {
                   3230:         $filepath.="/$parts[$count]";
                   3231:         if ((-e $filepath)!=1) {
                   3232: 	    mkdir($filepath,0777);
                   3233:         }
                   3234:     }
1.984     neumanie 3235: 
1.258     www      3236: # Save the file
                   3237:     {
1.701     albertel 3238: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3239: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3240: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3241: 	    return '/adm/notfound.html';
                   3242: 	}
1.1090    raeburn  3243:         if ($context eq 'overwrite') {
1.1117    foxr     3244:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3245:             my $target = $filepath.'/'.$file;
                   3246:             if (-e $source) {
                   3247:                 my @info = stat($source);
                   3248:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3249:                     unless (&File::Copy::move($source,$target)) {
                   3250:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3251:                         return "Moving from $source failed";
                   3252:                     }
                   3253:                 } else {
                   3254:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3255:                 }
                   3256:             } else {
                   3257:                 return "Temporary file: $source missing";
                   3258:             }
                   3259:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3260: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3261: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3262: 	    return '/adm/notfound.html';
                   3263: 	}
1.570     albertel 3264: 	close(FH);
1.1051    raeburn  3265:         if ($resizewidth && $resizeheight) {
                   3266:             my $mm = new File::MMagic;
                   3267:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3268:             if ($mime_type =~ m{^image/}) {
                   3269: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3270:             }  
1.977     amueller 3271: 	}
1.258     www      3272:     }
1.1152    raeburn  3273:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3274:         if (ref($mimetype)) {
                   3275:             if ($$mimetype eq '') {
                   3276:                 my $mm = new File::MMagic;
                   3277:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3278:                 $$mimetype = $type;
                   3279:             }
                   3280:         }
                   3281:     }
1.637     raeburn  3282:     if ($parser eq 'parse') {
1.1152    raeburn  3283:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3284:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3285:                                                        $allfiles,$codebase);
                   3286:             unless ($parse_result eq 'ok') {
                   3287:                 &logthis('Failed to parse '.$filepath.$file.
                   3288: 	   	         ' for embedded media: '.$parse_result); 
                   3289:             }
1.637     raeburn  3290:         }
                   3291:     }
1.860     raeburn  3292:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3293:         my $input = $filepath.'/'.$file;
                   3294:         my $output = $filepath.'/'.'tn-'.$file;
                   3295:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3296:         system("convert -sample $thumbsize $input $output");
                   3297:         if (-e $filepath.'/'.'tn-'.$file) {
                   3298:             $fetchthumb  = 1; 
                   3299:         }
                   3300:     }
1.858     raeburn  3301:  
1.259     www      3302: # Notify homeserver to grep it
                   3303: #
1.984     neumanie 3304:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3305:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3306:     if ($fetchresult eq 'ok') {
1.860     raeburn  3307:         if ($fetchthumb) {
                   3308:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3309:             if ($thumbresult ne 'ok') {
                   3310:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3311:                          $docuhome.': '.$thumbresult);
                   3312:             }
                   3313:         }
1.259     www      3314: #
1.258     www      3315: # Return the URL to it
1.494     albertel 3316:         return '/uploaded/'.$path.$file;
1.263     www      3317:     } else {
1.494     albertel 3318:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3319: 		 ': '.$fetchresult);
1.263     www      3320:         return '/adm/notfound.html';
1.858     raeburn  3321:     }
1.493     albertel 3322: }
                   3323: 
1.637     raeburn  3324: sub extract_embedded_items {
1.961     raeburn  3325:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3326:     my @state = ();
1.1164    raeburn  3327:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3328:     my %javafiles = (
                   3329:                       codebase => '',
                   3330:                       code => '',
                   3331:                       archive => ''
                   3332:                     );
                   3333:     my %mediafiles = (
                   3334:                       src => '',
                   3335:                       movie => '',
                   3336:                      );
1.648     raeburn  3337:     my $p;
                   3338:     if ($content) {
                   3339:         $p = HTML::LCParser->new($content);
                   3340:     } else {
1.961     raeburn  3341:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3342:     }
1.641     albertel 3343:     while (my $t=$p->get_token()) {
1.640     albertel 3344: 	if ($t->[0] eq 'S') {
                   3345: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3346: 	    push(@state, $tagname);
1.648     raeburn  3347:             if (lc($tagname) eq 'allow') {
                   3348:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3349:             }
1.640     albertel 3350: 	    if (lc($tagname) eq 'img') {
                   3351: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3352: 	    }
1.886     albertel 3353: 	    if (lc($tagname) eq 'a') {
                   3354: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3355: 	    }
1.645     raeburn  3356:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3357:                 my $src;
1.645     raeburn  3358:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3359:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3360:                 } else {
1.1164    raeburn  3361:                     if ($attr->{'src'} ne '') {
                   3362:                         $src = $attr->{'src'};
                   3363:                         &add_filetype($allfiles,$src,'src');
                   3364:                     }
                   3365:                 }
                   3366:                 my $text = $p->get_trimmed_text();
                   3367:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3368:                     my @swfargs = split(/,/,$1);
                   3369:                     foreach my $item (@swfargs) {
                   3370:                         $item =~ s/["']//g;
                   3371:                         $item =~ s/^\s+//;
                   3372:                         $item =~ s/\s+$//;
                   3373:                     }
                   3374:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3375:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3376:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3377:                         } else {
                   3378:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3379:                         }
                   3380:                     }
1.645     raeburn  3381:                 }
                   3382:             }
                   3383:             if (lc($tagname) eq 'link') {
                   3384:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3385:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3386:                 }
                   3387:             }
1.640     albertel 3388: 	    if (lc($tagname) eq 'object' ||
                   3389: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3390: 		foreach my $item (keys(%javafiles)) {
                   3391: 		    $javafiles{$item} = '';
                   3392: 		}
1.1164    raeburn  3393:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3394:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3395:                 }
1.640     albertel 3396: 	    }
                   3397: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3398: 		my $name = lc($attr->{'name'});
                   3399: 		foreach my $item (keys(%javafiles)) {
                   3400: 		    if ($name eq $item) {
                   3401: 			$javafiles{$item} = $attr->{'value'};
                   3402: 			last;
                   3403: 		    }
                   3404: 		}
1.1164    raeburn  3405:                 my $pathfrom;
1.640     albertel 3406: 		foreach my $item (keys(%mediafiles)) {
                   3407: 		    if ($name eq $item) {
1.1164    raeburn  3408:                         $pathfrom = $attr->{'value'};
                   3409:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3410: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3411: 			last;
                   3412: 		    }
                   3413: 		}
1.1164    raeburn  3414:                 if ($name eq 'flashvars') {
                   3415:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3416:                 }
                   3417:                 if ($pathfrom ne '') {
                   3418:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3419:                                          $pathfrom);
                   3420:                 }
1.640     albertel 3421: 	    }
                   3422: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3423: 		foreach my $item (keys(%javafiles)) {
                   3424: 		    if ($attr->{$item}) {
                   3425: 			$javafiles{$item} = $attr->{$item};
                   3426: 			last;
                   3427: 		    }
                   3428: 		}
                   3429: 		foreach my $item (keys(%mediafiles)) {
                   3430: 		    if ($attr->{$item}) {
                   3431: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3432: 			last;
                   3433: 		    }
                   3434: 		}
1.1164    raeburn  3435:                 if (lc($tagname) eq 'embed') {
                   3436:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3437:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3438:                                              $attr->{'src'});
                   3439:                     }
                   3440:                 }
1.640     albertel 3441: 	    }
1.1164    raeburn  3442:             if ($t->[4] =~ m{/>$}) {
                   3443:                 pop(@state);  
                   3444:             }
1.640     albertel 3445: 	} elsif ($t->[0] eq 'E') {
                   3446: 	    my ($tagname) = ($t->[1]);
                   3447: 	    if ($javafiles{'codebase'} ne '') {
                   3448: 		$javafiles{'codebase'} .= '/';
                   3449: 	    }  
                   3450: 	    if (lc($tagname) eq 'applet' ||
                   3451: 		lc($tagname) eq 'object' ||
                   3452: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3453: 		) {
                   3454: 		foreach my $item (keys(%javafiles)) {
                   3455: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3456: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3457: 			&add_filetype($allfiles,$file,$item);
                   3458: 		    }
                   3459: 		}
                   3460: 	    } 
                   3461: 	    pop @state;
                   3462: 	}
                   3463:     }
1.1164    raeburn  3464:     foreach my $id (sort(keys(%flashvars))) {
                   3465:         if ($shockwave{$id} ne '') {
                   3466:             my @pairs = split(/\&/,$flashvars{$id});
                   3467:             foreach my $pair (@pairs) {
                   3468:                 my ($key,$value) = split(/\=/,$pair);
                   3469:                 if ($key eq 'thumb') {
                   3470:                     &add_filetype($allfiles,$value,$key);
                   3471:                 } elsif ($key eq 'content') {
                   3472:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3473:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3474:                     if ($ext ne '') {
                   3475:                         &add_filetype($allfiles,$path.$value,$ext);
                   3476:                     }
                   3477:                 }
                   3478:             }
                   3479:         }
                   3480:     }
1.637     raeburn  3481:     return 'ok';
                   3482: }
                   3483: 
1.639     albertel 3484: sub add_filetype {
                   3485:     my ($allfiles,$file,$type)=@_;
                   3486:     if (exists($allfiles->{$file})) {
                   3487: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3488: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3489: 	}
                   3490:     } else {
                   3491: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3492:     }
                   3493: }
                   3494: 
1.1164    raeburn  3495: sub embedded_dependency {
                   3496:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3497:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3498:         if (($identifier ne '') &&
                   3499:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3500:             ($pathfrom ne '')) {
                   3501:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3502:             foreach my $dep (@{$related->{$identifier}}) {
                   3503:                 &add_filetype($allfiles,$path.$dep,'object');
                   3504:             }
                   3505:         }
                   3506:     }
                   3507:     return;
                   3508: }
                   3509: 
1.493     albertel 3510: sub removeuploadedurl {
1.984     neumanie 3511:     my ($url)=@_;	
                   3512:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3513:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3514: }
                   3515: 
                   3516: sub removeuserfile {
                   3517:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3518:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3519:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3520:     if ($result eq 'ok') {	
1.798     raeburn  3521:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3522:             my $metafile = $fname.'.meta';
                   3523:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3524: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3525:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3526:             my $sqlresult = 
1.823     albertel 3527:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3528:                                         'portfolio_metadata',$group,
                   3529:                                         'delete');
1.798     raeburn  3530:         }
                   3531:     }
                   3532:     return $result;
1.257     www      3533: }
1.15      www      3534: 
1.530     albertel 3535: sub mkdiruserfile {
                   3536:     my ($docuname,$docudom,$dir)=@_;
                   3537:     my $home=&homeserver($docuname,$docudom);
                   3538:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3539: }
                   3540: 
1.531     albertel 3541: sub renameuserfile {
                   3542:     my ($docuname,$docudom,$old,$new)=@_;
                   3543:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3544:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3545:                         &escape("$old").':'.&escape("$new"),$home);
                   3546:     if ($result eq 'ok') {
                   3547:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3548:             my $oldmeta = $old.'.meta';
                   3549:             my $newmeta = $new.'.meta';
                   3550:             my $metaresult = 
                   3551:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3552: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3553:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3554:             my $sqlresult = 
1.823     albertel 3555:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3556:                                         'portfolio_metadata',$group,
                   3557:                                         'delete');
1.798     raeburn  3558:         }
                   3559:     }
                   3560:     return $result;
1.531     albertel 3561: }
                   3562: 
1.14      www      3563: # ------------------------------------------------------------------------- Log
                   3564: 
                   3565: sub log {
                   3566:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3567:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3568: }
                   3569: 
                   3570: # ------------------------------------------------------------------ Course Log
1.352     www      3571: #
                   3572: # This routine flushes several buffers of non-mission-critical nature
                   3573: #
1.157     www      3574: 
                   3575: sub flushcourselogs {
1.352     www      3576:     &logthis('Flushing log buffers');
                   3577: #
                   3578: # course logs
                   3579: # This is a log of all transactions in a course, which can be used
                   3580: # for data mining purposes
                   3581: #
                   3582: # It also collects the courseid database, which lists last transaction
                   3583: # times and course titles for all courseids
                   3584: #
                   3585:     my %courseidbuffer=();
1.921     raeburn  3586:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3587:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3588: 		          &escape($courselogs{$crsid}),
                   3589: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3590: 	    delete $courselogs{$crsid};
                   3591:         } else {
                   3592:             &logthis('Failed to flush log buffer for '.$crsid);
                   3593:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3594:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3595:                         " exceeded maximum size, deleting.</font>");
                   3596:                delete $courselogs{$crsid};
                   3597:             }
1.352     www      3598:         }
1.920     raeburn  3599:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3600:             'description' => $coursedescrbuf{$crsid},
                   3601:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3602:             'type'        => $coursetypebuf{$crsid},
                   3603:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3604:         };
1.191     harris41 3605:     }
1.352     www      3606: #
                   3607: # Write course id database (reverse lookup) to homeserver of courses 
                   3608: # Is used in pickcourse
                   3609: #
1.840     albertel 3610:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3611:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3612:                                     $courseidbuffer{$crs_home},
                   3613:                                     $crs_home,'timeonly');
1.352     www      3614:     }
                   3615: #
                   3616: # File accesses
                   3617: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3618: #
1.449     matthew  3619:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3620:         if ($entry =~ /___count$/) {
                   3621:             my ($dom,$name);
1.807     albertel 3622:             ($dom,$name,undef)=
1.811     albertel 3623: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3624:             if (! defined($dom) || $dom eq '' || 
                   3625:                 ! defined($name) || $name eq '') {
1.620     albertel 3626:                 my $cid = $env{'request.course.id'};
                   3627:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3628:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3629:             }
1.450     matthew  3630:             my $value = $accesshash{$entry};
                   3631:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3632:             my %temphash=($url => $value);
1.449     matthew  3633:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3634:             if ($result eq 'ok') {
                   3635:                 delete $accesshash{$entry};
                   3636:             }
                   3637:         } else {
1.811     albertel 3638:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3639:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3640:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3641:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3642:                 delete $accesshash{$entry};
                   3643:             }
1.185     www      3644:         }
1.191     harris41 3645:     }
1.352     www      3646: #
                   3647: # Roles
                   3648: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3649: #
1.800     albertel 3650:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3651:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3652: 	    split(/\:/,$entry);
                   3653:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3654:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3655:                 $rudom,$runame) eq 'ok') {
                   3656: 	    delete $userrolehash{$entry};
                   3657:         }
                   3658:     }
1.662     raeburn  3659: #
                   3660: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3661: #
                   3662:     my %domrolebuffer = ();
1.1000    raeburn  3663:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3664:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3665:         if ($domrolebuffer{$rudom}) {
                   3666:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3667:                       '='.&escape($domainrolehash{$entry});
                   3668:         } else {
                   3669:             $domrolebuffer{$rudom}.=&escape($entry).
                   3670:                       '='.&escape($domainrolehash{$entry});
                   3671:         }
                   3672:         delete $domainrolehash{$entry};
                   3673:     }
                   3674:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3675: 	my %servers = &get_servers($dom,'library');
                   3676: 	foreach my $tryserver (keys(%servers)) {
                   3677: 	    unless (&reply('domroleput:'.$dom.':'.
                   3678: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3679: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3680: 	    }
1.662     raeburn  3681:         }
                   3682:     }
1.186     www      3683:     $dumpcount++;
1.157     www      3684: }
                   3685: 
                   3686: sub courselog {
                   3687:     my $what=shift;
1.158     www      3688:     $what=time.':'.$what;
1.620     albertel 3689:     unless ($env{'request.course.id'}) { return ''; }
                   3690:     $coursedombuf{$env{'request.course.id'}}=
                   3691:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3692:     $coursenumbuf{$env{'request.course.id'}}=
                   3693:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3694:     $coursehombuf{$env{'request.course.id'}}=
                   3695:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3696:     $coursedescrbuf{$env{'request.course.id'}}=
                   3697:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3698:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3699:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3700:     $courseownerbuf{$env{'request.course.id'}}=
                   3701:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3702:     $coursetypebuf{$env{'request.course.id'}}=
                   3703:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3704:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3705: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3706:     } else {
1.620     albertel 3707: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3708:     }
1.620     albertel 3709:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3710: 	&flushcourselogs();
                   3711:     }
1.158     www      3712: }
                   3713: 
                   3714: sub courseacclog {
                   3715:     my $fnsymb=shift;
1.620     albertel 3716:     unless ($env{'request.course.id'}) { return ''; }
                   3717:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3718:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3719:         $what.=':POST';
1.583     matthew  3720:         # FIXME: Probably ought to escape things....
1.800     albertel 3721: 	foreach my $key (keys(%env)) {
                   3722:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3723:                 my $formitem = $1;
                   3724:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3725:                     $what.=':'.$formitem.'='.$env{$key};
                   3726:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3727:                     $what.=':'.$formitem.'='.$env{$key};
                   3728:                 }
1.158     www      3729:             }
1.191     harris41 3730:         }
1.583     matthew  3731:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3732:         # FIXME: We should not be depending on a form parameter that someone
                   3733:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3734:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3735:             $what.= ':POST';
                   3736:             # FIXME: Probably ought to escape things....
                   3737:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3738:                                  'crsdiscuss') {
1.620     albertel 3739:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3740:             }
                   3741:         }
1.158     www      3742:     }
                   3743:     &courselog($what);
1.149     www      3744: }
                   3745: 
1.185     www      3746: sub countacc {
                   3747:     my $url=&declutter(shift);
1.458     matthew  3748:     return if (! defined($url) || $url eq '');
1.620     albertel 3749:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3750: #
                   3751: # Mark that this url was used in this course
                   3752: #
1.620     albertel 3753:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3754: #
                   3755: # Increase the access count for this resource in this child process
                   3756: #
1.281     www      3757:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3758:     $accesshash{$key}++;
1.185     www      3759: }
1.349     www      3760: 
1.361     www      3761: sub linklog {
                   3762:     my ($from,$to)=@_;
                   3763:     $from=&declutter($from);
                   3764:     $to=&declutter($to);
                   3765:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3766:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3767: }
1.1160    www      3768: 
                   3769: sub statslog {
                   3770:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3771:     if ($users<2) { return; }
                   3772:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3773:             'course'       => $env{'request.course.id'},
                   3774:             'sections'     => '"all"',
                   3775:             'num_students' => $users,
                   3776:             'part'         => $part,
                   3777:             'symb'         => $symb,
                   3778:             'mean_tries'   => $av_attempts,
                   3779:             'deg_of_diff'  => $degdiff});
                   3780:     foreach my $key (keys(%dynstore)) {
                   3781:         $accesshash{$key}=$dynstore{$key};
                   3782:     }
                   3783: }
1.361     www      3784:   
1.349     www      3785: sub userrolelog {
                   3786:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3787:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3788:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3789:        $userrolehash
                   3790:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3791:                     =$tend.':'.$tstart;
1.662     raeburn  3792:     }
1.1169    droeschl 3793:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3794:        $userrolehash
                   3795:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3796:                     =$tend.':'.$tstart;
                   3797:     }
1.1169    droeschl 3798:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3799:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3800:        $domainrolehash
                   3801:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3802:                     = $tend.':'.$tstart;
                   3803:     }
1.351     www      3804: }
                   3805: 
1.957     raeburn  3806: sub courserolelog {
                   3807:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3808:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3809:         my $cdom = $1;
                   3810:         my $cnum = $2;
                   3811:         my $sec = $3;
                   3812:         my $namespace = 'rolelog';
                   3813:         my %storehash = (
                   3814:                            role    => $trole,
                   3815:                            start   => $tstart,
                   3816:                            end     => $tend,
                   3817:                            selfenroll => $selfenroll,
                   3818:                            context    => $context,
                   3819:                         );
                   3820:         if ($trole eq 'gr') {
                   3821:             $namespace = 'groupslog';
                   3822:             $storehash{'group'} = $sec;
                   3823:         } else {
                   3824:             $storehash{'section'} = $sec;
                   3825:         }
                   3826:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3827:                    $domain,$cnum,$cdom);
                   3828:         if (($trole ne 'st') || ($sec ne '')) {
                   3829:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3830:         }
                   3831:     }
                   3832:     return;
                   3833: }
                   3834: 
1.1172.2.9  raeburn  3835: sub domainrolelog {
                   3836:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3837:     if ($area =~ m{^/($match_domain)/$}) {
                   3838:         my $cdom = $1;
                   3839:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3840:         my $namespace = 'rolelog';
                   3841:         my %storehash = (
                   3842:                            role    => $trole,
                   3843:                            start   => $tstart,
                   3844:                            end     => $tend,
                   3845:                            context => $context,
                   3846:                         );
                   3847:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3848:                    $domain,$domconfiguser,$cdom);
                   3849:     }
                   3850:     return;
                   3851: 
                   3852: }
                   3853: 
                   3854: sub coauthorrolelog {
                   3855:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3856:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3857:         my $audom = $1;
                   3858:         my $auname = $2;
                   3859:         my $namespace = 'rolelog';
                   3860:         my %storehash = (
                   3861:                            role    => $trole,
                   3862:                            start   => $tstart,
                   3863:                            end     => $tend,
                   3864:                            context => $context,
                   3865:                         );
                   3866:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3867:                    $domain,$auname,$audom);
                   3868:     }
                   3869:     return;
                   3870: }
                   3871: 
1.351     www      3872: sub get_course_adv_roles {
1.948     raeburn  3873:     my ($cid,$codes) = @_;
1.620     albertel 3874:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3875:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3876:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3877:     my %nothide=();
1.800     albertel 3878:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3879:         if ($user !~ /:/) {
                   3880: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3881:         } else {
                   3882:             $nothide{$user}=1;
                   3883:         }
1.470     www      3884:     }
1.351     www      3885:     my %returnhash=();
                   3886:     my %dumphash=
                   3887:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3888:     my $now=time;
1.997     raeburn  3889:     my %privileged;
1.1000    raeburn  3890:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3891: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3892:         if (($tstart) && ($tstart<0)) { next; }
                   3893:         if (($tend) && ($tend<$now)) { next; }
                   3894:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3895:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3896: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3897:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3898:             my %dompersonnel =
1.998     raeburn  3899:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3900:             $privileged{$domain} = {};
                   3901:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3902:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3903:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3904:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3905:                         $privileged{$udom}{$uname} = 1;
                   3906:                     }
                   3907:                 }
                   3908:             }
                   3909:         }
                   3910:         if ((exists($privileged{$domain}{$username})) && 
                   3911:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3912: 	if ($role eq 'cr') { next; }
1.948     raeburn  3913:         if ($codes) {
                   3914:             if ($section) { $role .= ':'.$section; }
                   3915:             if ($returnhash{$role}) {
                   3916:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3917:             } else {
                   3918:                 $returnhash{$role}=$username.':'.$domain;
                   3919:             }
1.351     www      3920:         } else {
1.988     raeburn  3921:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3922:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3923:             if ($returnhash{$key}) {
                   3924: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3925:             } else {
                   3926:                 $returnhash{$key}=$username.':'.$domain;
                   3927:             }
1.351     www      3928:         }
1.948     raeburn  3929:     }
1.400     www      3930:     return %returnhash;
                   3931: }
                   3932: 
                   3933: sub get_my_roles {
1.937     raeburn  3934:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3935:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3936:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3937:     my (%dumphash,%nothide);
1.1086    raeburn  3938:     if ($context eq 'userroles') {
1.1166    raeburn  3939:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3940:     } else {
                   3941:         %dumphash=
1.400     www      3942:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3943:         if ($hidepriv) {
                   3944:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3945:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3946:                 if ($user !~ /:/) {
                   3947:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3948:                 } else {
                   3949:                     $nothide{$user} = 1;
                   3950:                 }
                   3951:             }
                   3952:         }
1.858     raeburn  3953:     }
1.400     www      3954:     my %returnhash=();
                   3955:     my $now=time;
1.999     raeburn  3956:     my %privileged;
1.800     albertel 3957:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3958:         my ($role,$tend,$tstart);
                   3959:         if ($context eq 'userroles') {
1.1149    raeburn  3960:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3961: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3962:         } else {
                   3963:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3964:         }
1.400     www      3965:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3966:         my $status = 'active';
1.939     raeburn  3967:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3968:             $status = 'previous';
                   3969:         } 
                   3970:         if (($tstart) && ($now<$tstart)) {
                   3971:             $status = 'future';
                   3972:         }
                   3973:         if (ref($types) eq 'ARRAY') {
                   3974:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3975:                 next;
                   3976:             } 
                   3977:         } else {
                   3978:             if ($status ne 'active') {
                   3979:                 next;
                   3980:             }
                   3981:         }
1.867     raeburn  3982:         my ($rolecode,$username,$domain,$section,$area);
                   3983:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3984:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3985:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3986:         } else {
                   3987:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3988:         }
1.832     raeburn  3989:         if (ref($roledoms) eq 'ARRAY') {
                   3990:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3991:                 next;
                   3992:             }
                   3993:         }
                   3994:         if (ref($roles) eq 'ARRAY') {
                   3995:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3996:                 if ($role =~ /^cr\//) {
                   3997:                     if (!grep(/^cr$/,@{$roles})) {
                   3998:                         next;
                   3999:                     }
1.1104    raeburn  4000:                 } elsif ($role =~ /^gr\//) {
                   4001:                     if (!grep(/^gr$/,@{$roles})) {
                   4002:                         next;
                   4003:                     }
1.922     raeburn  4004:                 } else {
                   4005:                     next;
                   4006:                 }
1.832     raeburn  4007:             }
1.867     raeburn  4008:         }
1.937     raeburn  4009:         if ($hidepriv) {
1.999     raeburn  4010:             if ($context eq 'userroles') {
                   4011:                 if ((&privileged($username,$domain)) &&
                   4012:                     (!$nothide{$username.':'.$domain})) {
                   4013:                     next;
                   4014:                 }
                   4015:             } else {
                   4016:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4017:                     my %dompersonnel =
                   4018:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4019:                     $privileged{$domain} = {};
                   4020:                     if (keys(%dompersonnel)) {
                   4021:                         foreach my $server (keys(%dompersonnel)) {
                   4022:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4023:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4024:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4025:                                     $privileged{$udom}{$uname} = $trole;
                   4026:                                 }
                   4027:                             }
                   4028:                         }
                   4029:                     }
                   4030:                 }
                   4031:                 if (exists($privileged{$domain}{$username})) {
                   4032:                     if (!$nothide{$username.':'.$domain}) {
                   4033:                         next;
                   4034:                     }
                   4035:                 }
1.937     raeburn  4036:             }
                   4037:         }
1.933     raeburn  4038:         if ($withsec) {
                   4039:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4040:                 $tstart.':'.$tend;
                   4041:         } else {
                   4042:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4043:         }
1.832     raeburn  4044:     }
1.373     www      4045:     return %returnhash;
1.399     www      4046: }
                   4047: 
                   4048: # ----------------------------------------------------- Frontpage Announcements
                   4049: #
                   4050: #
                   4051: 
                   4052: sub postannounce {
                   4053:     my ($server,$text)=@_;
1.844     albertel 4054:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4055:     unless ($text=~/\w/) { $text=''; }
                   4056:     return &reply('setannounce:'.&escape($text),$server);
                   4057: }
                   4058: 
                   4059: sub getannounce {
1.448     albertel 4060: 
                   4061:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4062: 	my $announcement='';
1.800     albertel 4063: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4064: 	close($fh);
1.399     www      4065: 	if ($announcement=~/\w/) { 
                   4066: 	    return 
                   4067:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4068:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4069: 	} else {
                   4070: 	    return '';
                   4071: 	}
                   4072:     } else {
                   4073: 	return '';
                   4074:     }
1.351     www      4075: }
1.353     www      4076: 
                   4077: # ---------------------------------------------------------- Course ID routines
                   4078: # Deal with domain's nohist_courseid.db files
                   4079: #
                   4080: 
                   4081: sub courseidput {
1.921     raeburn  4082:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4083:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4084:     my $outcome;
                   4085:     if ($caller eq 'timeonly') {
                   4086:         my $cids = '';
                   4087:         foreach my $item (keys(%$storehash)) {
                   4088:             $cids.=&escape($item).'&';
                   4089:         }
                   4090:         $cids=~s/\&$//;
                   4091:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4092:                           $coursehome);       
                   4093:     } else {
                   4094:         my $items = '';
                   4095:         foreach my $item (keys(%$storehash)) {
                   4096:             $items.= &escape($item).'='.
                   4097:                      &freeze_escape($$storehash{$item}).'&';
                   4098:         }
                   4099:         $items=~s/\&$//;
                   4100:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4101:                           $coursehome);
1.918     raeburn  4102:     }
                   4103:     if ($outcome eq 'unknown_cmd') {
                   4104:         my $what;
                   4105:         foreach my $cid (keys(%$storehash)) {
                   4106:             $what .= &escape($cid).'=';
1.921     raeburn  4107:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4108:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4109:             }
                   4110:             $what =~ s/\:$/&/;
                   4111:         }
                   4112:         $what =~ s/\&$//;  
                   4113:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4114:     } else {
                   4115:         return $outcome;
                   4116:     }
1.353     www      4117: }
                   4118: 
                   4119: sub courseiddump {
1.921     raeburn  4120:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4121:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4122:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4123:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4124:     my $as_hash = 1;
                   4125:     my %returnhash;
                   4126:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4127:     my %libserv = &all_library();
                   4128:     foreach my $tryserver (keys(%libserv)) {
                   4129:         if ( (  $hostidflag == 1 
                   4130: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4131: 	     || (!defined($hostidflag)) ) {
                   4132: 
1.918     raeburn  4133: 	    if (($domfilter eq '') ||
                   4134: 		(&host_domain($tryserver) eq $domfilter)) {
                   4135:                 my $rep = 
                   4136:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4137:                          $sincefilter.':'.&escape($descfilter).':'.
                   4138:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   4139:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  4140:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  4141:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  4142:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  4143:                          &escape($cc_clone).':'.$cloneonly.':'.
                   4144:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  4145:                          &escape($creationcontext).':'.$domcloner,
                   4146:                          $tryserver);
1.918     raeburn  4147:                 my @pairs=split(/\&/,$rep);
                   4148:                 foreach my $item (@pairs) {
                   4149:                     my ($key,$value)=split(/\=/,$item,2);
                   4150:                     $key = &unescape($key);
                   4151:                     next if ($key =~ /^error: 2 /);
                   4152:                     my $result = &thaw_unescape($value);
                   4153:                     if (ref($result) eq 'HASH') {
                   4154:                         $returnhash{$key}=$result;
                   4155:                     } else {
1.921     raeburn  4156:                         my @responses = split(/:/,$value);
                   4157:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4158:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4159:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4160:                         }
1.1008    raeburn  4161:                     }
1.353     www      4162:                 }
                   4163:             }
                   4164:         }
                   4165:     }
                   4166:     return %returnhash;
                   4167: }
                   4168: 
1.1055    raeburn  4169: sub courselastaccess {
                   4170:     my ($cdom,$cnum,$hostidref) = @_;
                   4171:     my %returnhash;
                   4172:     if ($cdom && $cnum) {
                   4173:         my $chome = &homeserver($cnum,$cdom);
                   4174:         if ($chome ne 'no_host') {
                   4175:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4176:             &extract_lastaccess(\%returnhash,$rep);
                   4177:         }
                   4178:     } else {
                   4179:         if (!$cdom) { $cdom=''; }
                   4180:         my %libserv = &all_library();
                   4181:         foreach my $tryserver (keys(%libserv)) {
                   4182:             if (ref($hostidref) eq 'ARRAY') {
                   4183:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4184:             } 
                   4185:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4186:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4187:                 &extract_lastaccess(\%returnhash,$rep);
                   4188:             }
                   4189:         }
                   4190:     }
                   4191:     return %returnhash;
                   4192: }
                   4193: 
                   4194: sub extract_lastaccess {
                   4195:     my ($returnhash,$rep) = @_;
                   4196:     if (ref($returnhash) eq 'HASH') {
                   4197:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4198:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4199:                  $rep eq '') {
                   4200:             my @pairs=split(/\&/,$rep);
                   4201:             foreach my $item (@pairs) {
                   4202:                 my ($key,$value)=split(/\=/,$item,2);
                   4203:                 $key = &unescape($key);
                   4204:                 next if ($key =~ /^error: 2 /);
                   4205:                 $returnhash->{$key} = &thaw_unescape($value);
                   4206:             }
                   4207:         }
                   4208:     }
                   4209:     return;
                   4210: }
                   4211: 
1.658     raeburn  4212: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4213: 
                   4214: sub dcmailput {
1.685     raeburn  4215:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4216:     my $status = &Apache::lonnet::critical(
1.740     www      4217:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4218:        &escape($message),$server);
1.662     raeburn  4219:     return $status;
                   4220: }
                   4221: 
1.658     raeburn  4222: sub dcmaildump {
                   4223:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4224:     my %returnhash=();
1.846     albertel 4225: 
                   4226:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4227:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4228:                                                          &escape($enddate).':';
                   4229: 	my @esc_senders=map { &escape($_)} @$senders;
                   4230: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4231: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4232:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4233:             if (($key) && ($value)) {
                   4234:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4235:             }
                   4236:         }
                   4237:     }
                   4238:     return %returnhash;
                   4239: }
1.662     raeburn  4240: # ---------------------------------------------------------- Domain roles
                   4241: 
                   4242: sub get_domain_roles {
                   4243:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4244:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4245:         $startdate = '.';
                   4246:     }
1.1018    raeburn  4247:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4248:         $enddate = '.';
                   4249:     }
1.922     raeburn  4250:     my $rolelist;
                   4251:     if (ref($roles) eq 'ARRAY') {
                   4252:         $rolelist = join(':',@{$roles});
                   4253:     }
1.662     raeburn  4254:     my %personnel = ();
1.841     albertel 4255: 
                   4256:     my %servers = &get_servers($dom,'library');
                   4257:     foreach my $tryserver (keys(%servers)) {
                   4258: 	%{$personnel{$tryserver}}=();
                   4259: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4260: 					    &escape($startdate).':'.
                   4261: 					    &escape($enddate).':'.
                   4262: 					    &escape($rolelist), $tryserver))) {
                   4263: 	    my ($key,$value) = split(/\=/,$line,2);
                   4264: 	    if (($key) && ($value)) {
                   4265: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4266: 	    }
                   4267: 	}
1.662     raeburn  4268:     }
                   4269:     return %personnel;
                   4270: }
1.658     raeburn  4271: 
1.1057    www      4272: # ----------------------------------------------------------- Interval timing 
1.149     www      4273: 
1.1153    www      4274: {
                   4275: # Caches needed for speedup of navmaps
                   4276: # We don't want to cache this for very long at all (5 seconds at most)
                   4277: # 
                   4278: # The user for whom we cache
                   4279: my $cachedkey='';
                   4280: # The cached times for this user
                   4281: my %cachedtimes=();
                   4282: # When this was last done
                   4283: my $cachedtime=();
                   4284: 
                   4285: sub load_all_first_access {
1.1154    raeburn  4286:     my ($uname,$udom)=@_;
1.1156    www      4287:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4288:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4289:         return;
                   4290:     }
                   4291:     $cachedtime=time;
                   4292:     $cachedkey=$uname.':'.$udom;
                   4293:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4294: }
                   4295: 
1.504     albertel 4296: sub get_first_access {
1.1162    raeburn  4297:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4298:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4299:     if ($argsymb) { $symb=$argsymb; }
                   4300:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4301:     if ($argmap) { $map = $argmap; }
1.926     albertel 4302:     if ($type eq 'course') {
                   4303: 	$res='course';
                   4304:     } elsif ($type eq 'map') {
1.588     albertel 4305: 	$res=&symbread($map);
                   4306:     } else {
                   4307: 	$res=$symb;
                   4308:     }
1.1153    www      4309:     &load_all_first_access($uname,$udom);
                   4310:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4311: }
                   4312: 
                   4313: sub set_first_access {
1.1162    raeburn  4314:     my ($type,$interval)=@_;
1.790     albertel 4315:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4316:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4317:     if ($type eq 'course') {
                   4318: 	$res='course';
                   4319:     } elsif ($type eq 'map') {
1.588     albertel 4320: 	$res=&symbread($map);
                   4321:     } else {
                   4322: 	$res=$symb;
                   4323:     }
1.1153    www      4324:     $cachedkey='';
1.1162    raeburn  4325:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4326:     if (!$firstaccess) {
1.1162    raeburn  4327:         my $start = time;
                   4328: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4329:                           $udom,$uname);
                   4330:         if ($putres eq 'ok') {
                   4331:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4332:                  $udom,$uname); 
                   4333:             &appenv(
                   4334:                      {
                   4335:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4336:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4337:                      }
                   4338:                   );
                   4339:         }
                   4340:         return $putres;
1.505     albertel 4341:     }
                   4342:     return 'already_set';
1.504     albertel 4343: }
1.1153    www      4344: }
1.110     www      4345: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4346: 
                   4347: sub expirespread {
                   4348:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4349:     my $cid=$env{'request.course.id'}; 
1.110     www      4350:     if ($cid) {
                   4351:        my $now=time;
                   4352:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4353:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4354:                             $env{'course.'.$cid.'.num'}.
1.110     www      4355: 	        	    ':nohist_expirationdates:'.
                   4356:                             &escape($key).'='.$now,
1.620     albertel 4357:                             $env{'course.'.$cid.'.home'})
1.110     www      4358:     }
                   4359:     return 'ok';
1.14      www      4360: }
                   4361: 
1.109     www      4362: # ----------------------------------------------------- Devalidate Spreadsheets
                   4363: 
                   4364: sub devalidate {
1.325     www      4365:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4366:     my $cid=$env{'request.course.id'}; 
1.109     www      4367:     if ($cid) {
1.391     matthew  4368:         # delete the stored spreadsheets for
                   4369:         # - the student level sheet of this user in course's homespace
                   4370:         # - the assessment level sheet for this resource 
                   4371:         #   for this user in user's homespace
1.553     albertel 4372: 	# - current conditional state info
1.325     www      4373: 	my $key=$uname.':'.$udom.':';
1.109     www      4374:         my $status=
1.299     matthew  4375: 	    &del('nohist_calculatedsheets',
1.391     matthew  4376: 		 [$key.'studentcalc:'],
1.620     albertel 4377: 		 $env{'course.'.$cid.'.domain'},
                   4378: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4379: 		.' '.
                   4380: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4381: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4382:         unless ($status eq 'ok ok') {
                   4383:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4384:                     $uname.' at '.$udom.' for '.
1.109     www      4385: 		    $symb.': '.$status);
1.133     albertel 4386:         }
1.553     albertel 4387: 	&delenv('user.state.'.$cid);
1.109     www      4388:     }
                   4389: }
                   4390: 
1.265     albertel 4391: sub get_scalar {
                   4392:     my ($string,$end) = @_;
                   4393:     my $value;
                   4394:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4395: 	$value = $1;
                   4396:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4397: 	$value = $1;
                   4398:     }
                   4399:     return &unescape($value);
                   4400: }
                   4401: 
                   4402: sub array2str {
                   4403:   my (@array) = @_;
                   4404:   my $result=&arrayref2str(\@array);
                   4405:   $result=~s/^__ARRAY_REF__//;
                   4406:   $result=~s/__END_ARRAY_REF__$//;
                   4407:   return $result;
                   4408: }
                   4409: 
1.204     albertel 4410: sub arrayref2str {
                   4411:   my ($arrayref) = @_;
1.265     albertel 4412:   my $result='__ARRAY_REF__';
1.204     albertel 4413:   foreach my $elem (@$arrayref) {
1.265     albertel 4414:     if(ref($elem) eq 'ARRAY') {
                   4415:       $result.=&arrayref2str($elem).'&';
                   4416:     } elsif(ref($elem) eq 'HASH') {
                   4417:       $result.=&hashref2str($elem).'&';
                   4418:     } elsif(ref($elem)) {
                   4419:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4420:     } else {
                   4421:       $result.=&escape($elem).'&';
                   4422:     }
                   4423:   }
                   4424:   $result=~s/\&$//;
1.265     albertel 4425:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4426:   return $result;
                   4427: }
                   4428: 
1.168     albertel 4429: sub hash2str {
1.204     albertel 4430:   my (%hash) = @_;
                   4431:   my $result=&hashref2str(\%hash);
1.265     albertel 4432:   $result=~s/^__HASH_REF__//;
                   4433:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4434:   return $result;
                   4435: }
                   4436: 
                   4437: sub hashref2str {
                   4438:   my ($hashref)=@_;
1.265     albertel 4439:   my $result='__HASH_REF__';
1.800     albertel 4440:   foreach my $key (sort(keys(%$hashref))) {
                   4441:     if (ref($key) eq 'ARRAY') {
                   4442:       $result.=&arrayref2str($key).'=';
                   4443:     } elsif (ref($key) eq 'HASH') {
                   4444:       $result.=&hashref2str($key).'=';
                   4445:     } elsif (ref($key)) {
1.265     albertel 4446:       $result.='=';
1.800     albertel 4447:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4448:     } else {
1.1132    raeburn  4449: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4450:     }
                   4451: 
1.800     albertel 4452:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4453:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4454:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4455:       $result.=&hashref2str($hashref->{$key}).'&';
                   4456:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4457:        $result.='&';
1.800     albertel 4458:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4459:     } else {
1.800     albertel 4460:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4461:     }
                   4462:   }
1.168     albertel 4463:   $result=~s/\&$//;
1.265     albertel 4464:   $result .= '__END_HASH_REF__';
1.168     albertel 4465:   return $result;
                   4466: }
                   4467: 
                   4468: sub str2hash {
1.265     albertel 4469:     my ($string)=@_;
                   4470:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4471:     return %$hash;
                   4472: }
                   4473: 
                   4474: sub str2hashref {
1.168     albertel 4475:   my ($string) = @_;
1.265     albertel 4476: 
                   4477:   my %hash;
                   4478: 
                   4479:   if($string !~ /^__HASH_REF__/) {
                   4480:       if (! ($string eq '' || !defined($string))) {
                   4481: 	  $hash{'error'}='Not hash reference';
                   4482:       }
                   4483:       return (\%hash, $string);
                   4484:   }
                   4485: 
                   4486:   $string =~ s/^__HASH_REF__//;
                   4487: 
                   4488:   while($string !~ /^__END_HASH_REF__/) {
                   4489:       #key
                   4490:       my $key='';
                   4491:       if($string =~ /^__HASH_REF__/) {
                   4492:           ($key, $string)=&str2hashref($string);
                   4493:           if(defined($key->{'error'})) {
                   4494:               $hash{'error'}='Bad data';
                   4495:               return (\%hash, $string);
                   4496:           }
                   4497:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4498:           ($key, $string)=&str2arrayref($string);
                   4499:           if($key->[0] eq 'Array reference error') {
                   4500:               $hash{'error'}='Bad data';
                   4501:               return (\%hash, $string);
                   4502:           }
                   4503:       } else {
                   4504:           $string =~ s/^(.*?)=//;
1.267     albertel 4505: 	  $key=&unescape($1);
1.265     albertel 4506:       }
                   4507:       $string =~ s/^=//;
                   4508: 
                   4509:       #value
                   4510:       my $value='';
                   4511:       if($string =~ /^__HASH_REF__/) {
                   4512:           ($value, $string)=&str2hashref($string);
                   4513:           if(defined($value->{'error'})) {
                   4514:               $hash{'error'}='Bad data';
                   4515:               return (\%hash, $string);
                   4516:           }
                   4517:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4518:           ($value, $string)=&str2arrayref($string);
                   4519:           if($value->[0] eq 'Array reference error') {
                   4520:               $hash{'error'}='Bad data';
                   4521:               return (\%hash, $string);
                   4522:           }
                   4523:       } else {
                   4524: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4525:       }
                   4526:       $string =~ s/^&//;
                   4527: 
                   4528:       $hash{$key}=$value;
1.204     albertel 4529:   }
1.265     albertel 4530: 
                   4531:   $string =~ s/^__END_HASH_REF__//;
                   4532: 
                   4533:   return (\%hash, $string);
1.204     albertel 4534: }
                   4535: 
                   4536: sub str2array {
1.265     albertel 4537:     my ($string)=@_;
                   4538:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4539:     return @$array;
                   4540: }
                   4541: 
                   4542: sub str2arrayref {
1.204     albertel 4543:   my ($string) = @_;
1.265     albertel 4544:   my @array;
                   4545: 
                   4546:   if($string !~ /^__ARRAY_REF__/) {
                   4547:       if (! ($string eq '' || !defined($string))) {
                   4548: 	  $array[0]='Array reference error';
                   4549:       }
                   4550:       return (\@array, $string);
                   4551:   }
                   4552: 
                   4553:   $string =~ s/^__ARRAY_REF__//;
                   4554: 
                   4555:   while($string !~ /^__END_ARRAY_REF__/) {
                   4556:       my $value='';
                   4557:       if($string =~ /^__HASH_REF__/) {
                   4558:           ($value, $string)=&str2hashref($string);
                   4559:           if(defined($value->{'error'})) {
                   4560:               $array[0] ='Array reference error';
                   4561:               return (\@array, $string);
                   4562:           }
                   4563:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4564:           ($value, $string)=&str2arrayref($string);
                   4565:           if($value->[0] eq 'Array reference error') {
                   4566:               $array[0] ='Array reference error';
                   4567:               return (\@array, $string);
                   4568:           }
                   4569:       } else {
                   4570: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4571:       }
                   4572:       $string =~ s/^&//;
                   4573: 
                   4574:       push(@array, $value);
1.191     harris41 4575:   }
1.265     albertel 4576: 
                   4577:   $string =~ s/^__END_ARRAY_REF__//;
                   4578: 
                   4579:   return (\@array, $string);
1.168     albertel 4580: }
                   4581: 
1.167     albertel 4582: # -------------------------------------------------------------------Temp Store
                   4583: 
1.168     albertel 4584: sub tmpreset {
                   4585:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4586:   if (!$symb) {
                   4587:     $symb=&symbread();
1.620     albertel 4588:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4589:   }
                   4590:   $symb=escape($symb);
                   4591: 
1.620     albertel 4592:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4593:   $namespace=~s/\//\_/g;
                   4594:   $namespace=~s/\W//g;
                   4595: 
1.620     albertel 4596:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4597:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4598:   if ($domain eq 'public' && $stuname eq 'public') {
                   4599:       $stuname=$ENV{'REMOTE_ADDR'};
                   4600:   }
1.1117    foxr     4601:   my $path=LONCAPA::tempdir();
1.168     albertel 4602:   my %hash;
                   4603:   if (tie(%hash,'GDBM_File',
                   4604: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4605: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4606:     foreach my $key (keys(%hash)) {
1.180     albertel 4607:       if ($key=~ /:$symb/) {
1.168     albertel 4608: 	delete($hash{$key});
                   4609:       }
                   4610:     }
                   4611:   }
                   4612: }
                   4613: 
1.167     albertel 4614: sub tmpstore {
1.168     albertel 4615:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4616: 
                   4617:   if (!$symb) {
                   4618:     $symb=&symbread();
1.620     albertel 4619:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4620:   }
                   4621:   $symb=escape($symb);
                   4622: 
                   4623:   if (!$namespace) {
                   4624:     # I don't think we would ever want to store this for a course.
                   4625:     # it seems this will only be used if we don't have a course.
1.620     albertel 4626:     #$namespace=$env{'request.course.id'};
1.168     albertel 4627:     #if (!$namespace) {
1.620     albertel 4628:       $namespace=$env{'request.state'};
1.168     albertel 4629:     #}
                   4630:   }
                   4631:   $namespace=~s/\//\_/g;
                   4632:   $namespace=~s/\W//g;
1.620     albertel 4633:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4634:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4635:   if ($domain eq 'public' && $stuname eq 'public') {
                   4636:       $stuname=$ENV{'REMOTE_ADDR'};
                   4637:   }
1.168     albertel 4638:   my $now=time;
                   4639:   my %hash;
1.1117    foxr     4640:   my $path=LONCAPA::tempdir();
1.168     albertel 4641:   if (tie(%hash,'GDBM_File',
                   4642: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4643: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4644:     $hash{"version:$symb"}++;
                   4645:     my $version=$hash{"version:$symb"};
                   4646:     my $allkeys=''; 
                   4647:     foreach my $key (keys(%$storehash)) {
                   4648:       $allkeys.=$key.':';
1.591     albertel 4649:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4650:     }
                   4651:     $hash{"$version:$symb:timestamp"}=$now;
                   4652:     $allkeys.='timestamp';
                   4653:     $hash{"$version:keys:$symb"}=$allkeys;
                   4654:     if (untie(%hash)) {
                   4655:       return 'ok';
                   4656:     } else {
                   4657:       return "error:$!";
                   4658:     }
                   4659:   } else {
                   4660:     return "error:$!";
                   4661:   }
                   4662: }
1.167     albertel 4663: 
1.168     albertel 4664: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4665: 
1.168     albertel 4666: sub tmprestore {
                   4667:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4668: 
1.168     albertel 4669:   if (!$symb) {
                   4670:     $symb=&symbread();
1.620     albertel 4671:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4672:   }
                   4673:   $symb=escape($symb);
                   4674: 
1.620     albertel 4675:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4676: 
1.620     albertel 4677:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4678:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4679:   if ($domain eq 'public' && $stuname eq 'public') {
                   4680:       $stuname=$ENV{'REMOTE_ADDR'};
                   4681:   }
1.168     albertel 4682:   my %returnhash;
                   4683:   $namespace=~s/\//\_/g;
                   4684:   $namespace=~s/\W//g;
                   4685:   my %hash;
1.1117    foxr     4686:   my $path=LONCAPA::tempdir();
1.168     albertel 4687:   if (tie(%hash,'GDBM_File',
                   4688: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4689: 	  &GDBM_READER(),0640)) {
1.168     albertel 4690:     my $version=$hash{"version:$symb"};
                   4691:     $returnhash{'version'}=$version;
                   4692:     my $scope;
                   4693:     for ($scope=1;$scope<=$version;$scope++) {
                   4694:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4695:       my @keys=split(/:/,$vkeys);
                   4696:       my $key;
                   4697:       $returnhash{"$scope:keys"}=$vkeys;
                   4698:       foreach $key (@keys) {
1.591     albertel 4699: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4700: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4701:       }
                   4702:     }
1.168     albertel 4703:     if (!(untie(%hash))) {
                   4704:       return "error:$!";
                   4705:     }
                   4706:   } else {
                   4707:     return "error:$!";
                   4708:   }
                   4709:   return %returnhash;
1.167     albertel 4710: }
                   4711: 
1.9       www      4712: # ----------------------------------------------------------------------- Store
                   4713: 
                   4714: sub store {
1.124     www      4715:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4716:     my $home='';
                   4717: 
1.168     albertel 4718:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4719: 
1.213     www      4720:     $symb=&symbclean($symb);
1.122     albertel 4721:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4722: 
1.620     albertel 4723:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4724:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4725: 
                   4726:     &devalidate($symb,$stuname,$domain);
1.109     www      4727: 
                   4728:     $symb=escape($symb);
1.187     www      4729:     if (!$namespace) { 
1.620     albertel 4730:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4731:           return ''; 
                   4732:        } 
                   4733:     }
1.620     albertel 4734:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4735: 
                   4736:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4737:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4738: 
1.12      www      4739:     my $namevalue='';
1.800     albertel 4740:     foreach my $key (keys(%$storehash)) {
                   4741:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4742:     }
1.12      www      4743:     $namevalue=~s/\&$//;
1.187     www      4744:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4745:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4746: }
                   4747: 
1.47      www      4748: # -------------------------------------------------------------- Critical Store
                   4749: 
                   4750: sub cstore {
1.124     www      4751:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4752:     my $home='';
                   4753: 
1.168     albertel 4754:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4755: 
1.213     www      4756:     $symb=&symbclean($symb);
1.122     albertel 4757:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4758: 
1.620     albertel 4759:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4760:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4761: 
                   4762:     &devalidate($symb,$stuname,$domain);
1.109     www      4763: 
                   4764:     $symb=escape($symb);
1.187     www      4765:     if (!$namespace) { 
1.620     albertel 4766:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4767:           return ''; 
                   4768:        } 
                   4769:     }
1.620     albertel 4770:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4771: 
                   4772:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4773:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4774: 
1.47      www      4775:     my $namevalue='';
1.800     albertel 4776:     foreach my $key (keys(%$storehash)) {
                   4777:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4778:     }
1.47      www      4779:     $namevalue=~s/\&$//;
1.187     www      4780:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4781:     return critical
                   4782:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4783: }
                   4784: 
1.9       www      4785: # --------------------------------------------------------------------- Restore
                   4786: 
                   4787: sub restore {
1.124     www      4788:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4789:     my $home='';
                   4790: 
1.168     albertel 4791:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4792: 
1.122     albertel 4793:     if (!$symb) {
                   4794:       unless ($symb=escape(&symbread())) { return ''; }
                   4795:     } else {
1.213     www      4796:       $symb=&escape(&symbclean($symb));
1.122     albertel 4797:     }
1.188     www      4798:     if (!$namespace) { 
1.620     albertel 4799:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4800:           return ''; 
                   4801:        } 
                   4802:     }
1.620     albertel 4803:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4804:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4805:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4806:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4807: 
1.12      www      4808:     my %returnhash=();
1.800     albertel 4809:     foreach my $line (split(/\&/,$answer)) {
                   4810: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4811:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4812:     }
1.75      www      4813:     my $version;
                   4814:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4815:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4816:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4817:        }
1.75      www      4818:     }
1.13      www      4819:     return %returnhash;
1.34      www      4820: }
                   4821: 
                   4822: # ---------------------------------------------------------- Course Description
1.1118    foxr     4823: #
                   4824: #  
1.34      www      4825: 
                   4826: sub coursedescription {
1.731     albertel 4827:     my ($courseid,$args)=@_;
1.34      www      4828:     $courseid=~s/^\///;
1.49      www      4829:     $courseid=~s/\_/\//g;
1.34      www      4830:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4831:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4832:     my $normalid=$cdomain.'_'.$cnum;
                   4833:     # need to always cache even if we get errors otherwise we keep 
                   4834:     # trying and trying and trying to get the course description.
                   4835:     my %envhash=();
                   4836:     my %returnhash=();
1.731     albertel 4837:     
                   4838:     my $expiretime=600;
                   4839:     if ($env{'request.course.id'} eq $normalid) {
                   4840: 	$expiretime=120;
                   4841:     }
                   4842: 
                   4843:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4844:     if (!$args->{'freshen_cache'}
                   4845: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4846: 	foreach my $key (keys(%env)) {
                   4847: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4848: 	    my ($setting) = $1;
                   4849: 	    $returnhash{$setting} = $env{$key};
                   4850: 	}
                   4851: 	return %returnhash;
                   4852:     }
                   4853: 
1.1118    foxr     4854:     # get the data again
                   4855: 
1.731     albertel 4856:     if (!$args->{'one_time'}) {
                   4857: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4858:     }
1.811     albertel 4859: 
1.34      www      4860:     if ($chome ne 'no_host') {
1.302     albertel 4861:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4862:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4863: 	   my $username = $env{'user.name'}; # Defult username
                   4864: 	   if(defined $args->{'user'}) {
                   4865: 	       $username = $args->{'user'};
                   4866: 	   }
1.129     albertel 4867:            $returnhash{'home'}= $chome;
                   4868: 	   $returnhash{'domain'} = $cdomain;
                   4869: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4870:            if (!defined($returnhash{'type'})) {
                   4871:                $returnhash{'type'} = 'Course';
                   4872:            }
1.130     albertel 4873:            while (my ($name,$value) = each %returnhash) {
1.53      www      4874:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4875:            }
1.270     www      4876:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4877:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4878: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4879:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4880:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4881:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4882:        }
                   4883:     }
1.731     albertel 4884:     if (!$args->{'one_time'}) {
1.949     raeburn  4885: 	&appenv(\%envhash);
1.731     albertel 4886:     }
1.302     albertel 4887:     return %returnhash;
1.461     www      4888: }
                   4889: 
1.1080    raeburn  4890: sub update_released_required {
                   4891:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4892:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4893:         $cid = $env{'request.course.id'};
                   4894:         $cdom = $env{'course.'.$cid.'.domain'};
                   4895:         $cnum = $env{'course.'.$cid.'.num'};
                   4896:         $chome = $env{'course.'.$cid.'.home'};
                   4897:     }
                   4898:     if ($needsrelease) {
                   4899:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4900:         my $needsupdate;
                   4901:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4902:             $needsupdate = 1;
                   4903:         } else {
                   4904:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4905:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4906:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4907:                 $needsupdate = 1;
                   4908:             }
                   4909:         }
                   4910:         if ($needsupdate) {
                   4911:             my %needshash = (
                   4912:                              'internal.releaserequired' => $needsrelease,
                   4913:                             );
                   4914:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4915:             if ($putresult eq 'ok') {
                   4916:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4917:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4918:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4919:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4920:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4921:                 }
                   4922:             }
                   4923:         }
                   4924:     }
                   4925:     return;
                   4926: }
                   4927: 
1.461     www      4928: # -------------------------------------------------See if a user is privileged
                   4929: 
                   4930: sub privileged {
                   4931:     my ($username,$domain)=@_;
1.1170    droeschl 4932: 
                   4933:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4934:     my $now = time;
                   4935: 
                   4936:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4937:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4938:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4939:                 return 1 unless ($tend && $tend < $now) 
                   4940:                     or ($tstart && $tstart > $now);
                   4941:             }
1.461     www      4942: 	}
1.1170    droeschl 4943: 
1.461     www      4944:     return 0;
1.9       www      4945: }
1.1       albertel 4946: 
1.103     harris41 4947: # -------------------------------------------------------- Get user privileges
1.11      www      4948: 
                   4949: sub rolesinit {
1.1169    droeschl 4950:     my ($domain, $username) = @_;
                   4951:     my %userroles = ('user.login.time' => time);
                   4952:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4953: 
                   4954:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4955:     # also, blocking can be triggered by an activating timer
                   4956:     # it's saved in the user's %env.
                   4957:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4958:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4959:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4960:         %timerintchk, %timerintenv);
                   4961: 
1.1162    raeburn  4962:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4963:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4964:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4965:     }
1.1169    droeschl 4966: 
1.1162    raeburn  4967:     foreach my $key (keys(%timerinterval)) {
                   4968:         my ($cid,$rest) = split(/\0/,$key);
                   4969:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4970:     }
1.1169    droeschl 4971: 
1.11      www      4972:     my %allroles=();
1.1162    raeburn  4973:     my %allgroups=();
1.11      www      4974: 
1.1169    droeschl 4975:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4976:         my $role = $rolesdump{$area};
                   4977:         $area =~ s/\_\w\w$//;
                   4978: 
                   4979:         my ($trole, $tend, $tstart, $group_privs);
                   4980: 
                   4981:         if ($role =~ /^cr/) {
                   4982:         # Custom role, defined by a user 
                   4983:         # e.g., user.role.cr/msu/smith/mynewrole
                   4984:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4985:                 $trole = $1;
                   4986:                 ($tend, $tstart) = split('_', $2);
                   4987:             } else {
                   4988:                 $trole = $role;
                   4989:             }
                   4990:         } elsif ($role =~ m|^gr/|) {
                   4991:         # Role of member in a group, defined within a course/community
                   4992:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4993:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4994:             next if $tstart eq '-1';
                   4995:             ($trole, $group_privs) = split(/\//, $trole);
                   4996:             $group_privs = &unescape($group_privs);
                   4997:         } else {
                   4998:         # Just a normal role, defined in roles.tab
                   4999:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5000:         }
                   5001: 
                   5002:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5003:                  $username);
                   5004:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5005: 
                   5006:         # role expired or not available yet?
                   5007:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5008:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5009: 
                   5010:         next if $area eq '' or $trole eq '';
                   5011: 
                   5012:         my $spec = "$trole.$area";
                   5013:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5014: 
                   5015:         if ($trole =~ /^cr\//) {
                   5016:         # Custom role, defined by a user
                   5017:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5018:         } elsif ($trole eq 'gr') {
                   5019:         # Role of a member in a group, defined within a course/community
                   5020:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5021:             next;
                   5022:         } else {
                   5023:         # Normal role, defined in roles.tab
                   5024:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5025:         }
                   5026: 
                   5027:         my $cid = $tdomain.'_'.$trest;
                   5028:         unless ($firstaccchk{$cid}) {
                   5029:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5030:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5031:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5032:                         $coursetimerstarts{$cid}{$item}; 
                   5033:                 }
                   5034:             }
                   5035:             $firstaccchk{$cid} = 1;
                   5036:         }
                   5037:         unless ($timerintchk{$cid}) {
                   5038:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5039:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5040:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5041:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5042:                 }
1.12      www      5043:             }
1.1169    droeschl 5044:             $timerintchk{$cid} = 1;
1.191     harris41 5045:         }
1.11      www      5046:     }
1.1169    droeschl 5047: 
                   5048:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5049:         \%allroles, \%allgroups);
                   5050:     $env{'user.adv'} = $userroles{'user.adv'};
                   5051: 
1.1162    raeburn  5052:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5053: }
                   5054: 
1.567     raeburn  5055: sub set_arearole {
1.1172.2.19  raeburn  5056:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5057:     unless ($nolog) {
1.567     raeburn  5058: # log the associated role with the area
1.1172.2.19  raeburn  5059:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5060:     }
1.743     albertel 5061:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5062: }
                   5063: 
                   5064: sub custom_roleprivs {
                   5065:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5066:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5067:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5068:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5069:         my ($rdummy,$roledef)=
                   5070:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5071:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5072:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5073:             if (defined($syspriv)) {
1.1043    raeburn  5074:                 if ($trest =~ /^$match_community$/) {
                   5075:                     $syspriv =~ s/bre\&S//; 
                   5076:                 }
1.567     raeburn  5077:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5078:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5079:             }
                   5080:             if ($tdomain ne '') {
                   5081:                 if (defined($dompriv)) {
                   5082:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5083:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5084:                 }
                   5085:                 if (($trest ne '') && (defined($coursepriv))) {
                   5086:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5087:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5088:                 }
                   5089:             }
                   5090:         }
                   5091:     }
                   5092: }
                   5093: 
1.678     raeburn  5094: sub group_roleprivs {
                   5095:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5096:     my $access = 1;
                   5097:     my $now = time;
                   5098:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5099:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5100:     if ($access) {
1.811     albertel 5101:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5102:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5103:     }
                   5104: }
1.567     raeburn  5105: 
                   5106: sub standard_roleprivs {
                   5107:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5108:     if (defined($pr{$trole.':s'})) {
                   5109:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5110:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5111:     }
                   5112:     if ($tdomain ne '') {
                   5113:         if (defined($pr{$trole.':d'})) {
                   5114:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5115:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5116:         }
                   5117:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5118:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5119:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5120:         }
                   5121:     }
                   5122: }
                   5123: 
                   5124: sub set_userprivs {
1.1064    raeburn  5125:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5126:     my $author=0;
                   5127:     my $adv=0;
1.678     raeburn  5128:     my %grouproles = ();
                   5129:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5130:         my @groupkeys; 
1.1000    raeburn  5131:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5132:             push(@groupkeys,$role);
                   5133:         }
                   5134:         if (ref($groups_roles) eq 'HASH') {
                   5135:             foreach my $key (keys(%{$groups_roles})) {
                   5136:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5137:                     push(@groupkeys,$key);
                   5138:                 }
                   5139:             }
                   5140:         }
                   5141:         if (@groupkeys > 0) {
                   5142:             foreach my $role (@groupkeys) {
                   5143:                 my ($trole,$area,$sec,$extendedarea);
                   5144:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5145:                     $trole = $1;
                   5146:                     $area = $2;
                   5147:                     $sec = $3;
                   5148:                     $extendedarea = $area.$sec;
                   5149:                     if (exists($$allgroups{$area})) {
                   5150:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5151:                             my $spec = $trole.'.'.$extendedarea;
                   5152:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5153:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5154:                         }
1.678     raeburn  5155:                     }
                   5156:                 }
                   5157:             }
                   5158:         }
                   5159:     }
1.800     albertel 5160:     foreach my $group (keys(%grouproles)) {
                   5161:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5162:     }
1.800     albertel 5163:     foreach my $role (keys(%{$allroles})) {
                   5164:         my %thesepriv;
1.941     raeburn  5165:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5166:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5167:             if ($item ne '') {
                   5168:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5169:                 if ($restrictions eq '') {
                   5170:                     $thesepriv{$privilege}='F';
                   5171:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5172:                     $thesepriv{$privilege}.=$restrictions;
                   5173:                 }
                   5174:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5175:             }
                   5176:         }
                   5177:         my $thesestr='';
1.1104    raeburn  5178:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5179: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5180: 	}
                   5181:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5182:     }
                   5183:     return ($author,$adv);
                   5184: }
                   5185: 
1.994     raeburn  5186: sub role_status {
1.1104    raeburn  5187:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5188:     my @pwhere = ();
                   5189:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5190:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5191:         unless (!defined($$role) || $$role eq '') {
                   5192:             $$where=join('.',@pwhere);
                   5193:             $$trolecode=$$role.'.'.$$where;
                   5194:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5195:             $$tstatus='is';
1.1104    raeburn  5196:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5197:                 $$tstatus='future';
1.1034    raeburn  5198:                 if ($$tstart<$now) {
                   5199:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5200:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5201:                             my (%allroles,%allgroups,$group_privs,
                   5202:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5203:                             my %userroles = (
                   5204:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5205:                             );
1.1064    raeburn  5206:                             @rolecodes = ('cm'); 
1.1002    raeburn  5207:                             my $spec=$$role.'.'.$$where;
                   5208:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5209:                             if ($$role =~ /^cr\//) {
                   5210:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5211:                                 push(@rolecodes,'cr');
1.1002    raeburn  5212:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5213:                                 push(@rolecodes,$$role);
1.1002    raeburn  5214:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5215:                                                     $env{'user.name'});
1.1064    raeburn  5216:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5217:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5218:                                 $group_privs = &unescape($group_privs);
                   5219:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5220:                                 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  5221:                                 &get_groups_roles($tdomain,$trest,
                   5222:                                                   \%course_roles,\@rolecodes,
                   5223:                                                   \%groups_roles);
1.1002    raeburn  5224:                             } else {
1.1064    raeburn  5225:                                 push(@rolecodes,$$role);
1.1002    raeburn  5226:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5227:                             }
1.1064    raeburn  5228:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5229:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5230:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5231:                         }
                   5232:                     }
1.1034    raeburn  5233:                     $$tstatus = 'is';
1.1002    raeburn  5234:                 }
1.994     raeburn  5235:             }
                   5236:             if ($$tend) {
1.1104    raeburn  5237:                 if ($$tend<$update) {
1.994     raeburn  5238:                     $$tstatus='expired';
                   5239:                 } elsif ($$tend<$now) {
                   5240:                     $$tstatus='will_not';
                   5241:                 }
                   5242:             }
                   5243:         }
                   5244:     }
                   5245: }
                   5246: 
1.1104    raeburn  5247: sub get_groups_roles {
                   5248:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5249:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5250:                   (ref($rolecodes) eq 'ARRAY') && 
                   5251:                   (ref($groups_roles) eq 'HASH')); 
                   5252:     if (keys(%{$cdom_courseroles}) > 0) {
                   5253:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5254:         if ($cdom ne '' && $cnum ne '') {
                   5255:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5256:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5257:                     my $crsrole = $1;
                   5258:                     my $crssec = $2;
                   5259:                     if ($crsrole =~ /^cr/) {
                   5260:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5261:                             push(@{$rolecodes},'cr');
                   5262:                         }
                   5263:                     } else {
                   5264:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5265:                             push(@{$rolecodes},$crsrole);
                   5266:                         }
                   5267:                     }
                   5268:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5269:                     if ($crssec ne '') {
                   5270:                         $rolekey .= "/$crssec";
                   5271:                     }
                   5272:                     $rolekey .= './';
                   5273:                     $groups_roles->{$rolekey} = $rolecodes;
                   5274:                 }
                   5275:             }
                   5276:         }
                   5277:     }
                   5278:     return;
                   5279: }
                   5280: 
                   5281: sub delete_env_groupprivs {
                   5282:     my ($where,$courseroles,$possroles) = @_;
                   5283:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5284:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5285:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5286:         %{$courseroles->{$udom}} =
                   5287:             &get_my_roles('','','userroles',['active'],
                   5288:                           $possroles,[$udom],1);
                   5289:     }
                   5290:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5291:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5292:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5293:             my $area = '/'.$cdom.'/'.$cnum;
                   5294:             my $privkey = "user.priv.$crsrole.$area";
                   5295:             if ($crssec ne '') {
                   5296:                 $privkey .= '/'.$crssec;
                   5297:             }
                   5298:             $privkey .= ".$area/$group";
                   5299:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5300:         }
                   5301:     }
                   5302:     return;
                   5303: }
                   5304: 
1.994     raeburn  5305: sub check_adhoc_privs {
1.1104    raeburn  5306:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5307:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5308:     my $setprivs;
1.994     raeburn  5309:     if ($env{$cckey}) {
                   5310:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5311:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5312:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5313:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5314:             $setprivs = 1;
1.994     raeburn  5315:         }
                   5316:     } else {
1.1088    raeburn  5317:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5318:         $setprivs = 1;
1.994     raeburn  5319:     }
1.1172.2.9  raeburn  5320:     return $setprivs;
1.994     raeburn  5321: }
                   5322: 
                   5323: sub set_adhoc_privileges {
                   5324: # role can be cc or ca
1.1088    raeburn  5325:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5326:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5327:     my $spec = $role.'.'.$area;
                   5328:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5329:                                   $env{'user.name'},1);
1.994     raeburn  5330:     my %ccrole = ();
                   5331:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5332:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5333:     &appenv(\%userroles,[$role,'cm']);
                   5334:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5335:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5336:         &appenv( {'request.role'        => $spec,
                   5337:                   'request.role.domain' => $dcdom,
                   5338:                   'request.course.sec'  => ''
                   5339:                  }
                   5340:                );
                   5341:         my $tadv=0;
                   5342:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5343:         &appenv({'request.role.adv'    => $tadv});
                   5344:     }
1.994     raeburn  5345: }
                   5346: 
1.12      www      5347: # --------------------------------------------------------------- get interface
                   5348: 
                   5349: sub get {
1.131     albertel 5350:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5351:    my $items='';
1.800     albertel 5352:    foreach my $item (@$storearr) {
                   5353:        $items.=&escape($item).'&';
1.191     harris41 5354:    }
1.12      www      5355:    $items=~s/\&$//;
1.620     albertel 5356:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5357:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5358:    my $uhome=&homeserver($uname,$udomain);
                   5359: 
1.133     albertel 5360:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5361:    my @pairs=split(/\&/,$rep);
1.273     albertel 5362:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5363:      return @pairs;
                   5364:    }
1.15      www      5365:    my %returnhash=();
1.42      www      5366:    my $i=0;
1.800     albertel 5367:    foreach my $item (@$storearr) {
                   5368:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5369:       $i++;
1.191     harris41 5370:    }
1.15      www      5371:    return %returnhash;
1.27      www      5372: }
                   5373: 
                   5374: # --------------------------------------------------------------- del interface
                   5375: 
                   5376: sub del {
1.133     albertel 5377:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5378:    my $items='';
1.800     albertel 5379:    foreach my $item (@$storearr) {
                   5380:        $items.=&escape($item).'&';
1.191     harris41 5381:    }
1.984     neumanie 5382: 
1.27      www      5383:    $items=~s/\&$//;
1.620     albertel 5384:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5385:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5386:    my $uhome=&homeserver($uname,$udomain);
                   5387:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5388: }
                   5389: 
                   5390: # -------------------------------------------------------------- dump interface
                   5391: 
                   5392: sub dump {
1.1166    raeburn  5393:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5394:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5395:     if (!$uname) { $uname=$env{'user.name'}; }
                   5396:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5397: 
1.755     albertel 5398:     if ($regexp) {
                   5399: 	$regexp=&escape($regexp);
                   5400:     } else {
                   5401: 	$regexp='.';
                   5402:     }
1.1166    raeburn  5403:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5404:     my @pairs=split(/\&/,$rep);
                   5405:     my %returnhash=();
1.1098    foxr     5406:     if (!($rep =~ /^error/ )) {
                   5407: 	foreach my $item (@pairs) {
                   5408: 	    my ($key,$value)=split(/=/,$item,2);
                   5409: 	    $key = &unescape($key);
                   5410: 	    next if ($key =~ /^error: 2 /);
                   5411: 	    $returnhash{$key}=&thaw_unescape($value);
                   5412: 	}
1.755     albertel 5413:     }
                   5414:     return %returnhash;
1.407     www      5415: }
                   5416: 
1.1098    foxr     5417: 
1.717     albertel 5418: # --------------------------------------------------------- dumpstore interface
                   5419: 
                   5420: sub dumpstore {
                   5421:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5422:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5423:    if (!$uname) { $uname=$env{'user.name'}; }
                   5424:    my $uhome=&homeserver($uname,$udomain);
                   5425:    if ($regexp) {
                   5426:        $regexp=&escape($regexp);
                   5427:    } else {
                   5428:        $regexp='.';
                   5429:    }
                   5430:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5431:    my @pairs=split(/\&/,$rep);
                   5432:    my %returnhash=();
                   5433:    foreach my $item (@pairs) {
                   5434:        my ($key,$value)=split(/=/,$item,2);
                   5435:        next if ($key =~ /^error: 2 /);
                   5436:        $returnhash{$key}=&thaw_unescape($value);
                   5437:    }
                   5438:    return %returnhash;
1.717     albertel 5439: }
                   5440: 
1.407     www      5441: # -------------------------------------------------------------- keys interface
                   5442: 
                   5443: sub getkeys {
                   5444:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5445:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5446:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5447:    my $uhome=&homeserver($uname,$udomain);
                   5448:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5449:    my @keyarray=();
1.800     albertel 5450:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5451:       next if ($key =~ /^error: 2 /);
1.800     albertel 5452:       push(@keyarray,&unescape($key));
1.407     www      5453:    }
                   5454:    return @keyarray;
1.318     matthew  5455: }
                   5456: 
1.319     matthew  5457: # --------------------------------------------------------------- currentdump
                   5458: sub currentdump {
1.328     matthew  5459:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5460:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5461:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5462:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5463:    my $uhome = &homeserver($sname,$sdom);
                   5464:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5465:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5466:    #
1.318     matthew  5467:    my %returnhash=();
1.319     matthew  5468:    #
                   5469:    if ($rep eq "unknown_cmd") { 
                   5470:        # an old lond will not know currentdump
                   5471:        # Do a dump and make it look like a currentdump
1.822     albertel 5472:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5473:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5474:        my %hash = @tmp;
                   5475:        @tmp=();
1.424     matthew  5476:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5477:    } else {
                   5478:        my @pairs=split(/\&/,$rep);
1.800     albertel 5479:        foreach my $pair (@pairs) {
                   5480:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5481:            my ($symb,$param) = split(/:/,$key);
                   5482:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5483:                                                         &thaw_unescape($value);
1.319     matthew  5484:        }
1.191     harris41 5485:    }
1.12      www      5486:    return %returnhash;
1.424     matthew  5487: }
                   5488: 
                   5489: sub convert_dump_to_currentdump{
                   5490:     my %hash = %{shift()};
                   5491:     my %returnhash;
                   5492:     # Code ripped from lond, essentially.  The only difference
                   5493:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5494:     # we might run in to problems with parameter names =~ /^v\./
                   5495:     while (my ($key,$value) = each(%hash)) {
                   5496:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5497: 	$symb  = &unescape($symb);
                   5498: 	$param = &unescape($param);
1.424     matthew  5499:         next if ($v eq 'version' || $symb eq 'keys');
                   5500:         next if (exists($returnhash{$symb}) &&
                   5501:                  exists($returnhash{$symb}->{$param}) &&
                   5502:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5503:         $returnhash{$symb}->{$param}=$value;
                   5504:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5505:     }
                   5506:     #
                   5507:     # Remove all of the keys in the hashes which keep track of
                   5508:     # the version of the parameter.
                   5509:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5510:         # use a foreach because we are going to delete from the hash.
                   5511:         foreach my $key (keys(%$param_hash)) {
                   5512:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5513:         }
                   5514:     }
                   5515:     return \%returnhash;
1.12      www      5516: }
                   5517: 
1.627     albertel 5518: # ------------------------------------------------------ critical inc interface
                   5519: 
                   5520: sub cinc {
                   5521:     return &inc(@_,'critical');
                   5522: }
                   5523: 
1.449     matthew  5524: # --------------------------------------------------------------- inc interface
                   5525: 
                   5526: sub inc {
1.627     albertel 5527:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5528:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5529:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5530:     my $uhome=&homeserver($uname,$udomain);
                   5531:     my $items='';
                   5532:     if (! ref($store)) {
                   5533:         # got a single value, so use that instead
                   5534:         $items = &escape($store).'=&';
                   5535:     } elsif (ref($store) eq 'SCALAR') {
                   5536:         $items = &escape($$store).'=&';        
                   5537:     } elsif (ref($store) eq 'ARRAY') {
                   5538:         $items = join('=&',map {&escape($_);} @{$store});
                   5539:     } elsif (ref($store) eq 'HASH') {
                   5540:         while (my($key,$value) = each(%{$store})) {
                   5541:             $items.= &escape($key).'='.&escape($value).'&';
                   5542:         }
                   5543:     }
                   5544:     $items=~s/\&$//;
1.627     albertel 5545:     if ($critical) {
                   5546: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5547:     } else {
                   5548: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5549:     }
1.449     matthew  5550: }
                   5551: 
1.12      www      5552: # --------------------------------------------------------------- put interface
                   5553: 
                   5554: sub put {
1.134     albertel 5555:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5556:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5557:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5558:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5559:    my $items='';
1.800     albertel 5560:    foreach my $item (keys(%$storehash)) {
                   5561:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5562:    }
1.12      www      5563:    $items=~s/\&$//;
1.134     albertel 5564:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5565: }
                   5566: 
1.631     albertel 5567: # ------------------------------------------------------------ newput interface
                   5568: 
                   5569: sub newput {
                   5570:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5571:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5572:    if (!$uname) { $uname=$env{'user.name'}; }
                   5573:    my $uhome=&homeserver($uname,$udomain);
                   5574:    my $items='';
                   5575:    foreach my $key (keys(%$storehash)) {
                   5576:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5577:    }
                   5578:    $items=~s/\&$//;
                   5579:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5580: }
                   5581: 
                   5582: # ---------------------------------------------------------  putstore interface
                   5583: 
1.524     raeburn  5584: sub putstore {
1.715     albertel 5585:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5586:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5587:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5588:    my $uhome=&homeserver($uname,$udomain);
                   5589:    my $items='';
1.715     albertel 5590:    foreach my $key (keys(%$storehash)) {
                   5591:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5592:    }
1.715     albertel 5593:    $items=~s/\&$//;
1.716     albertel 5594:    my $esc_symb=&escape($symb);
                   5595:    my $esc_v=&escape($version);
1.715     albertel 5596:    my $reply =
1.716     albertel 5597:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5598: 	      $uhome);
                   5599:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5600:        # gfall back to way things use to be done
1.715     albertel 5601:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5602: 			    $uname);
1.524     raeburn  5603:    }
1.715     albertel 5604:    return $reply;
                   5605: }
                   5606: 
                   5607: sub old_putstore {
1.716     albertel 5608:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5609:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5610:     if (!$uname) { $uname=$env{'user.name'}; }
                   5611:     my $uhome=&homeserver($uname,$udomain);
                   5612:     my %newstorehash;
1.800     albertel 5613:     foreach my $item (keys(%$storehash)) {
                   5614: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5615: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5616:     }
                   5617:     my $items='';
                   5618:     my %allitems = ();
1.800     albertel 5619:     foreach my $item (keys(%newstorehash)) {
                   5620: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5621: 	    my $key = $1.':keys:'.$2;
                   5622: 	    $allitems{$key} .= $3.':';
                   5623: 	}
1.800     albertel 5624: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5625:     }
1.800     albertel 5626:     foreach my $item (keys(%allitems)) {
                   5627: 	$allitems{$item} =~ s/\:$//;
                   5628: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5629:     }
                   5630:     $items=~s/\&$//;
                   5631:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5632: }
                   5633: 
1.47      www      5634: # ------------------------------------------------------ critical put interface
                   5635: 
                   5636: sub cput {
1.134     albertel 5637:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5638:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5639:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5640:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5641:    my $items='';
1.800     albertel 5642:    foreach my $item (keys(%$storehash)) {
                   5643:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5644:    }
1.47      www      5645:    $items=~s/\&$//;
1.134     albertel 5646:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5647: }
                   5648: 
                   5649: # -------------------------------------------------------------- eget interface
                   5650: 
                   5651: sub eget {
1.133     albertel 5652:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5653:    my $items='';
1.800     albertel 5654:    foreach my $item (@$storearr) {
                   5655:        $items.=&escape($item).'&';
1.191     harris41 5656:    }
1.12      www      5657:    $items=~s/\&$//;
1.620     albertel 5658:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5659:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5660:    my $uhome=&homeserver($uname,$udomain);
                   5661:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5662:    my @pairs=split(/\&/,$rep);
                   5663:    my %returnhash=();
1.42      www      5664:    my $i=0;
1.800     albertel 5665:    foreach my $item (@$storearr) {
                   5666:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5667:       $i++;
1.191     harris41 5668:    }
1.12      www      5669:    return %returnhash;
                   5670: }
                   5671: 
1.667     albertel 5672: # ------------------------------------------------------------ tmpput interface
                   5673: sub tmpput {
1.802     raeburn  5674:     my ($storehash,$server,$context)=@_;
1.667     albertel 5675:     my $items='';
1.800     albertel 5676:     foreach my $item (keys(%$storehash)) {
                   5677: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5678:     }
                   5679:     $items=~s/\&$//;
1.802     raeburn  5680:     if (defined($context)) {
                   5681:         $items .= ':'.&escape($context);
                   5682:     }
1.667     albertel 5683:     return &reply("tmpput:$items",$server);
                   5684: }
                   5685: 
                   5686: # ------------------------------------------------------------ tmpget interface
                   5687: sub tmpget {
1.688     albertel 5688:     my ($token,$server)=@_;
                   5689:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5690:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5691:     my %returnhash;
                   5692:     foreach my $item (split(/\&/,$rep)) {
                   5693: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5694:         next if ($key =~ /^error: 2 /);
1.667     albertel 5695: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5696:     }
                   5697:     return %returnhash;
                   5698: }
                   5699: 
1.1113    raeburn  5700: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5701: sub tmpdel {
                   5702:     my ($token,$server)=@_;
                   5703:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5704:     return &reply("tmpdel:$token",$server);
                   5705: }
                   5706: 
1.1172.2.13  raeburn  5707: # ------------------------------------------------------------ get_timebased_id
                   5708: 
                   5709: sub get_timebased_id {
                   5710:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5711:         $maxtries) = @_;
                   5712:     my ($newid,$error,$dellock);
                   5713:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5714:         return ('','ok','invalid call to get suffix');
                   5715:     }
                   5716: 
                   5717: # set defaults for any optional args for which values were not supplied
                   5718:     if ($who eq '') {
                   5719:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5720:     }
                   5721:     if (!$locktries) {
                   5722:         $locktries = 3;
                   5723:     }
                   5724:     if (!$maxtries) {
                   5725:         $maxtries = 10;
                   5726:     }
                   5727: 
                   5728:     if (($cdom eq '') || ($cnum eq '')) {
                   5729:         if ($env{'request.course.id'}) {
                   5730:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5731:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5732:         }
                   5733:         if (($cdom eq '') || ($cnum eq '')) {
                   5734:             return ('','ok','call to get suffix not in course context');
                   5735:         }
                   5736:     }
                   5737: 
                   5738: # construct locking item
                   5739:     my $lockhash = {
                   5740:                       $prefix."\0".'locked_'.$keyid => $who,
                   5741:                    };
                   5742:     my $tries = 0;
                   5743: 
                   5744: # attempt to get lock on nohist_$namespace file
                   5745:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5746:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5747:         $tries ++;
                   5748:         sleep 1;
                   5749:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5750:     }
                   5751: 
                   5752: # attempt to get unique identifier, based on current timestamp
                   5753:     if ($gotlock eq 'ok') {
                   5754:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5755:         my $id = time;
                   5756:         $newid = $id;
                   5757:         my $idtries = 0;
                   5758:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5759:             if ($idtype eq 'concat') {
                   5760:                 $newid = $id.$idtries;
                   5761:             } else {
                   5762:                 $newid ++;
                   5763:             }
                   5764:             $idtries ++;
                   5765:         }
                   5766:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5767:             my %new_item =  (
                   5768:                               $prefix."\0".$newid => $who,
                   5769:                             );
                   5770:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5771:                                                  $cdom,$cnum);
                   5772:             if ($putresult ne 'ok') {
                   5773:                 undef($newid);
                   5774:                 $error = 'error saving new item: '.$putresult;
                   5775:             }
                   5776:         } else {
                   5777:              $error = ('error: no unique suffix available for the new item ');
                   5778:         }
                   5779: #  remove lock
                   5780:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5781:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5782:     } else {
                   5783:         $error = "error: could not obtain lockfile\n";
                   5784:         $dellock = 'ok';
                   5785:     }
                   5786:     return ($newid,$dellock,$error);
                   5787: }
                   5788: 
1.765     albertel 5789: # -------------------------------------------------- portfolio access checking
                   5790: 
                   5791: sub portfolio_access {
1.766     albertel 5792:     my ($requrl) = @_;
1.765     albertel 5793:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5794:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5795:     if ($result) {
                   5796:         my %setters;
                   5797:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5798:             my ($startblock,$endblock) =
                   5799:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5800:             if ($startblock && $endblock) {
                   5801:                 return 'B';
                   5802:             }
                   5803:         } else {
                   5804:             my ($startblock,$endblock) =
                   5805:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5806:             if ($startblock && $endblock) {
                   5807:                 return 'B';
                   5808:             }
                   5809:         }
                   5810:     }
1.765     albertel 5811:     if ($result eq 'ok') {
1.766     albertel 5812:        return 'F';
1.765     albertel 5813:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5814:        return 'A';
1.765     albertel 5815:     }
1.766     albertel 5816:     return '';
1.765     albertel 5817: }
                   5818: 
                   5819: sub get_portfolio_access {
1.767     albertel 5820:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5821: 
                   5822:     if (!ref($access_hash)) {
                   5823: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5824: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5825: 						   $file_name);
                   5826: 	$access_hash = $access_controls{$file_name};
                   5827:     }
                   5828: 
1.765     albertel 5829:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5830:     my $now = time;
                   5831:     if (ref($access_hash) eq 'HASH') {
                   5832:         foreach my $key (keys(%{$access_hash})) {
                   5833:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5834:             if ($start > $now) {
                   5835:                 next;
                   5836:             }
                   5837:             if ($end && $end<$now) {
                   5838:                 next;
                   5839:             }
                   5840:             if ($scope eq 'public') {
                   5841:                 $public = $key;
                   5842:                 last;
                   5843:             } elsif ($scope eq 'guest') {
                   5844:                 $guest = $key;
                   5845:             } elsif ($scope eq 'domains') {
                   5846:                 push(@domains,$key);
                   5847:             } elsif ($scope eq 'users') {
                   5848:                 push(@users,$key);
                   5849:             } elsif ($scope eq 'course') {
                   5850:                 push(@courses,$key);
                   5851:             } elsif ($scope eq 'group') {
                   5852:                 push(@groups,$key);
                   5853:             }
                   5854:         }
                   5855:         if ($public) {
                   5856:             return 'ok';
                   5857:         }
                   5858:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5859:             if ($guest) {
                   5860:                 return $guest;
                   5861:             }
                   5862:         } else {
                   5863:             if (@domains > 0) {
                   5864:                 foreach my $domkey (@domains) {
                   5865:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5866:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5867:                             return 'ok';
                   5868:                         }
                   5869:                     }
                   5870:                 }
                   5871:             }
                   5872:             if (@users > 0) {
                   5873:                 foreach my $userkey (@users) {
1.865     raeburn  5874:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5875:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5876:                             if (ref($item) eq 'HASH') {
                   5877:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5878:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5879:                                     return 'ok';
                   5880:                                 }
                   5881:                             }
                   5882:                         }
                   5883:                     } 
1.765     albertel 5884:                 }
                   5885:             }
                   5886:             my %roleshash;
                   5887:             my @courses_and_groups = @courses;
                   5888:             push(@courses_and_groups,@groups); 
                   5889:             if (@courses_and_groups > 0) {
                   5890:                 my (%allgroups,%allroles); 
                   5891:                 my ($start,$end,$role,$sec,$group);
                   5892:                 foreach my $envkey (%env) {
1.1060    raeburn  5893:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5894:                         my $cid = $2.'_'.$3; 
                   5895:                         if ($1 eq 'gr') {
                   5896:                             $group = $4;
                   5897:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5898:                         } else {
                   5899:                             if ($4 eq '') {
                   5900:                                 $sec = 'none';
                   5901:                             } else {
                   5902:                                 $sec = $4;
                   5903:                             }
                   5904:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5905:                         }
1.811     albertel 5906:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5907:                         my $cid = $2.'_'.$3;
                   5908:                         if ($4 eq '') {
                   5909:                             $sec = 'none';
                   5910:                         } else {
                   5911:                             $sec = $4;
                   5912:                         }
                   5913:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5914:                     }
                   5915:                 }
                   5916:                 if (keys(%allroles) == 0) {
                   5917:                     return;
                   5918:                 }
                   5919:                 foreach my $key (@courses_and_groups) {
                   5920:                     my %content = %{$$access_hash{$key}};
                   5921:                     my $cnum = $content{'number'};
                   5922:                     my $cdom = $content{'domain'};
                   5923:                     my $cid = $cdom.'_'.$cnum;
                   5924:                     if (!exists($allroles{$cid})) {
                   5925:                         next;
                   5926:                     }    
                   5927:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5928:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5929:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5930:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5931:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5932:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5933:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5934:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5935:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5936:                                         if (grep/^all$/,@sections) {
                   5937:                                             return 'ok';
                   5938:                                         } else {
                   5939:                                             if (grep/^$sec$/,@sections) {
                   5940:                                                 return 'ok';
                   5941:                                             }
                   5942:                                         }
                   5943:                                     }
                   5944:                                 }
                   5945:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5946:                                     if (grep/^none$/,@groups) {
                   5947:                                         return 'ok';
                   5948:                                     }
                   5949:                                 } else {
                   5950:                                     if (grep/^all$/,@groups) {
                   5951:                                         return 'ok';
                   5952:                                     } 
                   5953:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5954:                                         if (grep/^$group$/,@groups) {
                   5955:                                             return 'ok';
                   5956:                                         }
                   5957:                                     }
                   5958:                                 } 
                   5959:                             }
                   5960:                         }
                   5961:                     }
                   5962:                 }
                   5963:             }
                   5964:             if ($guest) {
                   5965:                 return $guest;
                   5966:             }
                   5967:         }
                   5968:     }
                   5969:     return;
                   5970: }
                   5971: 
                   5972: sub course_group_datechecker {
                   5973:     my ($dates,$now,$status) = @_;
                   5974:     my ($start,$end) = split(/\./,$dates);
                   5975:     if (!$start && !$end) {
                   5976:         return 'ok';
                   5977:     }
                   5978:     if (grep/^active$/,@{$status}) {
                   5979:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5980:             return 'ok';
                   5981:         }
                   5982:     }
                   5983:     if (grep/^previous$/,@{$status}) {
                   5984:         if ($end > $now ) {
                   5985:             return 'ok';
                   5986:         }
                   5987:     }
                   5988:     if (grep/^future$/,@{$status}) {
                   5989:         if ($start > $now) {
                   5990:             return 'ok';
                   5991:         }
                   5992:     }
                   5993:     return; 
                   5994: }
                   5995: 
                   5996: sub parse_portfolio_url {
                   5997:     my ($url) = @_;
                   5998: 
                   5999:     my ($type,$udom,$unum,$group,$file_name);
                   6000:     
1.823     albertel 6001:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6002: 	$type = 1;
                   6003:         $udom = $1;
                   6004:         $unum = $2;
                   6005:         $file_name = $3;
1.823     albertel 6006:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6007: 	$type = 2;
                   6008:         $udom = $1;
                   6009:         $unum = $2;
                   6010:         $group = $3;
                   6011:         $file_name = $3.'/'.$4;
                   6012:     }
                   6013:     if (wantarray) {
                   6014: 	return ($type,$udom,$unum,$file_name,$group);
                   6015:     }
                   6016:     return $type;
                   6017: }
                   6018: 
                   6019: sub is_portfolio_url {
                   6020:     my ($url) = @_;
                   6021:     return scalar(&parse_portfolio_url($url));
                   6022: }
                   6023: 
1.798     raeburn  6024: sub is_portfolio_file {
                   6025:     my ($file) = @_;
1.820     raeburn  6026:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6027:         return 1;
                   6028:     }
                   6029:     return;
                   6030: }
                   6031: 
1.976     raeburn  6032: sub usertools_access {
1.1084    raeburn  6033:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6034:     my ($access,%tools);
                   6035:     if ($context eq '') {
                   6036:         $context = 'tools';
                   6037:     }
                   6038:     if ($context eq 'requestcourses') {
                   6039:         %tools = (
                   6040:                       official   => 1,
                   6041:                       unofficial => 1,
1.1006    raeburn  6042:                       community  => 1,
1.985     raeburn  6043:                  );
1.1172.2.9  raeburn  6044:     } elsif ($context eq 'requestauthor') {
                   6045:         %tools = (
                   6046:                       requestauthor => 1,
                   6047:                  );
1.985     raeburn  6048:     } else {
                   6049:         %tools = (
                   6050:                       aboutme   => 1,
                   6051:                       blog      => 1,
1.1172.2.6  raeburn  6052:                       webdav    => 1,
1.985     raeburn  6053:                       portfolio => 1,
                   6054:                  );
                   6055:     }
1.976     raeburn  6056:     return if (!defined($tools{$tool}));
                   6057: 
                   6058:     if ((!defined($udom)) || (!defined($uname))) {
                   6059:         $udom = $env{'user.domain'};
                   6060:         $uname = $env{'user.name'};
                   6061:     }
                   6062: 
1.978     raeburn  6063:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6064:         if ($action ne 'reload') {
1.985     raeburn  6065:             if ($context eq 'requestcourses') {
                   6066:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6067:             } elsif ($context eq 'requestauthor') {
                   6068:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6069:             } else {
                   6070:                 return $env{'environment.availabletools.'.$tool};
                   6071:             }
                   6072:         }
1.976     raeburn  6073:     }
                   6074: 
1.1172.2.9  raeburn  6075:     my ($toolstatus,$inststatus,$envkey);
                   6076:     if ($context eq 'requestauthor') {
                   6077:         $envkey = $context;
                   6078:     } else {
                   6079:         $envkey = $context.'.'.$tool;
                   6080:     }
1.976     raeburn  6081: 
1.985     raeburn  6082:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6083:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6084:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6085:         $inststatus = $env{'environment.inststatus'};
                   6086:     } else {
1.1084    raeburn  6087:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6088:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6089:             $inststatus = $userenvref->{'inststatus'};
                   6090:         } else {
1.1172.2.9  raeburn  6091:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6092:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6093:             $inststatus = $userenv{'inststatus'};
                   6094:         }
1.976     raeburn  6095:     }
                   6096: 
                   6097:     if ($toolstatus ne '') {
                   6098:         if ($toolstatus) {
                   6099:             $access = 1;
                   6100:         } else {
                   6101:             $access = 0;
                   6102:         }
                   6103:         return $access;
                   6104:     }
                   6105: 
1.1084    raeburn  6106:     my ($is_adv,%domdef);
                   6107:     if (ref($is_advref) eq 'HASH') {
                   6108:         $is_adv = $is_advref->{'is_adv'};
                   6109:     } else {
                   6110:         $is_adv = &is_advanced_user($udom,$uname);
                   6111:     }
                   6112:     if (ref($domdefref) eq 'HASH') {
                   6113:         %domdef = %{$domdefref};
                   6114:     } else {
                   6115:         %domdef = &get_domain_defaults($udom);
                   6116:     }
1.976     raeburn  6117:     if (ref($domdef{$tool}) eq 'HASH') {
                   6118:         if ($is_adv) {
                   6119:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6120:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6121:                     $access = 1;
                   6122:                 } else {
                   6123:                     $access = 0;
                   6124:                 }
                   6125:                 return $access;
                   6126:             }
                   6127:         }
                   6128:         if ($inststatus ne '') {
                   6129:             my ($hasaccess,$hasnoaccess);
                   6130:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6131:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6132:                     if ($domdef{$tool}{$affiliation}) {
                   6133:                         $hasaccess = 1;
                   6134:                     } else {
                   6135:                         $hasnoaccess = 1;
                   6136:                     }
                   6137:                 }
                   6138:             }
                   6139:             if ($hasaccess || $hasnoaccess) {
                   6140:                 if ($hasaccess) {
                   6141:                     $access = 1;
                   6142:                 } elsif ($hasnoaccess) {
                   6143:                     $access = 0; 
                   6144:                 }
                   6145:                 return $access;
                   6146:             }
                   6147:         } else {
                   6148:             if ($domdef{$tool}{'default'} ne '') {
                   6149:                 if ($domdef{$tool}{'default'}) {
                   6150:                     $access = 1;
                   6151:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6152:                     $access = 0;
                   6153:                 }
                   6154:                 return $access;
                   6155:             }
                   6156:         }
                   6157:     } else {
1.1172.2.6  raeburn  6158:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6159:             $access = 1;
                   6160:         } else {
                   6161:             $access = 0;
                   6162:         }
1.976     raeburn  6163:         return $access;
                   6164:     }
                   6165: }
                   6166: 
1.1050    raeburn  6167: sub is_course_owner {
                   6168:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6169:     if (($udom eq '') || ($uname eq '')) {
                   6170:         $udom = $env{'user.domain'};
                   6171:         $uname = $env{'user.name'};
                   6172:     }
                   6173:     unless (($udom eq '') || ($uname eq '')) {
                   6174:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6175:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6176:                 return 1;
                   6177:             } else {
                   6178:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6179:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6180:                     return 1;
                   6181:                 }
                   6182:             }
                   6183:         }
                   6184:     }
                   6185:     return;
                   6186: }
                   6187: 
1.976     raeburn  6188: sub is_advanced_user {
                   6189:     my ($udom,$uname) = @_;
1.1085    raeburn  6190:     if ($udom ne '' && $uname ne '') {
                   6191:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6192:             if (wantarray) {
                   6193:                 return ($env{'user.adv'},$env{'user.author'});
                   6194:             } else {
                   6195:                 return $env{'user.adv'};
                   6196:             }
1.1085    raeburn  6197:         }
                   6198:     }
1.976     raeburn  6199:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6200:     my %allroles;
1.1128    raeburn  6201:     my ($is_adv,$is_author);
1.976     raeburn  6202:     foreach my $role (keys(%roleshash)) {
                   6203:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6204:         my $area = '/'.$tdomain.'/'.$trest;
                   6205:         if ($sec ne '') {
                   6206:             $area .= '/'.$sec;
                   6207:         }
                   6208:         if (($area ne '') && ($trole ne '')) {
                   6209:             my $spec=$trole.'.'.$area;
                   6210:             if ($trole =~ /^cr\//) {
                   6211:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6212:             } elsif ($trole ne 'gr') {
                   6213:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6214:             }
1.1128    raeburn  6215:             if ($trole eq 'au') {
                   6216:                 $is_author = 1;
                   6217:             }
1.976     raeburn  6218:         }
                   6219:     }
                   6220:     foreach my $role (keys(%allroles)) {
                   6221:         last if ($is_adv);
                   6222:         foreach my $item (split(/:/,$allroles{$role})) {
                   6223:             if ($item ne '') {
                   6224:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6225:                 if ($privilege eq 'adv') {
                   6226:                     $is_adv = 1;
                   6227:                     last;
                   6228:                 }
                   6229:             }
                   6230:         }
                   6231:     }
1.1128    raeburn  6232:     if (wantarray) {
                   6233:         return ($is_adv,$is_author);
                   6234:     }
1.976     raeburn  6235:     return $is_adv;
                   6236: }
1.798     raeburn  6237: 
1.1035    raeburn  6238: sub check_can_request {
1.1036    raeburn  6239:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6240:     my $canreq = 0;
                   6241:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6242:     my @options = ('approval','validate','autolimit');
                   6243:     my $optregex = join('|',@options);
                   6244:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6245:         foreach my $type (@{$types}) {
                   6246:             if (&usertools_access($env{'user.name'},
                   6247:                                   $env{'user.domain'},
                   6248:                                   $type,undef,'requestcourses')) {
                   6249:                 $canreq ++;
1.1036    raeburn  6250:                 if (ref($request_domains) eq 'HASH') {
                   6251:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6252:                 }
1.1035    raeburn  6253:                 if ($dom eq $env{'user.domain'}) {
                   6254:                     $can_request->{$type} = 1;
                   6255:                 }
                   6256:             }
                   6257:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6258:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6259:                 if (@curr > 0) {
1.1036    raeburn  6260:                     foreach my $item (@curr) {
                   6261:                         if (ref($request_domains) eq 'HASH') {
                   6262:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6263:                             if ($otherdom ne '') {
                   6264:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6265:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6266:                                         push(@{$request_domains->{$type}},$otherdom);
                   6267:                                     }
                   6268:                                 } else {
                   6269:                                     push(@{$request_domains->{$type}},$otherdom);
                   6270:                                 }
                   6271:                             }
                   6272:                         }
                   6273:                     }
                   6274:                     unless($dom eq $env{'user.domain'}) {
                   6275:                         $canreq ++;
1.1035    raeburn  6276:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6277:                             $can_request->{$type} = 1;
                   6278:                         }
                   6279:                     }
                   6280:                 }
                   6281:             }
                   6282:         }
                   6283:     }
                   6284:     return $canreq;
                   6285: }
                   6286: 
1.341     www      6287: # ---------------------------------------------- Custom access rule evaluation
                   6288: 
                   6289: sub customaccess {
                   6290:     my ($priv,$uri)=@_;
1.807     albertel 6291:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6292:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6293:     $udom = &LONCAPA::clean_domain($udom);
                   6294:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6295:     my $access=0;
1.800     albertel 6296:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6297: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6298: 	if ($type eq 'user') {
                   6299: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6300: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6301: 		if ($tdom) {
                   6302: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6303: 		}
1.896     albertel 6304: 		if ($tuname) {
                   6305: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6306: 		}
                   6307: 		$access=($effect eq 'allow');
                   6308: 		last;
                   6309: 	    }
                   6310: 	} else {
                   6311: 	    if ($role) {
                   6312: 		if ($role ne $urole) { next; }
                   6313: 	    }
                   6314: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6315: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6316: 		if ($tdom) {
                   6317: 		    if ($tdom ne $udom) { next; }
                   6318: 		}
                   6319: 		if ($tcrs) {
                   6320: 		    if ($tcrs ne $ucrs) { next; }
                   6321: 		}
                   6322: 		if ($tsec) {
                   6323: 		    if ($tsec ne $usec) { next; }
                   6324: 		}
                   6325: 		$access=($effect eq 'allow');
                   6326: 		last;
                   6327: 	    }
                   6328: 	    if ($realm eq '' && $role eq '') {
                   6329: 		$access=($effect eq 'allow');
                   6330: 	    }
1.402     bowersj2 6331: 	}
1.341     www      6332:     }
                   6333:     return $access;
                   6334: }
                   6335: 
1.103     harris41 6336: # ------------------------------------------------- Check for a user privilege
1.12      www      6337: 
                   6338: sub allowed {
1.810     raeburn  6339:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6340:     my $ver_orguri=$uri;
1.439     www      6341:     $uri=&deversion($uri);
1.152     www      6342:     my $orguri=$uri;
1.52      www      6343:     $uri=&declutter($uri);
1.809     raeburn  6344: 
1.810     raeburn  6345:     if ($priv eq 'evb') {
                   6346: # Evade communication block restrictions for specified role in a course
                   6347:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6348:             return $1;
                   6349:         } else {
                   6350:             return;
                   6351:         }
                   6352:     }
                   6353: 
1.620     albertel 6354:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6355: # Free bre access to adm and meta resources
1.775     albertel 6356:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6357: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6358: 	&& ($priv eq 'bre')) {
1.14      www      6359: 	return 'F';
1.159     www      6360:     }
                   6361: 
1.545     banghart 6362: # Free bre access to user's own portfolio contents
1.714     raeburn  6363:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6364:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6365: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6366:         my %setters;
                   6367:         my ($startblock,$endblock) = 
                   6368:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6369:         if ($startblock && $endblock) {
                   6370:             return 'B';
                   6371:         } else {
                   6372:             return 'F';
                   6373:         }
1.545     banghart 6374:     }
                   6375: 
1.762     raeburn  6376: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6377:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6378:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6379:         if (exists($env{'request.course.id'})) {
                   6380:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6381:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6382:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6383:                 my $courseprivid=$env{'request.course.id'};
                   6384:                 $courseprivid=~s/\_/\//;
                   6385:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6386:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6387:                     return $1; 
1.762     raeburn  6388:                 } else {
                   6389:                     if ($env{'request.course.sec'}) {
                   6390:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6391:                     }
                   6392:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6393:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6394:                         return $2;
                   6395:                     }
1.714     raeburn  6396:                 }
                   6397:             }
                   6398:         }
                   6399:     }
                   6400: 
1.159     www      6401: # Free bre to public access
                   6402: 
                   6403:     if ($priv eq 'bre') {
1.238     www      6404:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6405: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6406:            return 'F'; 
                   6407:         }
1.238     www      6408:         if ($copyright eq 'priv') {
                   6409:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6410: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6411: 		return '';
                   6412:             }
                   6413:         }
                   6414:         if ($copyright eq 'domain') {
                   6415:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6416: 	    unless (($env{'user.domain'} eq $1) ||
                   6417:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6418: 		return '';
                   6419:             }
1.262     matthew  6420:         }
1.620     albertel 6421:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6422:             # Library role, so allow browsing of resources in this domain.
                   6423:             return 'F';
1.238     www      6424:         }
1.341     www      6425:         if ($copyright eq 'custom') {
                   6426: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6427:         }
1.14      www      6428:     }
1.264     matthew  6429:     # Domain coordinator is trying to create a course
1.620     albertel 6430:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6431:         # uri is the requested domain in this case.
                   6432:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6433:         # a role of dc for the domain in question.
1.620     albertel 6434:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6435:     }
1.29      www      6436: 
1.52      www      6437:     my $thisallowed='';
                   6438:     my $statecond=0;
                   6439:     my $courseprivid='';
                   6440: 
1.1039    raeburn  6441:     my $ownaccess;
1.1043    raeburn  6442:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6443:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6444:         if ($uri eq '') {
                   6445:             $ownaccess = 1;
                   6446:         } else {
                   6447:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6448:                 my $udom = $env{'user.domain'};
                   6449:                 my $uname = $env{'user.name'};
                   6450:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6451:                     $ownaccess = 1;
1.1040    raeburn  6452:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6453:                     unless ($uri =~ m{\.\./}) {
                   6454:                         $ownaccess = 1;
                   6455:                     }
                   6456:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6457:                     my $now = time;
                   6458:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6459:                         my $adom = $1;
                   6460:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6461:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6462:                                 my ($start,$end) = split('.',$env{$key});
                   6463:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6464:                                     $ownaccess = 1;
                   6465:                                     last;
                   6466:                                 }
                   6467:                             }
                   6468:                         }
                   6469:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6470:                         my $adom = $1;
                   6471:                         my $aname = $2;
1.1042    raeburn  6472:                         foreach my $role ('ca','aa') { 
                   6473:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6474:                                 my ($start,$end) =
                   6475:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6476:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6477:                                     $ownaccess = 1;
                   6478:                                     last;
                   6479:                                 }
1.1039    raeburn  6480:                             }
                   6481:                         }
                   6482:                     }
                   6483:                 }
                   6484:             }
                   6485:         }
                   6486:     }
                   6487: 
1.52      www      6488: # Course
                   6489: 
1.620     albertel 6490:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6491:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6492:             $thisallowed.=$1;
                   6493:         }
1.52      www      6494:     }
1.29      www      6495: 
1.52      www      6496: # Domain
                   6497: 
1.620     albertel 6498:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6499:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6500:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6501:             $thisallowed.=$1;
                   6502:         }
1.12      www      6503:     }
1.52      www      6504: 
1.1141    raeburn  6505: # User who is not author or co-author might still be able to edit
                   6506: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6507:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6508:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6509:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6510:             $thisallowed.=$1;
                   6511:         }
                   6512:     }
                   6513: 
1.52      www      6514: # Course: uri itself is a course
1.66      www      6515:     my $courseuri=$uri;
                   6516:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6517:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6518: 
1.620     albertel 6519:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6520:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6521:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6522:             $thisallowed.=$1;
                   6523:         }
1.12      www      6524:     }
1.29      www      6525: 
1.665     albertel 6526: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6527: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6528:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6529: 	$thisallowed='';
1.671     raeburn  6530:         my ($match)=&is_on_map($uri);
                   6531:         if ($match) {
                   6532:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6533:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6534:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6535:                 if (@blockers > 0) {
                   6536:                     $thisallowed = 'B';
                   6537:                 } else {
                   6538:                     $thisallowed.=$1;
                   6539:                 }
1.671     raeburn  6540:             }
                   6541:         } else {
1.705     albertel 6542:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6543:             if ($refuri) {
                   6544:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6545:                     $thisallowed='F';
1.671     raeburn  6546:                 } else {
                   6547:                     $refuri=&declutter($refuri);
                   6548:                     my ($match) = &is_on_map($refuri);
                   6549:                     if ($match) {
1.1162    raeburn  6550:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6551:                         if (@blockers > 0) {
                   6552:                             $thisallowed = 'B';
                   6553:                         } else {
                   6554:                             $thisallowed='F';
                   6555:                         }
1.671     raeburn  6556:                     }
1.669     raeburn  6557:                 }
1.671     raeburn  6558:             }
                   6559:         }
1.314     www      6560:     }
1.492     albertel 6561: 
1.766     albertel 6562:     if ($priv eq 'bre'
                   6563: 	&& $thisallowed ne 'F' 
                   6564: 	&& $thisallowed ne '2'
                   6565: 	&& &is_portfolio_url($uri)) {
                   6566: 	$thisallowed = &portfolio_access($uri);
                   6567:     }
                   6568:     
1.52      www      6569: # Full access at system, domain or course-wide level? Exit.
1.29      www      6570:     if ($thisallowed=~/F/) {
                   6571: 	return 'F';
                   6572:     }
                   6573: 
1.52      www      6574: # If this is generating or modifying users, exit with special codes
1.29      www      6575: 
1.643     www      6576:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6577: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6578: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6579: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6580: 	    unless ($auname) { return $thisallowed; }
                   6581: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6582: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6583: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6584: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6585: 	}
1.52      www      6586: 	return $thisallowed;
                   6587:     }
                   6588: #
1.103     harris41 6589: # Gathered so far: system, domain and course wide privileges
1.52      www      6590: #
                   6591: # Course: See if uri or referer is an individual resource that is part of 
                   6592: # the course
                   6593: 
1.620     albertel 6594:     if ($env{'request.course.id'}) {
1.232     www      6595: 
1.620     albertel 6596:        $courseprivid=$env{'request.course.id'};
                   6597:        if ($env{'request.course.sec'}) {
                   6598:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6599:        }
                   6600:        $courseprivid=~s/\_/\//;
                   6601:        my $checkreferer=1;
1.232     www      6602:        my ($match,$cond)=&is_on_map($uri);
                   6603:        if ($match) {
                   6604:            $statecond=$cond;
1.620     albertel 6605:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6606:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6607:                my $value = $1;
                   6608:                if ($priv eq 'bre') {
                   6609:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6610:                    if (@blockers > 0) {
                   6611:                        $thisallowed = 'B';
                   6612:                    } else {
                   6613:                        $thisallowed.=$value;
                   6614:                    }
                   6615:                } else {
                   6616:                    $thisallowed.=$value;
                   6617:                }
1.52      www      6618:                $checkreferer=0;
                   6619:            }
1.29      www      6620:        }
1.83      www      6621:        
1.148     www      6622:        if ($checkreferer) {
1.620     albertel 6623: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6624:             unless ($refuri) {
1.800     albertel 6625:                 foreach my $key (keys(%env)) {
                   6626: 		    if ($key=~/^httpref\..*\*/) {
                   6627: 			my $pattern=$key;
1.156     www      6628:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6629:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6630:                         $pattern=~s/\//\\\//g;
1.152     www      6631:                         if ($orguri=~/$pattern/) {
1.800     albertel 6632: 			    $refuri=$env{$key};
1.148     www      6633:                         }
                   6634:                     }
1.191     harris41 6635:                 }
1.148     www      6636:             }
1.232     www      6637: 
1.148     www      6638:          if ($refuri) { 
1.152     www      6639: 	  $refuri=&declutter($refuri);
1.232     www      6640:           my ($match,$cond)=&is_on_map($refuri);
                   6641:             if ($match) {
                   6642:               my $refstatecond=$cond;
1.620     albertel 6643:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6644:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6645:                   my $value = $1;
                   6646:                   if ($priv eq 'bre') {
                   6647:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6648:                       if (@blockers > 0) {
                   6649:                           $thisallowed = 'B';
                   6650:                       } else {
                   6651:                           $thisallowed.=$value;
                   6652:                       }
                   6653:                   } else {
                   6654:                       $thisallowed.=$value;
                   6655:                   }
1.53      www      6656:                   $uri=$refuri;
                   6657:                   $statecond=$refstatecond;
1.52      www      6658:               }
                   6659:           }
1.148     www      6660:         }
1.29      www      6661:        }
1.52      www      6662:    }
1.29      www      6663: 
1.52      www      6664: #
1.103     harris41 6665: # Gathered now: all privileges that could apply, and condition number
1.52      www      6666: # 
                   6667: #
                   6668: # Full or no access?
                   6669: #
1.29      www      6670: 
1.52      www      6671:     if ($thisallowed=~/F/) {
                   6672: 	return 'F';
                   6673:     }
1.29      www      6674: 
1.52      www      6675:     unless ($thisallowed) {
                   6676:         return '';
                   6677:     }
1.29      www      6678: 
1.52      www      6679: # Restrictions exist, deal with them
                   6680: #
                   6681: #   C:according to course preferences
                   6682: #   R:according to resource settings
                   6683: #   L:unless locked
                   6684: #   X:according to user session state
                   6685: #
                   6686: 
                   6687: # Possibly locked functionality, check all courses
1.54      www      6688: # Locks might take effect only after 10 minutes cache expiration for other
                   6689: # courses, and 2 minutes for current course
1.52      www      6690: 
                   6691:     my $envkey;
                   6692:     if ($thisallowed=~/L/) {
1.1000    raeburn  6693:         foreach $envkey (keys(%env)) {
1.54      www      6694:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6695:                my $courseid=$2;
                   6696:                my $roleid=$1.'.'.$2;
1.92      www      6697:                $courseid=~s/^\///;
1.54      www      6698:                my $expiretime=600;
1.620     albertel 6699:                if ($env{'request.role'} eq $roleid) {
1.54      www      6700: 		  $expiretime=120;
                   6701:                }
                   6702: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6703:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6704:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6705: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6706:                }
1.620     albertel 6707:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6708:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6709: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6710:                        &log($env{'user.domain'},$env{'user.name'},
                   6711:                             $env{'user.home'},
1.57      www      6712:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6713:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6714:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6715: 		       return '';
                   6716:                    }
                   6717:                }
1.620     albertel 6718:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6719:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6720: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6721:                        &log($env{'user.domain'},$env{'user.name'},
                   6722:                             $env{'user.home'},
1.57      www      6723:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6724:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6725:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6726: 		       return '';
                   6727:                    }
                   6728:                }
                   6729: 	   }
1.29      www      6730:        }
1.52      www      6731:     }
                   6732:    
                   6733: #
                   6734: # Rest of the restrictions depend on selected course
                   6735: #
                   6736: 
1.620     albertel 6737:     unless ($env{'request.course.id'}) {
1.766     albertel 6738: 	if ($thisallowed eq 'A') {
                   6739: 	    return 'A';
1.814     raeburn  6740:         } elsif ($thisallowed eq 'B') {
                   6741:             return 'B';
1.766     albertel 6742: 	} else {
                   6743: 	    return '1';
                   6744: 	}
1.52      www      6745:     }
1.29      www      6746: 
1.52      www      6747: #
                   6748: # Now user is definitely in a course
                   6749: #
1.53      www      6750: 
                   6751: 
                   6752: # Course preferences
                   6753: 
                   6754:    if ($thisallowed=~/C/) {
1.620     albertel 6755:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6756:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6757:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6758: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6759: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6760: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6761: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6762: 			$env{'request.course.id'});
                   6763: 	   }
1.237     www      6764:            return '';
                   6765:        }
                   6766: 
1.620     albertel 6767:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6768: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6769: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6770: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6771: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6772: 			$env{'request.course.id'});
                   6773: 	   }
1.54      www      6774:            return '';
                   6775:        }
1.53      www      6776:    }
                   6777: 
                   6778: # Resource preferences
                   6779: 
                   6780:    if ($thisallowed=~/R/) {
1.620     albertel 6781:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6782:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6783: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6784: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6785: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6786: 	   }
                   6787: 	   return '';
1.54      www      6788:        }
1.53      www      6789:    }
1.30      www      6790: 
1.246     www      6791: # Restricted by state or randomout?
1.30      www      6792: 
1.52      www      6793:    if ($thisallowed=~/X/) {
1.620     albertel 6794:       if ($env{'acc.randomout'}) {
1.579     albertel 6795: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6796:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6797:             return ''; 
                   6798:          }
1.247     www      6799:       }
                   6800:       if (&condval($statecond)) {
1.52      www      6801: 	 return '2';
                   6802:       } else {
                   6803:          return '';
                   6804:       }
                   6805:    }
1.30      www      6806: 
1.766     albertel 6807:     if ($thisallowed eq 'A') {
                   6808: 	return 'A';
1.814     raeburn  6809:     } elsif ($thisallowed eq 'B') {
                   6810:         return 'B';
1.766     albertel 6811:     }
1.52      www      6812:    return 'F';
1.232     www      6813: }
1.1162    raeburn  6814: 
1.1172.2.13  raeburn  6815: # ------------------------------------------- Check construction space access
                   6816: 
                   6817: sub constructaccess {
                   6818:     my ($url,$setpriv)=@_;
                   6819: 
                   6820: # We do not allow editing of previous versions of files
                   6821:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6822: 
                   6823: # Get username and domain from URL
                   6824:     my ($ownername,$ownerdomain,$ownerhome);
                   6825: 
                   6826:     ($ownerdomain,$ownername) =
                   6827:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6828: 
                   6829: # The URL does not really point to any authorspace, forget it
                   6830:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6831: 
                   6832: # Now we need to see if the user has access to the authorspace of
                   6833: # $ownername at $ownerdomain
                   6834: 
                   6835:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6836: # Real author for this?
                   6837:        $ownerhome = $env{'user.home'};
                   6838:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6839:           return ($ownername,$ownerdomain,$ownerhome);
                   6840:        }
                   6841:     } else {
                   6842: # Co-author for this?
                   6843:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6844:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6845:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6846:             return ($ownername,$ownerdomain,$ownerhome);
                   6847:         }
                   6848:     }
                   6849: 
                   6850: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6851: # we might as well leave
                   6852:    unless ($setpriv) { return ''; }
                   6853: 
                   6854: # Backdoor access?
                   6855:     my $allowed=&allowed('eco',$ownerdomain);
                   6856: # Nope
                   6857:     unless ($allowed) { return ''; }
                   6858: # Looks like we may have access, but could be locked by the owner of the construction space
                   6859:     if ($allowed eq 'U') {
                   6860:         my %blocked=&get('environment',['domcoord.author'],
                   6861:                          $ownerdomain,$ownername);
                   6862: # Is blocked by owner
                   6863:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6864:     }
                   6865:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6866: # Grant temporary access
                   6867:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6868:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6869:         if (!$update) { $update = $then; }
                   6870:         my $refresh=$env{'user.refresh.time'};
                   6871:         if (!$refresh) { $refresh = $update; }
                   6872:         my $now = time;
                   6873:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6874:                            $now,'ca','constructaccess');
                   6875:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6876:         return($ownername,$ownerdomain,$ownerhome);
                   6877:     }
                   6878: # No business here
                   6879:     return '';
                   6880: }
                   6881: 
1.1162    raeburn  6882: sub get_comm_blocks {
                   6883:     my ($cdom,$cnum) = @_;
                   6884:     if ($cdom eq '' || $cnum eq '') {
                   6885:         return unless ($env{'request.course.id'});
                   6886:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6887:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6888:     }
                   6889:     my %commblocks;
                   6890:     my $hashid=$cdom.'_'.$cnum;
                   6891:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6892:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6893:         %commblocks = %{$blocksref};
                   6894:     } else {
                   6895:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6896:         my $cachetime = 600;
                   6897:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6898:     }
                   6899:     return %commblocks;
                   6900: }
                   6901: 
                   6902: sub has_comm_blocking {
                   6903:     my ($priv,$symb,$uri,$blocks) = @_;
                   6904:     return unless ($env{'request.course.id'});
                   6905:     return unless ($priv eq 'bre');
                   6906:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6907:     my %commblocks;
                   6908:     if (ref($blocks) eq 'HASH') {
                   6909:         %commblocks = %{$blocks};
                   6910:     } else {
                   6911:         %commblocks = &get_comm_blocks();
                   6912:     }
                   6913:     return unless (keys(%commblocks) > 0);
                   6914:     if (!$symb) { $symb=&symbread($uri,1); }
                   6915:     my ($map,$resid,undef)=&decode_symb($symb);
                   6916:     my %tocheck = (
                   6917:                     maps      => $map,
                   6918:                     resources => $symb,
                   6919:                   );
                   6920:     my @blockers;
                   6921:     my $now = time;
1.1163    raeburn  6922:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6923:     foreach my $block (keys(%commblocks)) {
                   6924:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6925:             my ($start,$end) = ($1,$2);
                   6926:             if ($start <= $now && $end >= $now) {
                   6927:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6928:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6929:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6930:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6931:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6932:                                     push(@blockers,$block);
                   6933:                                 }
                   6934:                             }
                   6935:                         }
                   6936:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6937:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6938:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6939:                                     push(@blockers,$block);
                   6940:                                 }
                   6941:                             }
                   6942:                         }
                   6943:                     }
                   6944:                 }
                   6945:             }
                   6946:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6947:             my $item = $1;
1.1163    raeburn  6948:             my @to_test;
1.1162    raeburn  6949:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6950:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6951:                     my $check_interval;
                   6952:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6953:                         my @interval;
                   6954:                         my $type = 'map';
                   6955:                         if ($item eq 'course') {
                   6956:                             $type = 'course';
                   6957:                             @interval=&EXT("resource.0.interval");
                   6958:                         } else {
                   6959:                             if ($item =~ /___\d+___/) {
                   6960:                                 $type = 'resource';
                   6961:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6962:                                 if (ref($navmap)) {                        
                   6963:                                     my $res = $navmap->getBySymb($item); 
                   6964:                                     push(@to_test,$res);
                   6965:                                 }
1.1162    raeburn  6966:                             } else {
                   6967:                                 my $mapsymb = &symbread($item,1);
                   6968:                                 if ($mapsymb) {
                   6969:                                     if (ref($navmap)) {
                   6970:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6971:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6972:                                         foreach my $res (@to_test) {
1.1162    raeburn  6973:                                             my $symb = $res->symb();
                   6974:                                             next if ($symb eq $mapsymb);
                   6975:                                             if ($symb ne '') {
                   6976:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6977:                                                 last;
                   6978:                                             }
                   6979:                                         }
                   6980:                                     }
                   6981:                                 }
                   6982:                             }
                   6983:                         }
                   6984:                         if ($interval[0] =~ /\d+/) {
                   6985:                             my $first_access;
                   6986:                             if ($type eq 'resource') {
                   6987:                                 $first_access=&get_first_access($interval[1],$item);
                   6988:                             } elsif ($type eq 'map') {
                   6989:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6990:                             } else {
                   6991:                                 $first_access=&get_first_access($interval[1]);
                   6992:                             }
                   6993:                             if ($first_access) {
                   6994:                                 my $timesup = $first_access+$interval[0];
                   6995:                                 if ($timesup > $now) {
1.1163    raeburn  6996:                                     foreach my $res (@to_test) {
                   6997:                                         if ($res->is_problem()) {
                   6998:                                             if ($res->completable()) {
                   6999:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7000:                                                     push(@blockers,$block);
                   7001:                                                 }
                   7002:                                                 last;
                   7003:                                             }
                   7004:                                         }
1.1162    raeburn  7005:                                     }
                   7006:                                 }
                   7007:                             }
                   7008:                         }
                   7009:                     }
                   7010:                 }
                   7011:             }
                   7012:         }
                   7013:     }
                   7014:     return @blockers;
                   7015: }
                   7016: 
                   7017: sub check_docs_block {
                   7018:     my ($docsblock,$tocheck) =@_;
                   7019:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7020:         return;
                   7021:     }
                   7022:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7023:         if ($tocheck->{'maps'}) {
                   7024:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7025:                 return 1;
                   7026:             }
                   7027:         }
                   7028:     }
                   7029:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7030:         if ($tocheck->{'resources'}) {
                   7031:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7032:                 return 1;
                   7033:             }
                   7034:         }
                   7035:     }
                   7036:     return;
                   7037: }
                   7038: 
1.1133    foxr     7039: #
                   7040: #   Removes the versino from a URI and
                   7041: #   splits it in to its filename and path to the filename.
                   7042: #   Seems like File::Basename could have done this more clearly.
                   7043: #   Parameters:
                   7044: #      $uri   - input URI
                   7045: #   Returns:
                   7046: #     Two element list consisting of 
                   7047: #     $pathname  - the URI up to and excluding the trailing /
                   7048: #     $filename  - The part of the URI following the last /
                   7049: #  NOTE:
                   7050: #    Another realization of this is simply:
                   7051: #    use File::Basename;
                   7052: #    ...
                   7053: #    $uri = shift;
                   7054: #    $filename = basename($uri);
                   7055: #    $path     = dirname($uri);
                   7056: #    return ($filename, $path);
                   7057: #
                   7058: #     The implementation below is probably faster however.
                   7059: #
1.710     albertel 7060: sub split_uri_for_cond {
                   7061:     my $uri=&deversion(&declutter(shift));
                   7062:     my @uriparts=split(/\//,$uri);
                   7063:     my $filename=pop(@uriparts);
                   7064:     my $pathname=join('/',@uriparts);
                   7065:     return ($pathname,$filename);
                   7066: }
1.232     www      7067: # --------------------------------------------------- Is a resource on the map?
                   7068: 
                   7069: sub is_on_map {
1.710     albertel 7070:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7071:     #Trying to find the conditional for the file
1.620     albertel 7072:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7073: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7074:     if ($match) {
1.289     bowersj2 7075: 	return (1,$1);
                   7076:     } else {
1.434     www      7077: 	return (0,0);
1.289     bowersj2 7078:     }
1.12      www      7079: }
                   7080: 
1.427     www      7081: # --------------------------------------------------------- Get symb from alias
                   7082: 
                   7083: sub get_symb_from_alias {
                   7084:     my $symb=shift;
                   7085:     my ($map,$resid,$url)=&decode_symb($symb);
                   7086: # Already is a symb
                   7087:     if ($url) { return $symb; }
                   7088: # Must be an alias
                   7089:     my $aliassymb='';
                   7090:     my %bighash;
1.620     albertel 7091:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7092:                             &GDBM_READER(),0640)) {
                   7093:         my $rid=$bighash{'mapalias_'.$symb};
                   7094: 	if ($rid) {
                   7095: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7096: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7097: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7098: 	}
                   7099:         untie %bighash;
                   7100:     }
                   7101:     return $aliassymb;
                   7102: }
                   7103: 
1.12      www      7104: # ----------------------------------------------------------------- Define Role
                   7105: 
                   7106: sub definerole {
                   7107:   if (allowed('mcr','/')) {
                   7108:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7109:     foreach my $role (split(':',$sysrole)) {
                   7110: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7111:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7112:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7113: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7114:                return "refused:s:$crole&$cqual"; 
                   7115:             }
                   7116:         }
1.191     harris41 7117:     }
1.800     albertel 7118:     foreach my $role (split(':',$domrole)) {
                   7119: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7120:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7121:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7122: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7123:                return "refused:d:$crole&$cqual"; 
                   7124:             }
                   7125:         }
1.191     harris41 7126:     }
1.800     albertel 7127:     foreach my $role (split(':',$courole)) {
                   7128: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7129:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7130:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7131: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7132:                return "refused:c:$crole&$cqual"; 
                   7133:             }
                   7134:         }
1.191     harris41 7135:     }
1.620     albertel 7136:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7137:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7138: 	        "rolesdef_$rolename=".
                   7139:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7140:     return reply($command,$env{'user.home'});
1.12      www      7141:   } else {
                   7142:     return 'refused';
                   7143:   }
1.105     harris41 7144: }
                   7145: 
                   7146: # ---------------- Make a metadata query against the network of library servers
                   7147: 
                   7148: sub metadata_query {
1.244     matthew  7149:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7150:     my %rhash;
1.845     albertel 7151:     my %libserv = &all_library();
1.244     matthew  7152:     my @server_list = (defined($server_array) ? @$server_array
                   7153:                                               : keys(%libserv) );
                   7154:     for my $server (@server_list) {
1.118     harris41 7155: 	unless ($custom or $customshow) {
                   7156: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7157: 	    $rhash{$server}=$reply;
                   7158: 	}
                   7159: 	else {
                   7160: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7161: 			     &escape($custom).':'.&escape($customshow),
                   7162: 			     $server);
                   7163: 	    $rhash{$server}=$reply;
                   7164: 	}
1.112     harris41 7165:     }
1.118     harris41 7166:     return \%rhash;
1.240     www      7167: }
                   7168: 
                   7169: # ----------------------------------------- Send log queries and wait for reply
                   7170: 
                   7171: sub log_query {
                   7172:     my ($uname,$udom,$query,%filters)=@_;
                   7173:     my $uhome=&homeserver($uname,$udom);
                   7174:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7175:     my $uhost=&hostname($uhome);
1.800     albertel 7176:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7177:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7178:                        $uhome);
1.479     albertel 7179:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7180:     return get_query_reply($queryid);
                   7181: }
                   7182: 
1.818     raeburn  7183: # -------------------------- Update MySQL table for portfolio file
                   7184: 
                   7185: sub update_portfolio_table {
1.821     raeburn  7186:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7187:     if ($group ne '') {
                   7188:         $file_name =~s /^\Q$group\E//;
                   7189:     }
1.818     raeburn  7190:     my $homeserver = &homeserver($uname,$udom);
                   7191:     my $queryid=
1.821     raeburn  7192:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7193:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7194:     my $reply = &get_query_reply($queryid);
                   7195:     return $reply;
                   7196: }
                   7197: 
1.899     raeburn  7198: # -------------------------- Update MySQL allusers table
                   7199: 
                   7200: sub update_allusers_table {
                   7201:     my ($uname,$udom,$names) = @_;
                   7202:     my $homeserver = &homeserver($uname,$udom);
                   7203:     my $queryid=
                   7204:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7205:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7206:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7207:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7208:                'generation='.&escape($names->{'generation'}).'%%'.
                   7209:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7210:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7211:     return;
1.899     raeburn  7212: }
                   7213: 
1.508     raeburn  7214: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7215: 
                   7216: sub fetch_enrollment_query {
1.511     raeburn  7217:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7218:     my $homeserver;
1.547     raeburn  7219:     my $maxtries = 1;
1.508     raeburn  7220:     if ($context eq 'automated') {
                   7221:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7222:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7223:     } else {
                   7224:         $homeserver = &homeserver($cnum,$dom);
                   7225:     }
1.838     albertel 7226:     my $host=&hostname($homeserver);
1.506     raeburn  7227:     my $cmd = '';
1.1000    raeburn  7228:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7229:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7230:     }
                   7231:     $cmd =~ s/%%$//;
                   7232:     $cmd = &escape($cmd);
                   7233:     my $query = 'fetchenrollment';
1.620     albertel 7234:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7235:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7236:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7237:         return 'error: '.$queryid;
                   7238:     }
1.506     raeburn  7239:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7240:     my $tries = 1;
                   7241:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7242:         $reply = &get_query_reply($queryid);
                   7243:         $tries ++;
                   7244:     }
1.526     raeburn  7245:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7246:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7247:     } else {
1.901     albertel 7248:         my @responses = split(/:/,$reply);
1.515     raeburn  7249:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7250:             foreach my $line (@responses) {
                   7251:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7252:                 $$replyref{$key} = $value;
                   7253:             }
                   7254:         } else {
1.1117    foxr     7255:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7256:             foreach my $line (@responses) {
                   7257:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7258:                 $$replyref{$key} = $value;
                   7259:                 if ($value > 0) {
1.800     albertel 7260:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7261:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7262:                         my $destname = $pathname.'/'.$filename;
                   7263:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7264:                         if ($xml_classlist =~ /^error/) {
                   7265:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7266:                         } else {
1.506     raeburn  7267:                             if ( open(FILE,">$destname") ) {
                   7268:                                 print FILE &unescape($xml_classlist);
                   7269:                                 close(FILE);
1.526     raeburn  7270:                             } else {
                   7271:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7272:                             }
                   7273:                         }
                   7274:                     }
                   7275:                 }
                   7276:             }
                   7277:         }
                   7278:         return 'ok';
                   7279:     }
                   7280:     return 'error';
                   7281: }
                   7282: 
1.242     www      7283: sub get_query_reply {
                   7284:     my $queryid=shift;
1.1117    foxr     7285:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7286:     my $reply='';
                   7287:     for (1..100) {
                   7288: 	sleep 2;
                   7289:         if (-e $replyfile.'.end') {
1.448     albertel 7290: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7291: 		$reply = join('',<$fh>);
                   7292: 		close($fh);
1.240     www      7293: 	   } else { return 'error: reply_file_error'; }
1.242     www      7294:            return &unescape($reply);
                   7295: 	}
1.240     www      7296:     }
1.242     www      7297:     return 'timeout:'.$queryid;
1.240     www      7298: }
                   7299: 
                   7300: sub courselog_query {
1.241     www      7301: #
                   7302: # possible filters:
                   7303: # url: url or symb
                   7304: # username
                   7305: # domain
                   7306: # action: view, submit, grade
                   7307: # start: timestamp
                   7308: # end: timestamp
                   7309: #
1.240     www      7310:     my (%filters)=@_;
1.620     albertel 7311:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7312:     if ($filters{'url'}) {
                   7313: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7314:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7315:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7316:     }
1.620     albertel 7317:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7318:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7319:     return &log_query($cname,$cdom,'courselog',%filters);
                   7320: }
                   7321: 
                   7322: sub userlog_query {
1.858     raeburn  7323: #
                   7324: # possible filters:
                   7325: # action: log check role
                   7326: # start: timestamp
                   7327: # end: timestamp
                   7328: #
1.240     www      7329:     my ($uname,$udom,%filters)=@_;
                   7330:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7331: }
                   7332: 
1.506     raeburn  7333: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7334: 
                   7335: sub auto_run {
1.508     raeburn  7336:     my ($cnum,$cdom) = @_;
1.876     raeburn  7337:     my $response = 0;
                   7338:     my $settings;
                   7339:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7340:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7341:         $settings = $domconfig{'autoenroll'};
                   7342:         if ($settings->{'run'} eq '1') {
                   7343:             $response = 1;
                   7344:         }
                   7345:     } else {
1.934     raeburn  7346:         my $homeserver;
                   7347:         if (&is_course($cdom,$cnum)) {
                   7348:             $homeserver = &homeserver($cnum,$cdom);
                   7349:         } else {
                   7350:             $homeserver = &domain($cdom,'primary');
                   7351:         }
                   7352:         if ($homeserver ne 'no_host') {
                   7353:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7354:         }
1.876     raeburn  7355:     }
1.506     raeburn  7356:     return $response;
                   7357: }
1.776     albertel 7358: 
1.506     raeburn  7359: sub auto_get_sections {
1.508     raeburn  7360:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7361:     my $homeserver;
                   7362:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7363:         $homeserver = &homeserver($cnum,$cdom);
                   7364:     }
                   7365:     if (!defined($homeserver)) { 
                   7366:         if ($cdom =~ /^$match_domain$/) {
                   7367:             $homeserver = &domain($cdom,'primary');
                   7368:         }
                   7369:     }
                   7370:     my @secs;
                   7371:     if (defined($homeserver)) {
                   7372:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7373:         unless ($response eq 'refused') {
                   7374:             @secs = split(/:/,$response);
                   7375:         }
1.506     raeburn  7376:     }
                   7377:     return @secs;
                   7378: }
1.776     albertel 7379: 
1.506     raeburn  7380: sub auto_new_course {
1.1099    raeburn  7381:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7382:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7383:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7384:     return $response;
                   7385: }
1.776     albertel 7386: 
1.506     raeburn  7387: sub auto_validate_courseID {
1.508     raeburn  7388:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7389:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7390:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7391:     return $response;
                   7392: }
1.776     albertel 7393: 
1.1007    raeburn  7394: sub auto_validate_instcode {
1.1020    raeburn  7395:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7396:     my ($homeserver,$response);
                   7397:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7398:         $homeserver = &homeserver($cnum,$cdom);
                   7399:     }
                   7400:     if (!defined($homeserver)) {
                   7401:         if ($cdom =~ /^$match_domain$/) {
                   7402:             $homeserver = &domain($cdom,'primary');
                   7403:         }
                   7404:     }
1.1065    raeburn  7405:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7406:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7407:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7408:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7409: }
                   7410: 
1.506     raeburn  7411: sub auto_create_password {
1.873     raeburn  7412:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7413:     my ($homeserver,$response);
1.506     raeburn  7414:     my $create_passwd = 0;
                   7415:     my $authchk = '';
1.873     raeburn  7416:     if ($udom =~ /^$match_domain$/) {
                   7417:         $homeserver = &domain($udom,'primary');
                   7418:     }
                   7419:     if ($homeserver eq '') {
                   7420:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7421:             $homeserver = &homeserver($cnum,$cdom);
                   7422:         }
                   7423:     }
                   7424:     if ($homeserver eq '') {
                   7425:         $authchk = 'nodomain';
1.506     raeburn  7426:     } else {
1.873     raeburn  7427:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7428:         if ($response eq 'refused') {
                   7429:             $authchk = 'refused';
                   7430:         } else {
1.901     albertel 7431:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7432:         }
1.506     raeburn  7433:     }
                   7434:     return ($authparam,$create_passwd,$authchk);
                   7435: }
                   7436: 
1.706     raeburn  7437: sub auto_photo_permission {
                   7438:     my ($cnum,$cdom,$students) = @_;
                   7439:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7440:     my ($outcome,$perm_reqd,$conditions) = 
                   7441: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7442:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7443: 	return (undef,undef);
                   7444:     }
1.706     raeburn  7445:     return ($outcome,$perm_reqd,$conditions);
                   7446: }
                   7447: 
                   7448: sub auto_checkphotos {
                   7449:     my ($uname,$udom,$pid) = @_;
                   7450:     my $homeserver = &homeserver($uname,$udom);
                   7451:     my ($result,$resulttype);
                   7452:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7453: 				   &escape($uname).':'.&escape($pid),
                   7454: 				   $homeserver));
1.709     albertel 7455:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7456: 	return (undef,undef);
                   7457:     }
1.706     raeburn  7458:     if ($outcome) {
                   7459:         ($result,$resulttype) = split(/:/,$outcome);
                   7460:     } 
                   7461:     return ($result,$resulttype);
                   7462: }
                   7463: 
                   7464: sub auto_photochoice {
                   7465:     my ($cnum,$cdom) = @_;
                   7466:     my $homeserver = &homeserver($cnum,$cdom);
                   7467:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7468: 						       &escape($cdom),
                   7469: 						       $homeserver)));
1.709     albertel 7470:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7471: 	return (undef,undef);
                   7472:     }
1.706     raeburn  7473:     return ($update,$comment);
                   7474: }
                   7475: 
                   7476: sub auto_photoupdate {
                   7477:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7478:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7479:     my $host=&hostname($homeserver);
1.706     raeburn  7480:     my $cmd = '';
                   7481:     my $maxtries = 1;
1.800     albertel 7482:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7483:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7484:     }
                   7485:     $cmd =~ s/%%$//;
                   7486:     $cmd = &escape($cmd);
                   7487:     my $query = 'institutionalphotos';
                   7488:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7489:     unless ($queryid=~/^\Q$host\E\_/) {
                   7490:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7491:         return 'error: '.$queryid;
                   7492:     }
                   7493:     my $reply = &get_query_reply($queryid);
                   7494:     my $tries = 1;
                   7495:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7496:         $reply = &get_query_reply($queryid);
                   7497:         $tries ++;
                   7498:     }
                   7499:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7500:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7501:     } else {
                   7502:         my @responses = split(/:/,$reply);
                   7503:         my $outcome = shift(@responses); 
                   7504:         foreach my $item (@responses) {
                   7505:             my ($key,$value) = split(/=/,$item);
                   7506:             $$photo{$key} = $value;
                   7507:         }
                   7508:         return $outcome;
                   7509:     }
                   7510:     return 'error';
                   7511: }
                   7512: 
1.521     raeburn  7513: sub auto_instcode_format {
1.793     albertel 7514:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7515: 	$cat_order) = @_;
1.521     raeburn  7516:     my $courses = '';
1.772     raeburn  7517:     my @homeservers;
1.521     raeburn  7518:     if ($caller eq 'global') {
1.841     albertel 7519: 	my %servers = &get_servers($codedom,'library');
                   7520: 	foreach my $tryserver (keys(%servers)) {
                   7521: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7522: 		push(@homeservers,$tryserver);
                   7523: 	    }
1.584     raeburn  7524:         }
1.1022    raeburn  7525:     } elsif ($caller eq 'requests') {
                   7526:         if ($codedom =~ /^$match_domain$/) {
                   7527:             my $chome = &domain($codedom,'primary');
                   7528:             unless ($chome eq 'no_host') {
                   7529:                 push(@homeservers,$chome);
                   7530:             }
                   7531:         }
1.521     raeburn  7532:     } else {
1.772     raeburn  7533:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7534:     }
1.793     albertel 7535:     foreach my $code (keys(%{$instcodes})) {
                   7536:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7537:     }
                   7538:     chop($courses);
1.772     raeburn  7539:     my $ok_response = 0;
                   7540:     my $response;
                   7541:     while (@homeservers > 0 && $ok_response == 0) {
                   7542:         my $server = shift(@homeservers); 
                   7543:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7544:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7545:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7546: 		split(/:/,$response);
1.772     raeburn  7547:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7548:             push(@{$codetitles},&str2array($codetitles_str));
                   7549:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7550:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7551:             $ok_response = 1;
                   7552:         }
                   7553:     }
                   7554:     if ($ok_response) {
1.521     raeburn  7555:         return 'ok';
1.772     raeburn  7556:     } else {
                   7557:         return $response;
1.521     raeburn  7558:     }
                   7559: }
                   7560: 
1.792     raeburn  7561: sub auto_instcode_defaults {
                   7562:     my ($domain,$returnhash,$code_order) = @_;
                   7563:     my @homeservers;
1.841     albertel 7564: 
                   7565:     my %servers = &get_servers($domain,'library');
                   7566:     foreach my $tryserver (keys(%servers)) {
                   7567: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7568: 	    push(@homeservers,$tryserver);
                   7569: 	}
1.792     raeburn  7570:     }
1.841     albertel 7571: 
1.792     raeburn  7572:     my $response;
1.841     albertel 7573:     foreach my $server (@homeservers) {
1.792     raeburn  7574:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7575:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7576: 	
                   7577: 	foreach my $pair (split(/\&/,$response)) {
                   7578: 	    my ($name,$value)=split(/\=/,$pair);
                   7579: 	    if ($name eq 'code_order') {
                   7580: 		@{$code_order} = split(/\&/,&unescape($value));
                   7581: 	    } else {
                   7582: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7583: 	    }
                   7584: 	}
                   7585: 	return 'ok';
1.792     raeburn  7586:     }
1.841     albertel 7587: 
                   7588:     return $response;
1.1003    raeburn  7589: }
                   7590: 
                   7591: sub auto_possible_instcodes {
1.1007    raeburn  7592:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7593:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7594:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7595:         return;
                   7596:     }
1.1003    raeburn  7597:     my (@homeservers,$uhome);
                   7598:     if (defined(&domain($domain,'primary'))) {
                   7599:         $uhome=&domain($domain,'primary');
                   7600:         push(@homeservers,&domain($domain,'primary'));
                   7601:     } else {
                   7602:         my %servers = &get_servers($domain,'library');
                   7603:         foreach my $tryserver (keys(%servers)) {
                   7604:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7605:                 push(@homeservers,$tryserver);
                   7606:             }
                   7607:         }
                   7608:     }
                   7609:     my $response;
                   7610:     foreach my $server (@homeservers) {
                   7611:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7612:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7613:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7614:             split(':',$response);
                   7615:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7616:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7617:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7618:             my ($name,$value)=split('=',$item);
                   7619:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7620:         }
                   7621:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7622:             my ($name,$value)=split('=',$item);
                   7623:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7624:         }
                   7625:         return 'ok';
                   7626:     }
                   7627:     return $response;
                   7628: }
1.792     raeburn  7629: 
1.1010    raeburn  7630: sub auto_courserequest_checks {
                   7631:     my ($dom) = @_;
1.1020    raeburn  7632:     my ($homeserver,%validations);
                   7633:     if ($dom =~ /^$match_domain$/) {
                   7634:         $homeserver = &domain($dom,'primary');
                   7635:     }
                   7636:     unless ($homeserver eq 'no_host') {
                   7637:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7638:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7639:             my @items = split(/&/,$response);
                   7640:             foreach my $item (@items) {
                   7641:                 my ($key,$value) = split('=',$item);
                   7642:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7643:             }
                   7644:         }
                   7645:     }
1.1010    raeburn  7646:     return %validations; 
                   7647: }
                   7648: 
1.1020    raeburn  7649: sub auto_courserequest_validation {
                   7650:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7651:     my ($homeserver,$response);
                   7652:     if ($dom =~ /^$match_domain$/) {
                   7653:         $homeserver = &domain($dom,'primary');
                   7654:     }
                   7655:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7656:           
1.1020    raeburn  7657:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7658:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7659:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7660:                                     $homeserver));
                   7661:     }
                   7662:     return $response;
                   7663: }
                   7664: 
1.777     albertel 7665: sub auto_validate_class_sec {
1.918     raeburn  7666:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7667:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7668:     my $ownerlist;
                   7669:     if (ref($owners) eq 'ARRAY') {
                   7670:         $ownerlist = join(',',@{$owners});
                   7671:     } else {
                   7672:         $ownerlist = $owners;
                   7673:     }
1.773     raeburn  7674:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7675:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7676:     return $response;
                   7677: }
                   7678: 
1.679     raeburn  7679: # ------------------------------------------------------- Course Group routines
                   7680: 
                   7681: sub get_coursegroups {
1.809     raeburn  7682:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7683:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7684: }
                   7685: 
1.679     raeburn  7686: sub modify_coursegroup {
                   7687:     my ($cdom,$cnum,$groupsettings) = @_;
                   7688:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7689: }
                   7690: 
1.809     raeburn  7691: sub toggle_coursegroup_status {
                   7692:     my ($cdom,$cnum,$group,$action) = @_;
                   7693:     my ($from_namespace,$to_namespace);
                   7694:     if ($action eq 'delete') {
                   7695:         $from_namespace = 'coursegroups';
                   7696:         $to_namespace = 'deleted_groups';
                   7697:     } else {
                   7698:         $from_namespace = 'deleted_groups';
                   7699:         $to_namespace = 'coursegroups';
                   7700:     }
                   7701:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7702:     if (my $tmp = &error(%curr_group)) {
                   7703:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7704:         return ('read error',$tmp);
                   7705:     } else {
                   7706:         my %savedsettings = %curr_group; 
1.809     raeburn  7707:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7708:         my $deloutcome;
                   7709:         if ($result eq 'ok') {
1.809     raeburn  7710:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7711:         } else {
                   7712:             return ('write error',$result);
                   7713:         }
                   7714:         if ($deloutcome eq 'ok') {
                   7715:             return 'ok';
                   7716:         } else {
                   7717:             return ('delete error',$deloutcome);
                   7718:         }
                   7719:     }
                   7720: }
                   7721: 
1.679     raeburn  7722: sub modify_group_roles {
1.957     raeburn  7723:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7724:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7725:     my $role = 'gr/'.&escape($userprivs);
                   7726:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7727:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7728:     if ($result eq 'ok') {
                   7729:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7730:     }
1.679     raeburn  7731:     return $result;
                   7732: }
                   7733: 
                   7734: sub modify_coursegroup_membership {
                   7735:     my ($cdom,$cnum,$membership) = @_;
                   7736:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7737:     return $result;
                   7738: }
                   7739: 
1.682     raeburn  7740: sub get_active_groups {
                   7741:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7742:     my $now = time;
                   7743:     my %groups = ();
                   7744:     foreach my $key (keys(%env)) {
1.811     albertel 7745:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7746:             my ($start,$end) = split(/\./,$env{$key});
                   7747:             if (($end!=0) && ($end<$now)) { next; }
                   7748:             if (($start!=0) && ($start>$now)) { next; }
                   7749:             if ($1 eq $cdom && $2 eq $cnum) {
                   7750:                 $groups{$3} = $env{$key} ;
                   7751:             }
                   7752:         }
                   7753:     }
                   7754:     return %groups;
                   7755: }
                   7756: 
1.683     raeburn  7757: sub get_group_membership {
                   7758:     my ($cdom,$cnum,$group) = @_;
                   7759:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7760: }
                   7761: 
                   7762: sub get_users_groups {
                   7763:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7764:     my @usersgroups;
1.683     raeburn  7765:     my $cachetime=1800;
                   7766: 
                   7767:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7768:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7769:     if (defined($cached)) {
1.734     albertel 7770:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7771:     } else {  
                   7772:         $grouplist = '';
1.816     raeburn  7773:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7774:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7775:         my $access_end = $env{'course.'.$courseid.
                   7776:                               '.default_enrollment_end_date'};
                   7777:         my $now = time;
                   7778:         foreach my $key (keys(%roleshash)) {
                   7779:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7780:                 my $group = $1;
                   7781:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7782:                     my $start = $2;
                   7783:                     my $end = $1;
                   7784:                     if ($start == -1) { next; } # deleted from group
                   7785:                     if (($start!=0) && ($start>$now)) { next; }
                   7786:                     if (($end!=0) && ($end<$now)) {
                   7787:                         if ($access_end && $access_end < $now) {
                   7788:                             if ($access_end - $end < 86400) {
                   7789:                                 push(@usersgroups,$group);
1.733     raeburn  7790:                             }
                   7791:                         }
1.817     raeburn  7792:                         next;
1.733     raeburn  7793:                     }
1.817     raeburn  7794:                     push(@usersgroups,$group);
1.683     raeburn  7795:                 }
                   7796:             }
                   7797:         }
1.817     raeburn  7798:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7799:         $grouplist = join(':',@usersgroups);
                   7800:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7801:     }
1.733     raeburn  7802:     return @usersgroups;
1.683     raeburn  7803: }
                   7804: 
                   7805: sub devalidate_getgroups_cache {
                   7806:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7807:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7808: 
1.683     raeburn  7809:     my $hashid="$udom:$uname:$courseid";
                   7810:     &devalidate_cache_new('getgroups',$hashid);
                   7811: }
                   7812: 
1.12      www      7813: # ------------------------------------------------------------------ Plain Text
                   7814: 
                   7815: sub plaintext {
1.988     raeburn  7816:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7817:     if ($short =~ m{^cr/}) {
1.758     albertel 7818: 	return (split('/',$short))[-1];
                   7819:     }
1.742     raeburn  7820:     if (!defined($cid)) {
                   7821:         $cid = $env{'request.course.id'};
                   7822:     }
                   7823:     my %rolenames = (
1.1008    raeburn  7824:                       Course    => 'std',
                   7825:                       Community => 'alt1',
1.742     raeburn  7826:                     );
1.1037    raeburn  7827:     if ($cid ne '') {
                   7828:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7829:             unless ($forcedefault) {
                   7830:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7831:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7832:                 return &Apache::lonlocal::mt($roletext);
                   7833:             }
                   7834:         }
                   7835:     }
                   7836:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7837:         (defined($rolenames{$type})) && 
                   7838:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7839:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7840:     } elsif ($cid ne '') {
                   7841:         my $crstype = $env{'course.'.$cid.'.type'};
                   7842:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7843:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7844:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7845:         }
1.742     raeburn  7846:     }
1.1037    raeburn  7847:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7848: }
                   7849: 
                   7850: # ----------------------------------------------------------------- Assign Role
                   7851: 
                   7852: sub assignrole {
1.957     raeburn  7853:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7854:         $context)=@_;
1.21      www      7855:     my $mrole;
                   7856:     if ($role =~ /^cr\//) {
1.393     www      7857:         my $cwosec=$url;
1.811     albertel 7858:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7859: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7860:            my $refused = 1;
                   7861:            if ($context eq 'requestcourses') {
                   7862:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7863:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7864:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7865:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7866:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7867:                            if ($crsenv{'internal.courseowner'} eq
                   7868:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7869:                                $refused = '';
                   7870:                            }
                   7871:                        }
                   7872:                    }
                   7873:                }
                   7874:            }
                   7875:            if ($refused) {
                   7876:                &logthis('Refused custom assignrole: '.
                   7877:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7878:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7879:                return 'refused';
                   7880:            }
1.104     www      7881:         }
1.21      www      7882:         $mrole='cr';
1.678     raeburn  7883:     } elsif ($role =~ /^gr\//) {
                   7884:         my $cwogrp=$url;
1.811     albertel 7885:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7886:         unless (&allowed('mdg',$cwogrp)) {
                   7887:             &logthis('Refused group assignrole: '.
                   7888:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7889:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7890:             return 'refused';
                   7891:         }
                   7892:         $mrole='gr';
1.21      www      7893:     } else {
1.82      www      7894:         my $cwosec=$url;
1.811     albertel 7895:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7896:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7897:             my $refused;
                   7898:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7899:                 if (!(&allowed('c'.$role,$url))) {
                   7900:                     $refused = 1;
                   7901:                 }
                   7902:             } else {
                   7903:                 $refused = 1;
                   7904:             }
1.947     raeburn  7905:             if ($refused) {
1.1045    raeburn  7906:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7907:                 if (!$selfenroll && $context eq 'course') {
                   7908:                     my %crsenv;
                   7909:                     if ($role eq 'cc' || $role eq 'co') {
                   7910:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7911:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7912:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7913:                                 if ($crsenv{'internal.courseowner'} eq 
                   7914:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7915:                                     $refused = '';
                   7916:                                 }
                   7917:                             }
                   7918:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7919:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7920:                                 if ($crsenv{'internal.courseowner'} eq 
                   7921:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7922:                                     $refused = '';
                   7923:                                 }
                   7924:                             }
                   7925:                         }
                   7926:                     }
                   7927:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7928:                     $refused = '';
1.1017    raeburn  7929:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7930:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7931:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7932:                         my $wrongcc;
                   7933:                         if ($cnum =~ /^$match_community$/) {
                   7934:                             $wrongcc = 1 if ($role eq 'cc');
                   7935:                         } else {
                   7936:                             $wrongcc = 1 if ($role eq 'co');
                   7937:                         }
                   7938:                         unless ($wrongcc) {
                   7939:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7940:                             if ($crsenv{'internal.courseowner'} eq 
                   7941:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7942:                                 $refused = '';
                   7943:                             }
1.1017    raeburn  7944:                         }
                   7945:                     }
1.1172.2.9  raeburn  7946:                 } elsif ($context eq 'requestauthor') {
                   7947:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7948:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7949:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7950:                             $refused = '';
                   7951:                         } else {
                   7952:                             my %domdefaults = &get_domain_defaults($udom);
                   7953:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7954:                                 my $checkbystatus;
                   7955:                                 if ($env{'user.adv'}) {
                   7956:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7957:                                     if ($disposition eq 'automatic') {
                   7958:                                         $refused = '';
                   7959:                                     } elsif ($disposition eq '') {
                   7960:                                         $checkbystatus = 1;
                   7961:                                     }
                   7962:                                 } else {
                   7963:                                     $checkbystatus = 1;
                   7964:                                 }
                   7965:                                 if ($checkbystatus) {
                   7966:                                     if ($env{'environment.inststatus'}) {
                   7967:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7968:                                         foreach my $type (@inststatuses) {
                   7969:                                             if (($type ne '') &&
                   7970:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7971:                                                 $refused = '';
                   7972:                                             }
                   7973:                                         }
                   7974:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7975:                                         $refused = '';
                   7976:                                     }
                   7977:                                 }
                   7978:                             }
                   7979:                         }
                   7980:                     }
1.1017    raeburn  7981:                 }
                   7982:                 if ($refused) {
1.947     raeburn  7983:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7984:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7985: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7986:                     return 'refused';
                   7987:                 }
1.932     raeburn  7988:             }
1.1131    raeburn  7989:         } elsif ($role eq 'au') {
                   7990:             if ($url ne '/'.$udom.'/') {
                   7991:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7992:                          ' to assign author role for '.$uname.':'.$udom.
                   7993:                          ' in domain: '.$url.' refused (wrong domain).');
                   7994:                 return 'refused';
                   7995:             }
1.104     www      7996:         }
1.21      www      7997:         $mrole=$role;
                   7998:     }
1.620     albertel 7999:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8000:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8001:     if ($end) { $command.='_'.$end; }
1.21      www      8002:     if ($start) {
                   8003: 	if ($end) { 
1.81      www      8004:            $command.='_'.$start; 
1.21      www      8005:         } else {
1.81      www      8006:            $command.='_0_'.$start;
1.21      www      8007:         }
                   8008:     }
1.739     raeburn  8009:     my $origstart = $start;
                   8010:     my $origend = $end;
1.957     raeburn  8011:     my $delflag;
1.357     www      8012: # actually delete
                   8013:     if ($deleteflag) {
1.373     www      8014: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8015: # modify command to delete the role
1.620     albertel 8016:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8017:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8018: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8019: # set start and finish to negative values for userrolelog
                   8020:            $start=-1;
                   8021:            $end=-1;
1.957     raeburn  8022:            $delflag = 1;
1.357     www      8023:         }
                   8024:     }
                   8025: # send command
1.349     www      8026:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8027: # log new user role if status is ok
1.349     www      8028:     if ($answer eq 'ok') {
1.663     raeburn  8029: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8030:         if (($role eq 'cc') || ($role eq 'in') ||
                   8031:             ($role eq 'ep') || ($role eq 'ad') ||
                   8032:             ($role eq 'ta') || ($role eq 'st') ||
                   8033:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8034:             ($role eq 'co')) {
1.1172.2.13  raeburn  8035: # for course roles, perform group memberships changes triggered by role change.
                   8036:             unless ($role =~ /^gr/) {
                   8037:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8038:                                                  $origstart,$selfenroll,$context);
                   8039:             }
1.1172.2.9  raeburn  8040:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8041:                            $selfenroll,$context);
                   8042:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8043:                  ($role eq 'au') || ($role eq 'dc')) {
                   8044:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8045:                            $context);
                   8046:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8047:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8048:                              $context);
                   8049:         }
1.1053    raeburn  8050:         if ($role eq 'cc') {
                   8051:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8052:         }
1.349     www      8053:     }
                   8054:     return $answer;
1.169     harris41 8055: }
                   8056: 
1.1053    raeburn  8057: sub autoupdate_coowners {
                   8058:     my ($url,$end,$start,$uname,$udom) = @_;
                   8059:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8060:     if (($cdom ne '') && ($cnum ne '')) {
                   8061:         my $now = time;
                   8062:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8063:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8064:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8065:             my $instcode = $coursehash{'internal.coursecode'};
                   8066:             if ($instcode ne '') {
1.1056    raeburn  8067:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8068:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8069:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8070:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8071:                         if ($result eq 'valid') {
                   8072:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8073:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8074:                                     push(@newcoowners,$coowner);
                   8075:                                 }
                   8076:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8077:                                     push(@newcoowners,$uname.':'.$udom);
                   8078:                                 }
                   8079:                                 @newcoowners = sort(@newcoowners);
                   8080:                             } else {
                   8081:                                 push(@newcoowners,$uname.':'.$udom);
                   8082:                             }
                   8083:                         } else {
                   8084:                             if ($coursehash{'internal.co-owners'}) {
                   8085:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8086:                                     unless ($coowner eq $uname.':'.$udom) {
                   8087:                                         push(@newcoowners,$coowner);
                   8088:                                     }
                   8089:                                 }
                   8090:                                 unless (@newcoowners > 0) {
                   8091:                                     $delcoowners = 1;
                   8092:                                     $coowners = '';
                   8093:                                 }
                   8094:                             }
                   8095:                         }
                   8096:                         if (@newcoowners || $delcoowners) {
                   8097:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8098:                                             $delcoowners,@newcoowners);
                   8099:                         }
                   8100:                     }
                   8101:                 }
                   8102:             }
                   8103:         }
                   8104:     }
                   8105: }
                   8106: 
                   8107: sub store_coowners {
                   8108:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8109:     my $cid = $cdom.'_'.$cnum;
                   8110:     my ($coowners,$delresult,$putresult);
                   8111:     if (@newcoowners) {
                   8112:         $coowners = join(',',@newcoowners);
                   8113:         my %coownershash = (
                   8114:                             'internal.co-owners' => $coowners,
                   8115:                            );
                   8116:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8117:         if ($putresult eq 'ok') {
                   8118:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8119:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8120:             }
                   8121:         }
                   8122:     }
                   8123:     if ($delcoowners) {
                   8124:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8125:         if ($delresult eq 'ok') {
                   8126:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8127:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8128:             }
                   8129:         }
                   8130:     }
                   8131:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8132:         my %crsinfo =
                   8133:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8134:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8135:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8136:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8137:         }
                   8138:     }
                   8139: }
                   8140: 
1.169     harris41 8141: # -------------------------------------------------- Modify user authentication
1.197     www      8142: # Overrides without validation
                   8143: 
1.169     harris41 8144: sub modifyuserauth {
                   8145:     my ($udom,$uname,$umode,$upass)=@_;
                   8146:     my $uhome=&homeserver($uname,$udom);
1.197     www      8147:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8148:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8149:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8150:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8151:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8152: 		     &escape($upass),$uhome);
1.620     albertel 8153:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8154:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8155:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8156:     &log($udom,,$uname,$uhome,
1.620     albertel 8157:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8158:                                      $env{'user.name'}.', '.$umode.
1.197     www      8159:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8160:     unless ($reply eq 'ok') {
1.197     www      8161:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8162: 	return 'error: '.$reply;
                   8163:     }   
1.170     harris41 8164:     return 'ok';
1.80      www      8165: }
                   8166: 
1.81      www      8167: # --------------------------------------------------------------- Modify a user
1.80      www      8168: 
1.81      www      8169: sub modifyuser {
1.206     matthew  8170:     my ($udom,    $uname, $uid,
                   8171:         $umode,   $upass, $first,
                   8172:         $middle,  $last,  $gene,
1.1058    raeburn  8173:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8174:     $udom= &LONCAPA::clean_domain($udom);
                   8175:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8176:     my $showcandelete = 'none';
                   8177:     if (ref($candelete) eq 'ARRAY') {
                   8178:         if (@{$candelete} > 0) {
                   8179:             $showcandelete = join(', ',@{$candelete});
                   8180:         }
                   8181:     }
1.81      www      8182:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8183:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8184: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8185:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8186:                                      ' desiredhome not specified'). 
1.620     albertel 8187:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8188:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8189:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8190:     my $newuser;
                   8191:     if ($uhome eq 'no_host') {
                   8192:         $newuser = 1;
                   8193:     }
1.80      www      8194: # ----------------------------------------------------------------- Create User
1.406     albertel 8195:     if (($uhome eq 'no_host') && 
                   8196: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8197:         my $unhome='';
1.844     albertel 8198:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8199:             $unhome = $desiredhome;
1.620     albertel 8200: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8201: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8202:         } else { # load balancing routine for determining $unhome
1.81      www      8203:             my $loadm=10000000;
1.841     albertel 8204: 	    my %servers = &get_servers($udom,'library');
                   8205: 	    foreach my $tryserver (keys(%servers)) {
                   8206: 		my $answer=reply('load',$tryserver);
                   8207: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8208: 		    $loadm=$answer;
                   8209: 		    $unhome=$tryserver;
                   8210: 		}
1.80      www      8211: 	    }
                   8212:         }
                   8213:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8214: 	    return 'error: unable to find a home server for '.$uname.
                   8215:                    ' in domain '.$udom;
1.80      www      8216:         }
                   8217:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8218:                          &escape($upass),$unhome);
                   8219: 	unless ($reply eq 'ok') {
                   8220:             return 'error: '.$reply;
                   8221:         }   
1.230     stredwic 8222:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8223:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8224: 	    return 'error: unable verify users home machine.';
1.80      www      8225:         }
1.209     matthew  8226:     }   # End of creation of new user
1.80      www      8227: # ---------------------------------------------------------------------- Add ID
                   8228:     if ($uid) {
                   8229:        $uid=~tr/A-Z/a-z/;
                   8230:        my %uidhash=&idrget($udom,$uname);
1.196     www      8231:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8232:          && (!$forceid)) {
1.80      www      8233: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8234: 	      return 'error: user id "'.$uid.'" does not match '.
                   8235:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8236:           }
                   8237:        } else {
                   8238: 	  &idput($udom,($uname => $uid));
                   8239:        }
                   8240:     }
                   8241: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8242:     my @tmp=&get('environment',
1.899     raeburn  8243: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8244:                     'permanentemail','inststatus'],
1.134     albertel 8245: 		   $udom,$uname);
1.1075    raeburn  8246:     my (%names,%oldnames);
1.313     matthew  8247:     if ($tmp[0] =~ m/^error:.*/) { 
                   8248:         %names=(); 
                   8249:     } else {
                   8250:         %names = @tmp;
1.1075    raeburn  8251:         %oldnames = %names;
1.313     matthew  8252:     }
1.388     www      8253: #
1.1058    raeburn  8254: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8255: # of users did not contain them), do not overwrite existing values
                   8256: # unless field is in $candelete array ref.  
                   8257: #
                   8258: 
                   8259:     my @fields = ('firstname','middlename','lastname','generation',
                   8260:                   'permanentemail','id');
                   8261:     my %newvalues;
                   8262:     if (ref($candelete) eq 'ARRAY') {
                   8263:         foreach my $field (@fields) {
                   8264:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8265:                 if ($field eq 'firstname') {
                   8266:                     $names{$field} = $first;
                   8267:                 } elsif ($field eq 'middlename') {
                   8268:                     $names{$field} = $middle;
                   8269:                 } elsif ($field eq 'lastname') {
                   8270:                     $names{$field} = $last;
                   8271:                 } elsif ($field eq 'generation') { 
                   8272:                     $names{$field} = $gene;
                   8273:                 } elsif ($field eq 'permanentemail') {
                   8274:                     $names{$field} = $email;
                   8275:                 } elsif ($field eq 'id') {
                   8276:                     $names{$field}  = $uid;
                   8277:                 }
                   8278:             }
                   8279:         }
                   8280:     }
1.388     www      8281:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8282:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8283:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8284:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8285:     if ($email) {
                   8286:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8287:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8288:     }
1.899     raeburn  8289:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8290:     if (defined($inststatus)) {
                   8291:         $names{'inststatus'} = '';
                   8292:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8293:         if (ref($usertypes) eq 'HASH') {
                   8294:             my @okstatuses; 
                   8295:             foreach my $item (split(/:/,$inststatus)) {
                   8296:                 if (defined($usertypes->{$item})) {
                   8297:                     push(@okstatuses,$item);  
                   8298:                 }
                   8299:             }
                   8300:             if (@okstatuses) {
                   8301:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8302:             }
                   8303:         }
                   8304:     }
1.1075    raeburn  8305:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8306:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8307:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8308:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8309:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8310:     } else {
                   8311:         $logmsg .= ' during self creation';
                   8312:     }
1.1075    raeburn  8313:     my $changed;
                   8314:     if ($newuser) {
                   8315:         $changed = 1;
                   8316:     } else {
                   8317:         foreach my $field (@fields) {
                   8318:             if ($names{$field} ne $oldnames{$field}) {
                   8319:                 $changed = 1;
                   8320:                 last;
                   8321:             }
                   8322:         }
                   8323:     }
                   8324:     unless ($changed) {
                   8325:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8326:         &logthis($logmsg);
                   8327:         return 'ok';
                   8328:     }
                   8329:     my $reply = &put('environment', \%names, $udom,$uname);
                   8330:     if ($reply ne 'ok') { 
                   8331:         return 'error: '.$reply;
                   8332:     }
1.1087    raeburn  8333:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8334:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8335:     }
1.1075    raeburn  8336:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8337:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8338:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8339:     &logthis($logmsg);
1.134     albertel 8340:     return 'ok';
1.80      www      8341: }
                   8342: 
1.81      www      8343: # -------------------------------------------------------------- Modify student
1.80      www      8344: 
1.81      www      8345: sub modifystudent {
                   8346:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8347:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8348:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8349:     if (!$cid) {
1.620     albertel 8350: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8351: 	    return 'not_in_class';
                   8352: 	}
1.80      www      8353:     }
                   8354: # --------------------------------------------------------------- Make the user
1.81      www      8355:     my $reply=&modifyuser
1.209     matthew  8356: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8357:          $desiredhome,$email,$inststatus);
1.80      www      8358:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8359:     # This will cause &modify_student_enrollment to get the uid from the
                   8360:     # students environment
                   8361:     $uid = undef if (!$forceid);
1.455     albertel 8362:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8363: 					$gene,$usec,$end,$start,$type,$locktype,
                   8364:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8365:     return $reply;
                   8366: }
                   8367: 
                   8368: sub modify_student_enrollment {
1.1172.2.19  raeburn  8369:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8370:     my ($cdom,$cnum,$chome);
                   8371:     if (!$cid) {
1.620     albertel 8372: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8373: 	    return 'not_in_class';
                   8374: 	}
1.620     albertel 8375: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8376: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8377:     } else {
                   8378: 	($cdom,$cnum)=split(/_/,$cid);
                   8379:     }
1.620     albertel 8380:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8381:     if (!$chome) {
1.457     raeburn  8382: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8383:     }
1.455     albertel 8384:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8385:     # Make sure the user exists
1.81      www      8386:     my $uhome=&homeserver($uname,$udom);
                   8387:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8388: 	return 'error: no such user';
                   8389:     }
1.297     matthew  8390:     # Get student data if we were not given enough information
                   8391:     if (!defined($first)  || $first  eq '' || 
                   8392:         !defined($last)   || $last   eq '' || 
                   8393:         !defined($uid)    || $uid    eq '' || 
                   8394:         !defined($middle) || $middle eq '' || 
                   8395:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8396:         # They did not supply us with enough data to enroll the student, so
                   8397:         # we need to pick up more information.
1.297     matthew  8398:         my %tmp = &get('environment',
1.294     matthew  8399:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8400:                        ,$udom,$uname);
                   8401: 
1.800     albertel 8402:         #foreach my $key (keys(%tmp)) {
                   8403:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8404:         #}
1.294     matthew  8405:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8406:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8407:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8408:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8409:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8410:     }
1.556     albertel 8411:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8412:     my $user = "$uname:$udom";
                   8413:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8414:     my $reply=cput('classlist',
1.1148    raeburn  8415: 		   {$user => 
1.1172.2.19  raeburn  8416: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8417: 		   $cdom,$cnum);
1.1148    raeburn  8418:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8419:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8420:     } else { 
1.81      www      8421: 	return 'error: '.$reply;
                   8422:     }
1.297     matthew  8423:     # Add student role to user
1.83      www      8424:     my $uurl='/'.$cid;
1.81      www      8425:     $uurl=~s/\_/\//g;
                   8426:     if ($usec) {
                   8427: 	$uurl.='/'.$usec;
                   8428:     }
1.1148    raeburn  8429:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8430:                              $selfenroll,$context);
                   8431:     if ($result ne 'ok') {
                   8432:         if ($old_entry{$user} ne '') {
                   8433:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8434:         } else {
                   8435:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8436:         }
                   8437:     }
                   8438:     return $result; 
1.21      www      8439: }
                   8440: 
1.556     albertel 8441: sub format_name {
                   8442:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8443:     my $name;
                   8444:     if ($first ne 'lastname') {
                   8445: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8446:     } else {
                   8447: 	if ($lastname=~/\S/) {
                   8448: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8449: 	    $name=~s/\s+,/,/;
                   8450: 	} else {
                   8451: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8452: 	}
                   8453:     }
                   8454:     $name=~s/^\s+//;
                   8455:     $name=~s/\s+$//;
                   8456:     $name=~s/\s+/ /g;
                   8457:     return $name;
                   8458: }
                   8459: 
1.84      www      8460: # ------------------------------------------------- Write to course preferences
                   8461: 
                   8462: sub writecoursepref {
                   8463:     my ($courseid,%prefs)=@_;
                   8464:     $courseid=~s/^\///;
                   8465:     $courseid=~s/\_/\//g;
                   8466:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8467:     my $chome=homeserver($cnum,$cdomain);
                   8468:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8469: 	return 'error: no such course';
                   8470:     }
                   8471:     my $cstring='';
1.800     albertel 8472:     foreach my $pref (keys(%prefs)) {
                   8473: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8474:     }
1.84      www      8475:     $cstring=~s/\&$//;
                   8476:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8477: }
                   8478: 
                   8479: # ---------------------------------------------------------- Make/modify course
                   8480: 
                   8481: sub createcourse {
1.741     raeburn  8482:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8483:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8484:     $url=&declutter($url);
                   8485:     my $cid='';
1.1028    raeburn  8486:     if ($context eq 'requestcourses') {
                   8487:         my $can_create = 0;
                   8488:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8489:         if ($udom eq $ownerdom) {
                   8490:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8491:                                   $context)) {
                   8492:                 $can_create = 1;
                   8493:             }
                   8494:         } else {
                   8495:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8496:                                            $category);
                   8497:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8498:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8499:                 if (@curr > 0) {
                   8500:                     my @options = qw(approval validate autolimit);
                   8501:                     my $optregex = join('|',@options);
                   8502:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8503:                         $can_create = 1;
                   8504:                     }
                   8505:                 }
                   8506:             }
                   8507:         }
                   8508:         if ($can_create) {
                   8509:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8510:                 unless (&allowed('ccc',$udom)) {
                   8511:                     return 'refused'; 
                   8512:                 }
1.1017    raeburn  8513:             }
                   8514:         } else {
                   8515:             return 'refused';
                   8516:         }
1.1028    raeburn  8517:     } elsif (!&allowed('ccc',$udom)) {
                   8518:         return 'refused';
1.84      www      8519:     }
1.1011    raeburn  8520: # --------------------------------------------------------------- Get Unique ID
                   8521:     my $uname;
                   8522:     if ($cnum =~ /^$match_courseid$/) {
                   8523:         my $chome=&homeserver($cnum,$udom,'true');
                   8524:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8525:             $uname = $cnum;
                   8526:         } else {
1.1038    raeburn  8527:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8528:         }
                   8529:     } else {
1.1038    raeburn  8530:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8531:     }
                   8532:     return $uname if ($uname =~ /^error/);
                   8533: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8534:     if (!defined($course_server)) {
                   8535:         if (defined(&domain($udom,'primary'))) {
                   8536:             $course_server = &domain($udom,'primary');
                   8537:         } else {
                   8538:             $course_server = $env{'user.home'}; 
                   8539:         }
                   8540:     }
                   8541:     my %host_servers =
                   8542:         &Apache::lonnet::get_servers($udom,'library');
                   8543:     unless ($host_servers{$course_server}) {
                   8544:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8545:     }
1.84      www      8546: # ------------------------------------------------------------- Make the course
                   8547:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8548:                       $course_server);
1.84      www      8549:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8550:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8551:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8552: 	return 'error: no such course';
                   8553:     }
1.271     www      8554: # ----------------------------------------------------------------- Course made
1.516     raeburn  8555: # log existence
1.1029    raeburn  8556:     my $now = time;
1.918     raeburn  8557:     my $newcourse = {
                   8558:                     $udom.'_'.$uname => {
1.921     raeburn  8559:                                      description => $description,
                   8560:                                      inst_code   => $inst_code,
                   8561:                                      owner       => $course_owner,
                   8562:                                      type        => $crstype,
1.1029    raeburn  8563:                                      creator     => $env{'user.name'}.':'.
                   8564:                                                     $env{'user.domain'},
                   8565:                                      created     => $now,
                   8566:                                      context     => $context,
1.918     raeburn  8567:                                                 },
                   8568:                     };
1.921     raeburn  8569:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8570: # set toplevel url
1.271     www      8571:     my $topurl=$url;
                   8572:     unless ($nonstandard) {
                   8573: # ------------------------------------------ For standard courses, make top url
                   8574:         my $mapurl=&clutter($url);
1.278     www      8575:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8576:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8577: <map>
                   8578: <resource id="1" type="start"></resource>
                   8579: <resource id="2" src="$mapurl"></resource>
                   8580: <resource id="3" type="finish"></resource>
                   8581: <link index="1" from="1" to="2"></link>
                   8582: <link index="2" from="2" to="3"></link>
                   8583: </map>
                   8584: ENDINITMAP
                   8585:         $topurl=&declutter(
1.638     albertel 8586:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8587:                           );
                   8588:     }
                   8589: # ----------------------------------------------------------- Write preferences
1.84      www      8590:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8591:                      ('description'              => $description,
                   8592:                       'url'                      => $topurl,
                   8593:                       'internal.creator'         => $env{'user.name'}.':'.
                   8594:                                                     $env{'user.domain'},
                   8595:                       'internal.created'         => $now,
                   8596:                       'internal.creationcontext' => $context)
                   8597:                     );
1.84      www      8598:     return '/'.$udom.'/'.$uname;
                   8599: }
                   8600: 
1.1011    raeburn  8601: # ------------------------------------------------------------------- Create ID
                   8602: sub generate_coursenum {
1.1038    raeburn  8603:     my ($udom,$crstype) = @_;
1.1011    raeburn  8604:     my $domdesc = &domain($udom);
                   8605:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8606:     my $first;
                   8607:     if ($crstype eq 'Community') {
                   8608:         $first = '0';
                   8609:     } else {
                   8610:         $first = int(1+rand(9)); 
                   8611:     } 
                   8612:     my $uname=$first.
1.1011    raeburn  8613:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8614:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8615:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8616: # ----------------------------------------------- Make sure that does not exist
                   8617:     my $uhome=&homeserver($uname,$udom,'true');
                   8618:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8619:         if ($crstype eq 'Community') {
                   8620:             $first = '0';
                   8621:         } else {
                   8622:             $first = int(1+rand(9));
                   8623:         }
                   8624:         $uname=$first.
1.1011    raeburn  8625:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8626:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8627:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8628:         $uhome=&homeserver($uname,$udom,'true');
                   8629:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8630:             return 'error: unable to generate unique course-ID';
                   8631:         }
                   8632:     }
                   8633:     return $uname;
                   8634: }
                   8635: 
1.813     albertel 8636: sub is_course {
1.1167    droeschl 8637:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8638:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8639: 
                   8640:     return unless $cdom and $cnum;
                   8641: 
                   8642:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8643:         '.');
                   8644: 
                   8645:     return unless exists($courses{$cdom.'_'.$cnum});
                   8646:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8647: }
                   8648: 
1.1015    raeburn  8649: sub store_userdata {
                   8650:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8651:     my $result;
1.1016    raeburn  8652:     if ($datakey ne '') {
1.1013    raeburn  8653:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8654:             if ($udom eq '' || $uname eq '') {
                   8655:                 $udom = $env{'user.domain'};
                   8656:                 $uname = $env{'user.name'};
                   8657:             }
                   8658:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8659:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8660:                 $result = 'error: no_host';
                   8661:             } else {
                   8662:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8663:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8664: 
                   8665:                 my $namevalue='';
                   8666:                 foreach my $key (keys(%{$storehash})) {
                   8667:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8668:                 }
                   8669:                 $namevalue=~s/\&$//;
1.1105    raeburn  8670:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8671:                                   $namevalue,$uhome);
1.1013    raeburn  8672:             }
                   8673:         } else {
                   8674:             $result = 'error: data to store was not a hash reference'; 
                   8675:         }
                   8676:     } else {
                   8677:         $result= 'error: invalid requestkey'; 
                   8678:     }
                   8679:     return $result;
                   8680: }
                   8681: 
1.21      www      8682: # ---------------------------------------------------------- Assign Custom Role
                   8683: 
                   8684: sub assigncustomrole {
1.957     raeburn  8685:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8686:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8687:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8688: }
                   8689: 
                   8690: # ----------------------------------------------------------------- Revoke Role
                   8691: 
                   8692: sub revokerole {
1.957     raeburn  8693:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8694:     my $now=time;
1.965     raeburn  8695:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8696: }
                   8697: 
                   8698: # ---------------------------------------------------------- Revoke Custom Role
                   8699: 
                   8700: sub revokecustomrole {
1.957     raeburn  8701:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8702:     my $now=time;
1.357     www      8703:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8704:            $deleteflag,$selfenroll,$context);
1.17      www      8705: }
                   8706: 
1.533     banghart 8707: # ------------------------------------------------------------ Disk usage
1.535     albertel 8708: sub diskusage {
1.955     raeburn  8709:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8710:     $directorypath =~ s/\/$//;
                   8711:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8712:                        .&escape($getpropath).':'.&escape($uname).':'
                   8713:                        .&escape($udom),homeserver($uname,$udom));
                   8714:     if ($listing eq 'unknown_cmd') {
                   8715:         if ($getpropath) {
                   8716:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8717:         }
                   8718:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8719:     }
1.514     albertel 8720:     return $listing;
1.512     banghart 8721: }
                   8722: 
1.566     banghart 8723: sub is_locked {
1.1096    raeburn  8724:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8725:     my @check;
                   8726:     my $is_locked;
1.1093    raeburn  8727:     push (@check,$file_name);
1.613     albertel 8728:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8729: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8730:     my ($tmp)=keys(%locked);
                   8731:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8732:     
1.566     banghart 8733:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8734:         $is_locked = 'false';
                   8735:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8736:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8737:                $is_locked = 'true';
1.1096    raeburn  8738:                if (ref($which) eq 'ARRAY') {
                   8739:                    push(@{$which},$entry);
                   8740:                } else {
                   8741:                    last;
                   8742:                }
1.745     raeburn  8743:            }
                   8744:        }
1.566     banghart 8745:     } else {
                   8746:         $is_locked = 'false';
                   8747:     }
1.1093    raeburn  8748:     return $is_locked;
1.566     banghart 8749: }
                   8750: 
1.759     albertel 8751: sub declutter_portfile {
                   8752:     my ($file) = @_;
1.833     albertel 8753:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8754:     return $file;
                   8755: }
                   8756: 
1.559     banghart 8757: # ------------------------------------------------------------- Mark as Read Only
                   8758: 
                   8759: sub mark_as_readonly {
                   8760:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8761:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8762:     my ($tmp)=keys(%current_permissions);
                   8763:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8764:     foreach my $file (@{$files}) {
1.759     albertel 8765: 	$file = &declutter_portfile($file);
1.561     banghart 8766:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8767:     }
1.613     albertel 8768:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8769:     return;
                   8770: }
                   8771: 
1.572     banghart 8772: # ------------------------------------------------------------Save Selected Files
                   8773: 
                   8774: sub save_selected_files {
                   8775:     my ($user, $path, @files) = @_;
                   8776:     my $filename = $user."savedfiles";
1.573     banghart 8777:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8778:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8779:     foreach my $file (@files) {
1.620     albertel 8780:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8781:     }
                   8782:     foreach my $file (@other_files) {
1.574     banghart 8783:         print (OUT $file."\n");
1.572     banghart 8784:     }
1.574     banghart 8785:     close (OUT);
1.572     banghart 8786:     return 'ok';
                   8787: }
                   8788: 
1.574     banghart 8789: sub clear_selected_files {
                   8790:     my ($user) = @_;
                   8791:     my $filename = $user."savedfiles";
1.1117    foxr     8792:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8793:     print (OUT undef);
                   8794:     close (OUT);
                   8795:     return ("ok");    
                   8796: }
                   8797: 
1.572     banghart 8798: sub files_in_path {
                   8799:     my ($user, $path) = @_;
                   8800:     my $filename = $user."savedfiles";
                   8801:     my %return_files;
1.1117    foxr     8802:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8803:     while (my $line_in = <IN>) {
1.574     banghart 8804:         chomp ($line_in);
                   8805:         my @paths_and_file = split (m!/!, $line_in);
                   8806:         my $file_part = pop (@paths_and_file);
                   8807:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8808:         $path_part.='/';
                   8809:         my $path_and_file = $path_part.$file_part;
                   8810:         if ($path_part eq $path) {
                   8811:             $return_files{$file_part}= 'selected';
                   8812:         }
                   8813:     }
1.574     banghart 8814:     close (IN);
                   8815:     return (\%return_files);
1.572     banghart 8816: }
                   8817: 
                   8818: # called in portfolio select mode, to show files selected NOT in current directory
                   8819: sub files_not_in_path {
                   8820:     my ($user, $path) = @_;
                   8821:     my $filename = $user."savedfiles";
                   8822:     my @return_files;
                   8823:     my $path_part;
1.1117    foxr     8824:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8825:     while (my $line = <IN>) {
1.572     banghart 8826:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8827:         my @paths_and_file = split(m|/|, $line);
                   8828:         my $file_part = pop(@paths_and_file);
                   8829:         chomp($file_part);
                   8830:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8831:         $path_part .= '/';
                   8832:         my $path_and_file = $path_part.$file_part;
                   8833:         if ($path_part ne $path) {
1.800     albertel 8834:             push(@return_files, ($path_and_file));
1.572     banghart 8835:         }
                   8836:     }
1.800     albertel 8837:     close(OUT);
1.574     banghart 8838:     return (@return_files);
1.572     banghart 8839: }
                   8840: 
1.745     raeburn  8841: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8842: 
1.745     raeburn  8843: sub get_portfile_permissions {
                   8844:     my ($domain,$user) = @_;
1.613     albertel 8845:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8846:     my ($tmp)=keys(%current_permissions);
                   8847:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8848:     return \%current_permissions;
                   8849: }
                   8850: 
                   8851: #---------------------------------------------Get portfolio file access controls
                   8852: 
1.749     raeburn  8853: sub get_access_controls {
1.745     raeburn  8854:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8855:     my %access;
                   8856:     my $real_file = $file;
                   8857:     $file =~ s/\.meta$//;
1.745     raeburn  8858:     if (defined($file)) {
1.749     raeburn  8859:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8860:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8861:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8862:             }
                   8863:         }
1.745     raeburn  8864:     } else {
1.749     raeburn  8865:         foreach my $key (keys(%{$current_permissions})) {
                   8866:             if ($key =~ /\0accesscontrol$/) {
                   8867:                 if (defined($group)) {
                   8868:                     if ($key !~ m-^\Q$group\E/-) {
                   8869:                         next;
                   8870:                     }
                   8871:                 }
                   8872:                 my ($fullpath) = split(/\0/,$key);
                   8873:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8874:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8875:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8876:                     }
                   8877:                 }
                   8878:             }
                   8879:         }
                   8880:     }
                   8881:     return %access;
                   8882: }
                   8883: 
                   8884: sub modify_access_controls {
                   8885:     my ($file_name,$changes,$domain,$user)=@_;
                   8886:     my ($outcome,$deloutcome);
                   8887:     my %store_permissions;
                   8888:     my %new_values;
                   8889:     my %new_control;
                   8890:     my %translation;
                   8891:     my @deletions = ();
                   8892:     my $now = time;
                   8893:     if (exists($$changes{'activate'})) {
                   8894:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8895:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8896:             my $numnew = scalar(@newitems);
                   8897:             for (my $i=0; $i<$numnew; $i++) {
                   8898:                 my $newkey = $newitems[$i];
                   8899:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8900:                 if ($newkey =~ /^\d+:/) { 
                   8901:                     $newkey =~ s/^(\d+)/$newid/;
                   8902:                     $translation{$1} = $newid;
                   8903:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8904:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8905:                     $translation{$1} = $newid;
                   8906:                 }
1.749     raeburn  8907:                 $new_values{$file_name."\0".$newkey} = 
                   8908:                                           $$changes{'activate'}{$newitems[$i]};
                   8909:                 $new_control{$newkey} = $now;
                   8910:             }
                   8911:         }
                   8912:     }
                   8913:     my %todelete;
                   8914:     my %changed_items;
                   8915:     foreach my $action ('delete','update') {
                   8916:         if (exists($$changes{$action})) {
                   8917:             if (ref($$changes{$action}) eq 'HASH') {
                   8918:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8919:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8920:                     if ($action eq 'delete') { 
                   8921:                         $todelete{$itemnum} = 1;
                   8922:                     } else {
                   8923:                         $changed_items{$itemnum} = $key;
                   8924:                     }
                   8925:                 }
1.745     raeburn  8926:             }
                   8927:         }
1.749     raeburn  8928:     }
                   8929:     # get lock on access controls for file.
                   8930:     my $lockhash = {
                   8931:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8932:                                                        ':'.$env{'user.domain'},
                   8933:                    }; 
                   8934:     my $tries = 0;
                   8935:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8936:    
                   8937:     while (($gotlock ne 'ok') && $tries <3) {
                   8938:         $tries ++;
                   8939:         sleep 1;
                   8940:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8941:     }
                   8942:     if ($gotlock eq 'ok') {
                   8943:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8944:         my ($tmp)=keys(%curr_permissions);
                   8945:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8946:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8947:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8948:             if (ref($curr_controls) eq 'HASH') {
                   8949:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8950:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8951:                     if (defined($todelete{$itemnum})) {
                   8952:                         push(@deletions,$file_name."\0".$control_item);
                   8953:                     } else {
                   8954:                         if (defined($changed_items{$itemnum})) {
                   8955:                             $new_control{$changed_items{$itemnum}} = $now;
                   8956:                             push(@deletions,$file_name."\0".$control_item);
                   8957:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8958:                         } else {
                   8959:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8960:                         }
                   8961:                     }
1.745     raeburn  8962:                 }
                   8963:             }
                   8964:         }
1.970     raeburn  8965:         my ($group);
                   8966:         if (&is_course($domain,$user)) {
                   8967:             ($group,my $file) = split(/\//,$file_name,2);
                   8968:         }
1.749     raeburn  8969:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8970:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8971:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8972:         #  remove lock
                   8973:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8974:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8975:         my $sqlresult =
1.970     raeburn  8976:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8977:                                     $group);
1.749     raeburn  8978:     } else {
                   8979:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8980:     }
1.749     raeburn  8981:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8982: }
                   8983: 
1.827     raeburn  8984: sub make_public_indefinitely {
                   8985:     my ($requrl) = @_;
                   8986:     my $now = time;
                   8987:     my $action = 'activate';
                   8988:     my $aclnum = 0;
                   8989:     if (&is_portfolio_url($requrl)) {
                   8990:         my (undef,$udom,$unum,$file_name,$group) =
                   8991:             &parse_portfolio_url($requrl);
                   8992:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8993:         my %access_controls = &get_access_controls($current_perms,
                   8994:                                                    $group,$file_name);
                   8995:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8996:             my ($num,$scope,$end,$start) = 
                   8997:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8998:             if ($scope eq 'public') {
                   8999:                 if ($start <= $now && $end == 0) {
                   9000:                     $action = 'none';
                   9001:                 } else {
                   9002:                     $action = 'update';
                   9003:                     $aclnum = $num;
                   9004:                 }
                   9005:                 last;
                   9006:             }
                   9007:         }
                   9008:         if ($action eq 'none') {
                   9009:              return 'ok';
                   9010:         } else {
                   9011:             my %changes;
                   9012:             my $newend = 0;
                   9013:             my $newstart = $now;
                   9014:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9015:             $changes{$action}{$newkey} = {
                   9016:                 type => 'public',
                   9017:                 time => {
                   9018:                     start => $newstart,
                   9019:                     end   => $newend,
                   9020:                 },
                   9021:             };
                   9022:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9023:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9024:             return $outcome;
                   9025:         }
                   9026:     } else {
                   9027:         return 'invalid';
                   9028:     }
                   9029: }
                   9030: 
1.745     raeburn  9031: #------------------------------------------------------Get Marked as Read Only
                   9032: 
                   9033: sub get_marked_as_readonly {
                   9034:     my ($domain,$user,$what,$group) = @_;
                   9035:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9036:     my @readonly_files;
1.629     banghart 9037:     my $cmp1=$what;
                   9038:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9039:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9040:         if (defined($group)) {
                   9041:             if ($file_name !~ m-^\Q$group\E/-) {
                   9042:                 next;
                   9043:             }
                   9044:         }
1.561     banghart 9045:         if (ref($value) eq "ARRAY"){
                   9046:             foreach my $stored_what (@{$value}) {
1.629     banghart 9047:                 my $cmp2=$stored_what;
1.759     albertel 9048:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9049:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9050:                 }
1.629     banghart 9051:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9052:                     push(@readonly_files, $file_name);
1.745     raeburn  9053:                     last;
1.563     banghart 9054:                 } elsif (!defined($what)) {
                   9055:                     push(@readonly_files, $file_name);
1.745     raeburn  9056:                     last;
1.561     banghart 9057:                 }
                   9058:             }
1.745     raeburn  9059:         }
1.561     banghart 9060:     }
                   9061:     return @readonly_files;
                   9062: }
1.577     banghart 9063: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9064: 
1.577     banghart 9065: sub get_marked_as_readonly_hash {
1.745     raeburn  9066:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9067:     my %readonly_files;
1.745     raeburn  9068:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9069:         if (defined($group)) {
                   9070:             if ($file_name !~ m-^\Q$group\E/-) {
                   9071:                 next;
                   9072:             }
                   9073:         }
1.577     banghart 9074:         if (ref($value) eq "ARRAY"){
                   9075:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9076:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9077:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9078:                         if ($lock_descriptor eq 'graded') {
                   9079:                             $readonly_files{$file_name} = 'graded';
                   9080:                         } elsif ($lock_descriptor eq 'handback') {
                   9081:                             $readonly_files{$file_name} = 'handback';
                   9082:                         } else {
                   9083:                             if (!exists($readonly_files{$file_name})) {
                   9084:                                 $readonly_files{$file_name} = 'locked';
                   9085:                             }
                   9086:                         }
1.745     raeburn  9087:                     }
1.750     banghart 9088:                 } 
1.577     banghart 9089:             }
                   9090:         } 
                   9091:     }
                   9092:     return %readonly_files;
                   9093: }
1.559     banghart 9094: # ------------------------------------------------------------ Unmark as Read Only
                   9095: 
                   9096: sub unmark_as_readonly {
1.629     banghart 9097:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9098:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9099:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9100:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9101:     my $symb_crs = $what;
                   9102:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9103:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9104:     my ($tmp)=keys(%current_permissions);
                   9105:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9106:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9107:     foreach my $file (@readonly_files) {
1.759     albertel 9108: 	my $clean_file = &declutter_portfile($file);
                   9109: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9110: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9111:         my @new_locks;
                   9112:         my @del_keys;
                   9113:         if (ref($current_locks) eq "ARRAY"){
                   9114:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9115:                 my $compare=$locker;
1.749     raeburn  9116:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9117:                     $compare=join('',@{$locker});
1.746     raeburn  9118:                     if ($compare ne $symb_crs) {
                   9119:                         push(@new_locks, $locker);
                   9120:                     }
1.563     banghart 9121:                 }
                   9122:             }
1.650     albertel 9123:             if (scalar(@new_locks) > 0) {
1.563     banghart 9124:                 $current_permissions{$file} = \@new_locks;
                   9125:             } else {
                   9126:                 push(@del_keys, $file);
1.613     albertel 9127:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9128:                 delete($current_permissions{$file});
1.563     banghart 9129:             }
                   9130:         }
1.561     banghart 9131:     }
1.613     albertel 9132:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9133:     return;
                   9134: }
1.512     banghart 9135: 
1.17      www      9136: # ------------------------------------------------------------ Directory lister
                   9137: 
                   9138: sub dirlist {
1.955     raeburn  9139:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9140:     $uri=~s/^\///;
                   9141:     $uri=~s/\/$//;
1.253     stredwic 9142:     my ($udom, $uname);
1.955     raeburn  9143:     if ($getuserdir) {
1.253     stredwic 9144:         $udom = $userdomain;
                   9145:         $uname = $username;
1.955     raeburn  9146:     } else {
                   9147:         (undef,$udom,$uname)=split(/\//,$uri);
                   9148:         if(defined($userdomain)) {
                   9149:             $udom = $userdomain;
                   9150:         }
                   9151:         if(defined($username)) {
                   9152:             $uname = $username;
                   9153:         }
1.253     stredwic 9154:     }
1.955     raeburn  9155:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9156: 
1.955     raeburn  9157:     $dirRoot = $perlvar{'lonDocRoot'};
                   9158:     if (defined($getpropath)) {
                   9159:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9160:         $dirRoot =~ s/\/$//;
1.955     raeburn  9161:     } elsif (defined($getuserdir)) {
                   9162:         my $subdir=$uname.'__';
                   9163:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9164:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9165:                    ."/$udom/$subdir/$uname";
                   9166:     } elsif (defined($alternateRoot)) {
                   9167:         $dirRoot = $alternateRoot;
1.751     banghart 9168:     }
1.253     stredwic 9169: 
                   9170:     if($udom) {
                   9171:         if($uname) {
1.1135    raeburn  9172:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9173:             if ($uhome eq 'no_host') {
                   9174:                 return ([],'no_host');
                   9175:             }
1.955     raeburn  9176:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9177:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9178:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9179:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9180:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9181:             } else {
                   9182:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9183:             }
1.605     matthew  9184:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9185:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9186:                 @listing_results = split(/:/,$listing);
                   9187:             } else {
                   9188:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9189:             }
1.1135    raeburn  9190:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9191:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9192:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9193:                 return ([],$listing);
                   9194:             } else {
                   9195:                 return (\@listing_results);
1.1135    raeburn  9196:             }
1.955     raeburn  9197:         } elsif(!$alternateRoot) {
1.1136    raeburn  9198:             my (%allusers,%listerror);
1.841     albertel 9199: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9200:  	    foreach my $tryserver (keys(%servers)) {
                   9201:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9202:                                   &escape($udom),$tryserver);
                   9203:                 if ($listing eq 'unknown_cmd') {
                   9204: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9205: 				      $udom, $tryserver);
                   9206:                 } else {
                   9207:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9208:                 }
1.841     albertel 9209: 		if ($listing eq 'unknown_cmd') {
                   9210: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9211: 				      $udom, $tryserver);
                   9212: 		    @listing_results = split(/:/,$listing);
                   9213: 		} else {
                   9214: 		    @listing_results =
                   9215: 			map { &unescape($_); } split(/:/,$listing);
                   9216: 		}
1.1136    raeburn  9217:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9218:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9219:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9220:                     $listerror{$tryserver} = $listing;
                   9221:                 } else {
1.841     albertel 9222: 		    foreach my $line (@listing_results) {
                   9223: 			my ($entry) = split(/&/,$line,2);
                   9224: 			$allusers{$entry} = 1;
                   9225: 		    }
                   9226: 		}
1.253     stredwic 9227:             }
1.1136    raeburn  9228:             my @alluserslist=();
1.800     albertel 9229:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9230:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9231:             }
1.1136    raeburn  9232:             return (\@alluserslist);
1.253     stredwic 9233:         } else {
1.1136    raeburn  9234:             return ([],'missing username');
1.253     stredwic 9235:         }
1.955     raeburn  9236:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9237:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9238:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9239:         return (\@all_domains);
1.955     raeburn  9240:     } else {
1.1136    raeburn  9241:         return ([],'missing domain');
1.275     stredwic 9242:     }
                   9243: }
                   9244: 
                   9245: # --------------------------------------------- GetFileTimestamp
                   9246: # This function utilizes dirlist and returns the date stamp for
                   9247: # when it was last modified.  It will also return an error of -1
                   9248: # if an error occurs
                   9249: 
                   9250: sub GetFileTimestamp {
1.955     raeburn  9251:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9252:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9253:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9254:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9255:                                     undef,$getuserdir);
                   9256:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9257:         return -1;
                   9258:     }
                   9259:     if (ref($fileref) eq 'ARRAY') {
                   9260:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9261:         # @stats contains first the filename, then the stat output
                   9262:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9263:     } else {
                   9264:         return -1;
1.253     stredwic 9265:     }
1.26      www      9266: }
                   9267: 
1.712     albertel 9268: sub stat_file {
                   9269:     my ($uri) = @_;
1.787     albertel 9270:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9271: 
1.955     raeburn  9272:     my ($udom,$uname,$file);
1.712     albertel 9273:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9274: 	($udom,$uname,$file) =
1.811     albertel 9275: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9276: 	$file = 'userfiles/'.$file;
                   9277:     }
                   9278:     if ($uri =~ m-^/res/-) {
                   9279: 	($udom,$uname) = 
1.807     albertel 9280: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9281: 	$file = $uri;
                   9282:     }
                   9283: 
                   9284:     if (!$udom || !$uname || !$file) {
                   9285: 	# unable to handle the uri
                   9286: 	return ();
                   9287:     }
1.956     raeburn  9288:     my $getpropath;
                   9289:     if ($file =~ /^userfiles\//) {
                   9290:         $getpropath = 1;
                   9291:     }
1.1136    raeburn  9292:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9293:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9294:         return ();
                   9295:     } else {
                   9296:         if (ref($listref) eq 'ARRAY') {
                   9297:             my @stats = split('&',$listref->[0]);
                   9298: 	    shift(@stats); #filename is first
                   9299: 	    return @stats;
                   9300:         }
1.712     albertel 9301:     }
                   9302:     return ();
                   9303: }
                   9304: 
1.26      www      9305: # -------------------------------------------------------- Value of a Condition
                   9306: 
1.713     albertel 9307: # gets the value of a specific preevaluated condition
                   9308: #    stored in the string  $env{user.state.<cid>}
                   9309: # or looks up a condition reference in the bighash and if if hasn't
                   9310: # already been evaluated recurses into docondval to get the value of
                   9311: # the condition, then memoizing it to 
                   9312: #   $env{user.state.<cid>.<condition>}
1.40      www      9313: sub directcondval {
                   9314:     my $number=shift;
1.620     albertel 9315:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9316: 	&Apache::lonuserstate::evalstate();
                   9317:     }
1.713     albertel 9318:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9319: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9320:     } elsif ($number =~ /^_/) {
                   9321: 	my $sub_condition;
                   9322: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9323: 		&GDBM_READER(),0640)) {
                   9324: 	    $sub_condition=$bighash{'conditions'.$number};
                   9325: 	    untie(%bighash);
                   9326: 	}
                   9327: 	my $value = &docondval($sub_condition);
1.949     raeburn  9328: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9329: 	return $value;
                   9330:     }
1.620     albertel 9331:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9332:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9333:     } else {
                   9334:        return 2;
                   9335:     }
                   9336: }
                   9337: 
1.713     albertel 9338: # get the collection of conditions for this resource
1.26      www      9339: sub condval {
                   9340:     my $condidx=shift;
1.54      www      9341:     my $allpathcond='';
1.713     albertel 9342:     foreach my $cond (split(/\|/,$condidx)) {
                   9343: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9344: 	    $allpathcond.=
                   9345: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9346: 	}
1.191     harris41 9347:     }
1.54      www      9348:     $allpathcond=~s/\|$//;
1.713     albertel 9349:     return &docondval($allpathcond);
                   9350: }
                   9351: 
                   9352: #evaluates an expression of conditions
                   9353: sub docondval {
                   9354:     my ($allpathcond) = @_;
                   9355:     my $result=0;
                   9356:     if ($env{'request.course.id'}
                   9357: 	&& defined($allpathcond)) {
                   9358: 	my $operand='|';
                   9359: 	my @stack;
                   9360: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9361: 	    if ($chunk eq '(') {
                   9362: 		push @stack,($operand,$result);
                   9363: 	    } elsif ($chunk eq ')') {
                   9364: 		my $before=pop @stack;
                   9365: 		if (pop @stack eq '&') {
                   9366: 		    $result=$result>$before?$before:$result;
                   9367: 		} else {
                   9368: 		    $result=$result>$before?$result:$before;
                   9369: 		}
                   9370: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9371: 		$operand=$chunk;
                   9372: 	    } else {
                   9373: 		my $new=directcondval($chunk);
                   9374: 		if ($operand eq '&') {
                   9375: 		    $result=$result>$new?$new:$result;
                   9376: 		} else {
                   9377: 		    $result=$result>$new?$result:$new;
                   9378: 		}
                   9379: 	    }
                   9380: 	}
1.26      www      9381:     }
                   9382:     return $result;
1.421     albertel 9383: }
                   9384: 
                   9385: # ---------------------------------------------------- Devalidate courseresdata
                   9386: 
                   9387: sub devalidatecourseresdata {
                   9388:     my ($coursenum,$coursedomain)=@_;
                   9389:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9390:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9391: }
                   9392: 
1.763     www      9393: 
1.200     www      9394: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9395: #
                   9396: #  Parameters:
                   9397: #      $coursenum    - Number of the course.
                   9398: #      $coursedomain - Domain at which the course was created.
                   9399: #  Returns:
                   9400: #     A hash of the course parameters along (I think) with timestamps
                   9401: #     and version info.
1.877     foxr     9402: 
1.624     albertel 9403: sub get_courseresdata {
                   9404:     my ($coursenum,$coursedomain)=@_;
1.200     www      9405:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9406:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9407:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9408:     my %dumpreply;
1.417     albertel 9409:     unless (defined($cached)) {
1.624     albertel 9410: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9411: 	$result=\%dumpreply;
1.251     albertel 9412: 	my ($tmp) = keys(%dumpreply);
                   9413: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9414: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9415: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9416: 	    return $tmp;
1.416     albertel 9417: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9418: 	    $result=undef;
1.599     albertel 9419: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9420: 	}
                   9421:     }
1.624     albertel 9422:     return $result;
                   9423: }
                   9424: 
1.633     albertel 9425: sub devalidateuserresdata {
                   9426:     my ($uname,$udom)=@_;
                   9427:     my $hashid="$udom:$uname";
                   9428:     &devalidate_cache_new('userres',$hashid);
                   9429: }
                   9430: 
1.624     albertel 9431: sub get_userresdata {
                   9432:     my ($uname,$udom)=@_;
                   9433:     #most student don\'t have any data set, check if there is some data
                   9434:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9435: 
                   9436:     my $hashid="$udom:$uname";
                   9437:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9438:     if (!defined($cached)) {
                   9439: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9440: 	$result=\%resourcedata;
                   9441: 	&do_cache_new('userres',$hashid,$result,600);
                   9442:     }
                   9443:     my ($tmp)=keys(%$result);
                   9444:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9445: 	return $result;
                   9446:     }
                   9447:     #error 2 occurs when the .db doesn't exist
                   9448:     if ($tmp!~/error: 2 /) {
1.672     albertel 9449: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9450: 		 " Trying to get resource data for ".
                   9451: 		 $uname." at ".$udom.": ".
                   9452: 		 $tmp."</font>");
                   9453:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9454: 	#&EXT_cache_set($udom,$uname);
                   9455: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9456: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9457:     }
                   9458:     return $tmp;
                   9459: }
1.879     foxr     9460: #----------------------------------------------- resdata - return resource data
                   9461: #  Purpose:
                   9462: #    Return resource data for either users or for a course.
                   9463: #  Parameters:
                   9464: #     $name      - Course/user name.
                   9465: #     $domain    - Name of the domain the user/course is registered on.
                   9466: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9467: #     @which     - Array of names of resources desired.
                   9468: #  Returns:
                   9469: #     The value of the first reasource in @which that is found in the
                   9470: #     resource hash.
                   9471: #  Exceptional Conditions:
                   9472: #     If the $type passed in is not valid (not the string 'course' or 
                   9473: #     'user', an undefined  reference is returned.
                   9474: #     If none of the resources are found, an undef is returned
1.624     albertel 9475: sub resdata {
                   9476:     my ($name,$domain,$type,@which)=@_;
                   9477:     my $result;
                   9478:     if ($type eq 'course') {
                   9479: 	$result=&get_courseresdata($name,$domain);
                   9480:     } elsif ($type eq 'user') {
                   9481: 	$result=&get_userresdata($name,$domain);
                   9482:     }
                   9483:     if (!ref($result)) { return $result; }    
1.251     albertel 9484:     foreach my $item (@which) {
1.927     albertel 9485: 	if (defined($result->{$item->[0]})) {
                   9486: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9487: 	}
1.250     albertel 9488:     }
1.291     albertel 9489:     return undef;
1.200     www      9490: }
                   9491: 
1.379     matthew  9492: #
                   9493: # EXT resource caching routines
                   9494: #
                   9495: 
                   9496: sub clear_EXT_cache_status {
1.383     albertel 9497:     &delenv('cache.EXT.');
1.379     matthew  9498: }
                   9499: 
                   9500: sub EXT_cache_status {
                   9501:     my ($target_domain,$target_user) = @_;
1.383     albertel 9502:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9503:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9504:         # We know already the user has no data
                   9505:         return 1;
                   9506:     } else {
                   9507:         return 0;
                   9508:     }
                   9509: }
                   9510: 
                   9511: sub EXT_cache_set {
                   9512:     my ($target_domain,$target_user) = @_;
1.383     albertel 9513:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9514:     #&appenv({$cachename => time});
1.379     matthew  9515: }
                   9516: 
1.28      www      9517: # --------------------------------------------------------- Value of a Variable
1.58      www      9518: sub EXT {
1.715     albertel 9519: 
1.395     albertel 9520:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9521:     unless ($varname) { return ''; }
1.218     albertel 9522:     #get real user name/domain, courseid and symb
                   9523:     my $courseid;
1.359     albertel 9524:     my $publicuser;
1.427     www      9525:     if ($symbparm) {
                   9526: 	$symbparm=&get_symb_from_alias($symbparm);
                   9527:     }
1.218     albertel 9528:     if (!($uname && $udom)) {
1.790     albertel 9529:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9530:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9531:     } else {
1.620     albertel 9532: 	$courseid=$env{'request.course.id'};
1.218     albertel 9533:     }
1.48      www      9534:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9535:     my $rest;
1.320     albertel 9536:     if (defined($therest[0])) {
1.48      www      9537:        $rest=join('.',@therest);
                   9538:     } else {
                   9539:        $rest='';
                   9540:     }
1.320     albertel 9541: 
1.57      www      9542:     my $qualifierrest=$qualifier;
                   9543:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9544:     my $spacequalifierrest=$space;
                   9545:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9546:     if ($realm eq 'user') {
1.48      www      9547: # --------------------------------------------------------------- user.resource
                   9548: 	if ($space eq 'resource') {
1.651     albertel 9549: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9550: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9551: 		 &&
1.744     albertel 9552: 		 ($symbparm eq &symbread()) ) {	
                   9553: 		# if we are in the middle of processing the resource the
                   9554: 		# get the value we are planning on committing
                   9555:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9556:                     return $Apache::lonhomework::results{$qualifierrest};
                   9557:                 } else {
                   9558:                     return $Apache::lonhomework::history{$qualifierrest};
                   9559:                 }
1.335     albertel 9560: 	    } else {
1.359     albertel 9561: 		my %restored;
1.620     albertel 9562: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9563: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9564: 		} else {
                   9565: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9566: 		}
1.335     albertel 9567: 		return $restored{$qualifierrest};
                   9568: 	    }
1.48      www      9569: # ----------------------------------------------------------------- user.access
                   9570:         } elsif ($space eq 'access') {
1.218     albertel 9571: 	    # FIXME - not supporting calls for a specific user
1.48      www      9572:             return &allowed($qualifier,$rest);
                   9573: # ------------------------------------------ user.preferences, user.environment
                   9574:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9575: 	    if (($uname eq $env{'user.name'}) &&
                   9576: 		($udom eq $env{'user.domain'})) {
                   9577: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9578: 	    } else {
1.359     albertel 9579: 		my %returnhash;
                   9580: 		if (!$publicuser) {
                   9581: 		    %returnhash=&userenvironment($udom,$uname,
                   9582: 						 $qualifierrest);
                   9583: 		}
1.218     albertel 9584: 		return $returnhash{$qualifierrest};
                   9585: 	    }
1.48      www      9586: # ----------------------------------------------------------------- user.course
                   9587:         } elsif ($space eq 'course') {
1.218     albertel 9588: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9589:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9590: # ------------------------------------------------------------------- user.role
                   9591:         } elsif ($space eq 'role') {
1.218     albertel 9592: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9593:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9594:             if ($qualifier eq 'value') {
                   9595: 		return $role;
                   9596:             } elsif ($qualifier eq 'extent') {
                   9597:                 return $where;
                   9598:             }
                   9599: # ----------------------------------------------------------------- user.domain
                   9600:         } elsif ($space eq 'domain') {
1.218     albertel 9601:             return $udom;
1.48      www      9602: # ------------------------------------------------------------------- user.name
                   9603:         } elsif ($space eq 'name') {
1.218     albertel 9604:             return $uname;
1.48      www      9605: # ---------------------------------------------------- Any other user namespace
1.29      www      9606:         } else {
1.359     albertel 9607: 	    my %reply;
                   9608: 	    if (!$publicuser) {
                   9609: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9610: 	    }
                   9611: 	    return $reply{$qualifierrest};
1.48      www      9612:         }
1.236     www      9613:     } elsif ($realm eq 'query') {
                   9614: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9615:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9616: 						[$spacequalifierrest]);
1.620     albertel 9617: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9618:    } elsif ($realm eq 'request') {
1.48      www      9619: # ------------------------------------------------------------- request.browser
                   9620:         if ($space eq 'browser') {
1.1145    bisitz   9621:             return $env{'browser.'.$qualifier};
1.57      www      9622: # ------------------------------------------------------------ request.filename
                   9623:         } else {
1.620     albertel 9624:             return $env{'request.'.$spacequalifierrest};
1.29      www      9625:         }
1.28      www      9626:     } elsif ($realm eq 'course') {
1.48      www      9627: # ---------------------------------------------------------- course.description
1.620     albertel 9628:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9629:     } elsif ($realm eq 'resource') {
1.165     www      9630: 
1.620     albertel 9631: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9632: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9633: 	}
1.693     albertel 9634: 
                   9635: 	if ($space eq 'title') {
                   9636: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9637: 	    return &gettitle($symbparm);
                   9638: 	}
                   9639: 	
                   9640: 	if ($space eq 'map') {
                   9641: 	    my ($map) = &decode_symb($symbparm);
                   9642: 	    return &symbread($map);
                   9643: 	}
1.905     albertel 9644: 	if ($space eq 'filename') {
                   9645: 	    if ($symbparm) {
                   9646: 		return &clutter((&decode_symb($symbparm))[2]);
                   9647: 	    }
                   9648: 	    return &hreflocation('',$env{'request.filename'});
                   9649: 	}
1.693     albertel 9650: 
                   9651: 	my ($section, $group, @groups);
1.593     albertel 9652: 	my ($courselevelm,$courselevel);
1.539     albertel 9653: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9654: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9655: 
1.218     albertel 9656: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9657: 
1.60      www      9658: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9659: 	    my $symbp=$symbparm;
1.735     albertel 9660: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9661: 
                   9662: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9663: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9664: 
1.620     albertel 9665: 	    if (($env{'user.name'} eq $uname) &&
                   9666: 		($env{'user.domain'} eq $udom)) {
                   9667: 		$section=$env{'request.course.sec'};
1.733     raeburn  9668:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9669:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9670: 	    } else {
1.539     albertel 9671: 		if (! defined($usection)) {
1.551     albertel 9672: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9673: 		} else {
                   9674: 		    $section = $usection;
                   9675: 		}
1.733     raeburn  9676:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9677: 	    }
                   9678: 
                   9679: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9680: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9681: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9682: 
1.593     albertel 9683: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9684: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9685: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9686: 
1.60      www      9687: # ----------------------------------------------------------- first, check user
1.624     albertel 9688: 
                   9689: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9690: 				       ([$courselevelr,'resource'],
                   9691: 					[$courselevelm,'map'     ],
                   9692: 					[$courselevel, 'course'  ]));
1.931     albertel 9693: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9694: 
1.594     albertel 9695: # ------------------------------------------------ second, check some of course
1.684     raeburn  9696:             my $coursereply;
1.691     raeburn  9697:             if (@groups > 0) {
                   9698:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9699:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9700:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9701:             }
1.96      www      9702: 
1.684     raeburn  9703: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9704: 				  $env{'course.'.$courseid.'.domain'},
                   9705: 				  'course',
                   9706: 				  ([$seclevelr,   'resource'],
                   9707: 				   [$seclevelm,   'map'     ],
                   9708: 				   [$seclevel,    'course'  ],
                   9709: 				   [$courselevelr,'resource']));
                   9710: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9711: 
1.60      www      9712: # ------------------------------------------------------ third, check map parms
1.218     albertel 9713: 	    my %parmhash=();
                   9714: 	    my $thisparm='';
                   9715: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9716: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9717: 		    &GDBM_READER(),0640)) {
1.218     albertel 9718: 		$thisparm=$parmhash{$symbparm};
                   9719: 		untie(%parmhash);
                   9720: 	    }
1.927     albertel 9721: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9722: 	}
1.594     albertel 9723: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9724: 
1.218     albertel 9725: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9726: 	my $filename;
                   9727: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9728: 	if ($symbparm) {
1.409     www      9729: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9730: 	} else {
1.620     albertel 9731: 	    $filename=$env{'request.filename'};
1.282     albertel 9732: 	}
                   9733: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9734: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9735: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9736: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9737: 
1.927     albertel 9738: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9739: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9740: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9741: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9742: 				     $env{'course.'.$courseid.'.domain'},
                   9743: 				     'course',
1.927     albertel 9744: 				     ([$courselevelm,'map'   ],
                   9745: 				      [$courselevel, 'course']));
                   9746: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9747: 	}
1.145     www      9748: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9749: 	unless ($space eq '0') {
1.336     albertel 9750: 	    my @parts=split(/_/,$space);
                   9751: 	    my $id=pop(@parts);
                   9752: 	    my $part=join('_',@parts);
                   9753: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9754: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9755: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9756: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9757: 	}
1.395     albertel 9758: 	if ($recurse) { return undef; }
                   9759: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9760: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9761: # ---------------------------------------------------- Any other user namespace
                   9762:     } elsif ($realm eq 'environment') {
                   9763: # ----------------------------------------------------------------- environment
1.620     albertel 9764: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9765: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9766: 	} else {
1.770     albertel 9767: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9768: 		return '';
                   9769: 	    }
1.219     albertel 9770: 	    my %returnhash=&userenvironment($udom,$uname,
                   9771: 					    $spacequalifierrest);
                   9772: 	    return $returnhash{$spacequalifierrest};
                   9773: 	}
1.28      www      9774:     } elsif ($realm eq 'system') {
1.48      www      9775: # ----------------------------------------------------------------- system.time
                   9776: 	if ($space eq 'time') {
                   9777: 	    return time;
                   9778:         }
1.696     albertel 9779:     } elsif ($realm eq 'server') {
                   9780: # ----------------------------------------------------------------- system.time
                   9781: 	if ($space eq 'name') {
                   9782: 	    return $ENV{'SERVER_NAME'};
                   9783:         }
1.28      www      9784:     }
1.48      www      9785:     return '';
1.61      www      9786: }
                   9787: 
1.927     albertel 9788: sub get_reply {
                   9789:     my ($reply_value) = @_;
1.940     raeburn  9790:     if (ref($reply_value) eq 'ARRAY') {
                   9791:         if (wantarray) {
                   9792: 	    return @$reply_value;
                   9793:         }
                   9794:         return $reply_value->[0];
                   9795:     } else {
                   9796:         return $reply_value;
1.927     albertel 9797:     }
                   9798: }
                   9799: 
1.691     raeburn  9800: sub check_group_parms {
                   9801:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9802:     my @groupitems = ();
                   9803:     my $resultitem;
1.927     albertel 9804:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9805:     foreach my $group (@{$groups}) {
                   9806:         foreach my $level (@levels) {
1.927     albertel 9807:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9808:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9809:         }
                   9810:     }
                   9811:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9812:                             $env{'course.'.$courseid.'.domain'},
                   9813:                                      'course',@groupitems);
                   9814:     return $coursereply;
                   9815: }
                   9816: 
                   9817: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9818:     my ($courseid,@groups) = @_;
                   9819:     @groups = sort(@groups);
1.691     raeburn  9820:     return @groups;
                   9821: }
                   9822: 
1.395     albertel 9823: sub packages_tab_default {
                   9824:     my ($uri,$varname)=@_;
                   9825:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9826: 
                   9827:     my (@extension,@specifics,$do_default);
                   9828:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9829: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9830: 	if ($pack_type eq 'default') {
                   9831: 	    $do_default=1;
                   9832: 	} elsif ($pack_type eq 'extension') {
                   9833: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9834: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9835: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9836: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9837: 	}
                   9838:     }
                   9839:     # first look for a package that matches the requested part id
                   9840:     foreach my $package (@specifics) {
                   9841: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9842: 	next if ($pack_part ne $part);
                   9843: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9844: 	    return $packagetab{"$pack_type&$name&default"};
                   9845: 	}
                   9846:     }
                   9847:     # look for any possible matching non extension_ package
                   9848:     foreach my $package (@specifics) {
                   9849: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9850: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9851: 	    return $packagetab{"$pack_type&$name&default"};
                   9852: 	}
1.585     albertel 9853: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9854: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9855: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9856: 	}
                   9857:     }
1.738     albertel 9858:     # look for any posible extension_ match
                   9859:     foreach my $package (@extension) {
                   9860: 	my ($package,$pack_type)=@{$package};
                   9861: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9862: 	    return $packagetab{"$pack_type&$name&default"};
                   9863: 	}
                   9864: 	if (defined($packagetab{$package."&$name&default"})) {
                   9865: 	    return $packagetab{$package."&$name&default"};
                   9866: 	}
                   9867:     }
                   9868:     # look for a global default setting
                   9869:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9870: 	return $packagetab{"default&$name&default"};
                   9871:     }
1.395     albertel 9872:     return undef;
                   9873: }
                   9874: 
1.334     albertel 9875: sub add_prefix_and_part {
                   9876:     my ($prefix,$part)=@_;
                   9877:     my $keyroot;
                   9878:     if (defined($prefix) && $prefix !~ /^__/) {
                   9879: 	# prefix that has a part already
                   9880: 	$keyroot=$prefix;
                   9881:     } elsif (defined($prefix)) {
                   9882: 	# prefix that is missing a part
                   9883: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9884:     } else {
                   9885: 	# no prefix at all
                   9886: 	if (defined($part)) { $keyroot='_'.$part; }
                   9887:     }
                   9888:     return $keyroot;
                   9889: }
                   9890: 
1.71      www      9891: # ---------------------------------------------------------------- Get metadata
                   9892: 
1.599     albertel 9893: my %metaentry;
1.1070    www      9894: my %importedpartids;
1.71      www      9895: sub metadata {
1.176     www      9896:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9897:     $uri=&declutter($uri);
1.288     albertel 9898:     # if it is a non metadata possible uri return quickly
1.529     albertel 9899:     if (($uri eq '') || 
                   9900: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  9901: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9902:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9903: 	return undef;
                   9904:     }
1.1140    www      9905:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9906: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9907: 	return undef;
1.288     albertel 9908:     }
1.73      www      9909:     my $filename=$uri;
                   9910:     $uri=~s/\.meta$//;
1.172     www      9911: #
                   9912: # Is the metadata already cached?
1.177     www      9913: # Look at timestamp of caching
1.172     www      9914: # Everything is cached by the main uri, libraries are never directly cached
                   9915: #
1.428     albertel 9916:     if (!defined($liburi)) {
1.599     albertel 9917: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9918: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9919:     }
                   9920:     {
1.1069    www      9921: # Imported parts would go here
1.1070    www      9922:         my %importedids=();
                   9923:         my @origfileimportpartids=();
1.1069    www      9924:         my $importedparts=0;
1.172     www      9925: #
                   9926: # Is this a recursive call for a library?
                   9927: #
1.599     albertel 9928: #	if (! exists($metacache{$uri})) {
                   9929: #	    $metacache{$uri}={};
                   9930: #	}
1.924     albertel 9931: 	my $cachetime = 60*60;
1.171     www      9932:         if ($liburi) {
                   9933: 	    $liburi=&declutter($liburi);
                   9934:             $filename=$liburi;
1.401     bowersj2 9935:         } else {
1.599     albertel 9936: 	    &devalidate_cache_new('meta',$uri);
                   9937: 	    undef(%metaentry);
1.401     bowersj2 9938: 	}
1.140     www      9939:         my %metathesekeys=();
1.73      www      9940:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9941: 	my $metastring;
1.1140    www      9942: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9943: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9944: 	    $metastring = 
1.929     albertel 9945: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9946: 					  ('grade_target' => 'meta'));
                   9947: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9948: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9949:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9950: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9951: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9952: 	    $metastring=&getfile($file);
1.489     albertel 9953: 	}
1.208     albertel 9954:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9955:         my $token;
1.140     www      9956:         undef %metathesekeys;
1.71      www      9957:         while ($token=$parser->get_token) {
1.339     albertel 9958: 	    if ($token->[0] eq 'S') {
                   9959: 		if (defined($token->[2]->{'package'})) {
1.172     www      9960: #
                   9961: # This is a package - get package info
                   9962: #
1.339     albertel 9963: 		    my $package=$token->[2]->{'package'};
                   9964: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9965: 		    if (defined($token->[2]->{'id'})) { 
                   9966: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9967: 		    }
1.599     albertel 9968: 		    if ($metaentry{':packages'}) {
                   9969: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9970: 		    } else {
1.599     albertel 9971: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9972: 		    }
1.736     albertel 9973: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9974: 			my $part=$keyroot;
                   9975: 			$part=~s/^\_//;
1.736     albertel 9976: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9977: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9978: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9979: 			    # ignore package.tab specified default values
                   9980:                             # here &package_tab_default() will fetch those
                   9981: 			    if ($subp eq 'default') { next; }
1.736     albertel 9982: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9983: 			    my $unikey;
                   9984: 			    if ($pack =~ /_0$/) {
                   9985: 				$unikey='parameter_0_'.$name;
                   9986: 				$part=0;
                   9987: 			    } else {
                   9988: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9989: 			    }
1.339     albertel 9990: 			    if ($subp eq 'display') {
                   9991: 				$value.=' [Part: '.$part.']';
                   9992: 			    }
1.599     albertel 9993: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9994: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9995: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9996: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9997: 			    }
1.599     albertel 9998: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9999: 				$metaentry{':'.$unikey}=
                   10000: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10001: 			    }
1.339     albertel 10002: 			}
                   10003: 		    }
                   10004: 		} else {
1.172     www      10005: #
                   10006: # This is not a package - some other kind of start tag
1.339     albertel 10007: #
                   10008: 		    my $entry=$token->[1];
1.1068    www      10009: 		    my $unikey='';
1.175     www      10010: 
1.339     albertel 10011: 		    if ($entry eq 'import') {
1.175     www      10012: #
                   10013: # Importing a library here
1.339     albertel 10014: #
1.1067    www      10015:                         my $location=$parser->get_text('/import');
                   10016:                         my $dir=$filename;
                   10017:                         $dir=~s|[^/]*$||;
                   10018:                         $location=&filelocation($dir,$location);
1.1069    www      10019:                        
1.1068    www      10020:                         my $importmode=$token->[2]->{'importmode'};
                   10021:                         if ($importmode eq 'problem') {
1.1069    www      10022: # Import as problem/response
1.1068    www      10023:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10024:                         } elsif ($importmode eq 'part') {
                   10025: # Import as part(s)
1.1069    www      10026:                            $importedparts=1;
                   10027: # We need to get the original file and the imported file to get the part order correct
                   10028: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10029: # Load and inspect original file
1.1070    www      10030:                            if ($#origfileimportpartids<0) {
                   10031:                               undef(%importedpartids);
                   10032:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10033:                               my $origfile=&getfile($origfilelocation);
                   10034:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10035:                            }
                   10036: 
1.1069    www      10037: # Load and inspect imported file
                   10038:                            my $impfile=&getfile($location);
                   10039:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10040:                            if ($#impfilepartids>=0) {
                   10041: # This problem had parts
1.1070    www      10042:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10043:                            } else {
                   10044: # Importing by turning a single problem into a problem part
                   10045: # It gets the import-tags ID as part-ID
                   10046:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10047:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10048:                            }
1.1068    www      10049:                         } else {
                   10050: # Normal import
                   10051:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10052:                            if (defined($token->[2]->{'id'})) {
                   10053:                               $unikey.='_'.$token->[2]->{'id'};
                   10054:                            }
1.1067    www      10055:                         }
                   10056: 
1.339     albertel 10057: 			if ($depthcount<20) {
1.736     albertel 10058: 			    my $metadata = 
                   10059: 				&metadata($uri,'keys', $location,$unikey,
                   10060: 					  $depthcount+1);
                   10061: 			    foreach my $meta (split(',',$metadata)) {
                   10062: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10063: 				$metathesekeys{$meta}=1;
1.339     albertel 10064: 			    }
1.1068    www      10065: 			
                   10066:                         }
1.1067    www      10067: 		    } else {
                   10068: #
                   10069: # Not importing, some other kind of non-package, non-library start tag
                   10070: # 
                   10071:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10072:                         if (defined($token->[2]->{'id'})) {
                   10073:                             $unikey.='_'.$token->[2]->{'id'};
                   10074:                         }
1.339     albertel 10075: 			if (defined($token->[2]->{'name'})) { 
                   10076: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10077: 			}
                   10078: 			$metathesekeys{$unikey}=1;
1.736     albertel 10079: 			foreach my $param (@{$token->[3]}) {
                   10080: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10081: 				$token->[2]->{$param};
1.339     albertel 10082: 			}
                   10083: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10084: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10085: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10086: 		 # only ws inside the tag, and not in default, so use default
                   10087: 		 # as value
1.599     albertel 10088: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10089: 			} elsif ( $internaltext =~ /\S/ ) {
                   10090: 		  # something interesting inside the tag
                   10091: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10092: 			} else {
1.908     albertel 10093: 		  # no interesting values, don't set a default
1.339     albertel 10094: 			}
1.172     www      10095: # end of not-a-package not-a-library import
1.339     albertel 10096: 		    }
1.172     www      10097: # end of not-a-package start tag
1.339     albertel 10098: 		}
1.172     www      10099: # the next is the end of "start tag"
1.339     albertel 10100: 	    }
                   10101: 	}
1.483     albertel 10102: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10103: 	$extension = lc($extension);
                   10104: 	if ($extension eq 'htm') { $extension='html'; }
                   10105: 
1.737     albertel 10106: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10107: 	    #no specific packages #how's our extension
                   10108: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10109: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10110: 					 \%metathesekeys);
                   10111: 	}
1.883     albertel 10112: 
                   10113: 	if (!exists($metaentry{':packages'})
                   10114: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10115: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10116: 		#no specific packages well let's get default then
                   10117: 		if ($key!~/^default&/) { next; }
1.488     albertel 10118: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10119: 					     \%metathesekeys);
                   10120: 	    }
                   10121: 	}
1.338     www      10122: # are there custom rights to evaluate
1.599     albertel 10123: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10124: 
1.338     www      10125:     #
                   10126:     # Importing a rights file here
1.339     albertel 10127:     #
                   10128: 	    unless ($depthcount) {
1.599     albertel 10129: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10130: 		my $dir=$filename;
                   10131: 		$dir=~s|[^/]*$||;
                   10132: 		$location=&filelocation($dir,$location);
1.736     albertel 10133: 		my $rights_metadata =
                   10134: 		    &metadata($uri,'keys',$location,'_rights',
                   10135: 			      $depthcount+1);
                   10136: 		foreach my $rights (split(',',$rights_metadata)) {
                   10137: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10138: 		    $metathesekeys{$rights}=1;
1.339     albertel 10139: 		}
                   10140: 	    }
                   10141: 	}
1.737     albertel 10142: 	# uniqifiy package listing
                   10143: 	my %seen;
                   10144: 	my @uniq_packages =
                   10145: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10146: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10147: 
1.1070    www      10148:         if ($importedparts) {
                   10149: # We had imported parts and need to rebuild partorder
                   10150:            $metaentry{':partorder'}='';
                   10151:            $metathesekeys{'partorder'}=1;
                   10152:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10153:                if ($origfileimportpartids[$index] eq 'part') {
                   10154: # original part, part of the problem
                   10155:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10156:                } else {
                   10157: # we have imported parts at this position
                   10158:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10159:                }
                   10160:            }
                   10161:            $metaentry{':partorder'}=~s/^\,//;
                   10162:         }
                   10163: 
1.737     albertel 10164: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10165: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10166: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10167: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10168: # this is the end of "was not already recently cached
1.71      www      10169:     }
1.599     albertel 10170:     return $metaentry{':'.$what};
1.261     albertel 10171: }
                   10172: 
1.488     albertel 10173: sub metadata_create_package_def {
1.483     albertel 10174:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10175:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10176:     if ($subp eq 'default') { next; }
                   10177:     
1.599     albertel 10178:     if (defined($metaentry{':packages'})) {
                   10179: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10180:     } else {
1.599     albertel 10181: 	$metaentry{':packages'}=$package;
1.483     albertel 10182:     }
                   10183:     my $value=$packagetab{$key};
                   10184:     my $unikey;
                   10185:     $unikey='parameter_0_'.$name;
1.599     albertel 10186:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10187:     $$metathesekeys{$unikey}=1;
1.599     albertel 10188:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10189: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10190:     }
1.599     albertel 10191:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10192: 	$metaentry{':'.$unikey}=
                   10193: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10194:     }
                   10195: }
                   10196: 
1.261     albertel 10197: sub metadata_generate_part0 {
                   10198:     my ($metadata,$metacache,$uri) = @_;
                   10199:     my %allnames;
1.737     albertel 10200:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10201: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10202: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10203: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10204: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10205: 	    $allnames{$name}=$part;
                   10206: 	  }
                   10207: 	}
                   10208:     }
                   10209:     foreach my $name (keys(%allnames)) {
                   10210:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10211:       my $key=":parameter_0_$name";
1.261     albertel 10212:       $$metacache{"$key.part"}='0';
                   10213:       $$metacache{"$key.name"}=$name;
1.428     albertel 10214:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10215: 					   $allnames{$name}.'_'.$name.
                   10216: 					   '.type'};
1.428     albertel 10217:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10218: 			     '.display'};
1.644     www      10219:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10220:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10221:       $$metacache{"$key.display"}=$olddis;
                   10222:     }
1.71      www      10223: }
                   10224: 
1.764     albertel 10225: # ------------------------------------------------------ Devalidate title cache
                   10226: 
                   10227: sub devalidate_title_cache {
                   10228:     my ($url)=@_;
                   10229:     if (!$env{'request.course.id'}) { return; }
                   10230:     my $symb=&symbread($url);
                   10231:     if (!$symb) { return; }
                   10232:     my $key=$env{'request.course.id'}."\0".$symb;
                   10233:     &devalidate_cache_new('title',$key);
                   10234: }
                   10235: 
1.1014    droeschl 10236: # ------------------------------------------------- Get the title of a course
                   10237: 
                   10238: sub current_course_title {
                   10239:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10240: }
1.301     www      10241: # ------------------------------------------------- Get the title of a resource
                   10242: 
                   10243: sub gettitle {
                   10244:     my $urlsymb=shift;
                   10245:     my $symb=&symbread($urlsymb);
1.534     albertel 10246:     if ($symb) {
1.620     albertel 10247: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10248: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10249: 	if (defined($cached)) { 
                   10250: 	    return $result;
                   10251: 	}
1.534     albertel 10252: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10253: 	my $title='';
1.907     albertel 10254: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10255: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10256: 	} else {
                   10257: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10258: 		    &GDBM_READER(),0640)) {
                   10259: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10260: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10261: 		untie(%bighash);
                   10262: 	    }
1.534     albertel 10263: 	}
                   10264: 	$title=~s/\&colon\;/\:/gs;
                   10265: 	if ($title) {
1.1159    www      10266: # Remember both $symb and $title for dynamic metadata
                   10267:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10268:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10269: # Cache this title and then return it
1.599     albertel 10270: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10271: 	}
                   10272: 	$urlsymb=$url;
                   10273:     }
                   10274:     my $title=&metadata($urlsymb,'title');
                   10275:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10276:     return $title;
1.301     www      10277: }
1.613     albertel 10278: 
1.1172.2.13  raeburn  10279: sub getdocspath {
                   10280:     my ($symb) = @_;
                   10281:     my $path;
                   10282:     if ($symb) {
                   10283:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10284:         if ($resurl=~/\.(sequence|page)$/) {
                   10285:             $mapurl=$resurl;
                   10286:         } elsif ($resurl eq 'adm/navmaps') {
                   10287:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10288:         }
                   10289:         my $mapresobj;
                   10290:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10291:         if (ref($navmap)) {
                   10292:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10293:         }
                   10294:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10295:         my $type=$2;
                   10296:         if (ref($mapresobj)) {
                   10297:             my $pcslist = $mapresobj->map_hierarchy();
                   10298:             if ($pcslist ne '') {
                   10299:                 foreach my $pc (split(/,/,$pcslist)) {
                   10300:                     next if ($pc <= 1);
                   10301:                     my $res = $navmap->getByMapPc($pc);
                   10302:                     if (ref($res)) {
                   10303:                         my $thisurl = $res->src();
                   10304:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10305:                         my $thistitle = $res->title();
                   10306:                         $path .= '&'.
                   10307:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10308:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10309:                                  ':'.$res->randompick().
                   10310:                                  ':'.$res->randomout().
                   10311:                                  ':'.$res->encrypted().
                   10312:                                  ':'.$res->randomorder().
                   10313:                                  ':'.$res->is_page();
                   10314:                     }
                   10315:                 }
                   10316:             }
                   10317:             $path =~ s/^\&//;
                   10318:             my $maptitle = $mapresobj->title();
                   10319:             if ($mapurl eq 'default') {
                   10320:                 $maptitle = 'Main Course Documents';
                   10321:             }
                   10322:             $path .= ($path ne '')? '&' : ''.
                   10323:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10324:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10325:                     ':'.$mapresobj->randompick().
                   10326:                     ':'.$mapresobj->randomout().
                   10327:                     ':'.$mapresobj->encrypted().
                   10328:                     ':'.$mapresobj->randomorder().
                   10329:                     ':'.$mapresobj->is_page();
                   10330:         } else {
                   10331:             my $maptitle = &gettitle($mapurl);
                   10332:             my $ispage;
                   10333:             if ($mapurl =~ /\.page$/) {
                   10334:                 $ispage = 1;
                   10335:             }
                   10336:             if ($mapurl eq 'default') {
                   10337:                 $maptitle = 'Main Course Documents';
                   10338:             }
                   10339:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10340:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10341:         }
                   10342:         unless ($mapurl eq 'default') {
                   10343:             $path = 'default&'.
                   10344:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10345:                     ':::::&'.$path;
                   10346:         }
                   10347:     }
                   10348:     return $path;
                   10349: }
                   10350: 
1.614     albertel 10351: sub get_slot {
                   10352:     my ($which,$cnum,$cdom)=@_;
                   10353:     if (!$cnum || !$cdom) {
1.790     albertel 10354: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10355: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10356: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10357:     }
1.703     albertel 10358:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10359:     my %slotinfo;
                   10360:     if (exists($remembered{$key})) {
                   10361: 	$slotinfo{$which} = $remembered{$key};
                   10362:     } else {
                   10363: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10364: 	&Apache::lonhomework::showhash(%slotinfo);
                   10365: 	my ($tmp)=keys(%slotinfo);
                   10366: 	if ($tmp=~/^error:/) { return (); }
                   10367: 	$remembered{$key} = $slotinfo{$which};
                   10368:     }
1.616     albertel 10369:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10370: 	return %{$slotinfo{$which}};
                   10371:     }
                   10372:     return $slotinfo{$which};
1.614     albertel 10373: }
1.1150    raeburn  10374: 
                   10375: sub get_reservable_slots {
                   10376:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10377:     my $now = time;
                   10378:     my $reservable_info;
                   10379:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10380:     if (exists($remembered{$key})) {
                   10381:         $reservable_info = $remembered{$key};
                   10382:     } else {
                   10383:         my %resv;
                   10384:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10385:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10386:         $reservable_info = \%resv;
                   10387:         $remembered{$key} = $reservable_info;
                   10388:     }
                   10389:     return $reservable_info;
                   10390: }
                   10391: 
                   10392: sub get_course_slots {
                   10393:     my ($cnum,$cdom) = @_;
                   10394:     my $hashid=$cnum.':'.$cdom;
                   10395:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10396:     if (defined($cached)) {
                   10397:         if (ref($result) eq 'HASH') {
                   10398:             return %{$result};
                   10399:         }
                   10400:     } else {
                   10401:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10402:         my ($tmp) = keys(%slots);
                   10403:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10404:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10405:             return %slots;
                   10406:         }
                   10407:     }
                   10408:     return;
                   10409: }
                   10410: 
                   10411: sub devalidate_slots_cache {
                   10412:     my ($cnum,$cdom)=@_;
                   10413:     my $hashid=$cnum.':'.$cdom;
                   10414:     &devalidate_cache_new('allslots',$hashid);
                   10415: }
                   10416: 
1.1172.2.8  raeburn  10417: sub get_coursechange {
                   10418:     my ($cdom,$cnum) = @_;
                   10419:     if ($cdom eq '' || $cnum eq '') {
                   10420:         return unless ($env{'request.course.id'});
                   10421:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10422:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10423:     }
                   10424:     my $hashid=$cdom.'_'.$cnum;
                   10425:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10426:     if ((defined($cached)) && ($change ne '')) {
                   10427:         return $change;
                   10428:     } else {
                   10429:         my %crshash;
                   10430:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10431:         if ($crshash{'internal.contentchange'} eq '') {
                   10432:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10433:             if ($change eq '') {
                   10434:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10435:                 $change = $crshash{'internal.created'};
                   10436:             }
                   10437:         } else {
                   10438:             $change = $crshash{'internal.contentchange'};
                   10439:         }
                   10440:         my $cachetime = 600;
                   10441:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10442:     }
                   10443:     return $change;
                   10444: }
                   10445: 
                   10446: sub devalidate_coursechange_cache {
                   10447:     my ($cnum,$cdom)=@_;
                   10448:     my $hashid=$cnum.':'.$cdom;
                   10449:     &devalidate_cache_new('crschange',$hashid);
                   10450: }
                   10451: 
1.31      www      10452: # ------------------------------------------------- Update symbolic store links
                   10453: 
                   10454: sub symblist {
                   10455:     my ($mapname,%newhash)=@_;
1.438     www      10456:     $mapname=&deversion(&declutter($mapname));
1.31      www      10457:     my %hash;
1.620     albertel 10458:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10459:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10460:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10461: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10462: 		next if ($url eq 'last_known'
                   10463: 			 && $env{'form.no_update_last_known'});
                   10464: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10465: 						    $newhash{$url}->[1],
                   10466: 						    $newhash{$url}->[0]);
1.191     harris41 10467:             }
1.31      www      10468:             if (untie(%hash)) {
                   10469: 		return 'ok';
                   10470:             }
                   10471:         }
                   10472:     }
                   10473:     return 'error';
1.212     www      10474: }
                   10475: 
                   10476: # --------------------------------------------------------------- Verify a symb
                   10477: 
                   10478: sub symbverify {
1.1172.2.11  raeburn  10479:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10480:     my $thisfn=$thisurl;
1.439     www      10481:     $thisfn=&declutter($thisfn);
1.215     www      10482: # direct jump to resource in page or to a sequence - will construct own symbs
                   10483:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10484: # check URL part
1.409     www      10485:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10486: 
1.431     www      10487:     unless ($url eq $thisfn) { return 0; }
1.213     www      10488: 
1.216     www      10489:     $symb=&symbclean($symb);
1.510     www      10490:     $thisurl=&deversion($thisurl);
1.439     www      10491:     $thisfn=&deversion($thisfn);
1.213     www      10492: 
                   10493:     my %bighash;
                   10494:     my $okay=0;
1.431     www      10495: 
1.620     albertel 10496:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10497:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10498:         my $noclutter;
1.1032    raeburn  10499:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10500:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10501:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10502:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10503:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10504:                 $noclutter = 1;
                   10505:             }
                   10506:         }
                   10507:         my $ids;
                   10508:         if ($noclutter) {
                   10509:             $ids=$bighash{'ids_'.$thisurl};
                   10510:         } else {
                   10511:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10512:         }
1.1102    raeburn  10513:         unless ($ids) {
1.1172.2.13  raeburn  10514:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10515:             $ids=$bighash{$idkey};
1.216     www      10516:         }
                   10517:         if ($ids) {
                   10518: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10519:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10520:                 $symb =~ s/\?.+$//;
                   10521:             }
1.800     albertel 10522: 	    foreach my $id (split(/\,/,$ids)) {
                   10523: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10524:                if (
                   10525:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10526:    eq $symb) {
1.1172.2.11  raeburn  10527:                    if (ref($encstate)) {
                   10528:                        $$encstate = $bighash{'encrypted_'.$id};
                   10529:                    }
1.1172.2.13  raeburn  10530:                    if (($env{'request.role.adv'}) ||
                   10531:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10532:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10533:                        $okay=1;
                   10534:                        last;
                   10535:                    }
                   10536:                }
                   10537:            }
1.216     www      10538:         }
1.213     www      10539: 	untie(%bighash);
                   10540:     }
                   10541:     return $okay;
1.31      www      10542: }
                   10543: 
1.210     www      10544: # --------------------------------------------------------------- Clean-up symb
                   10545: 
                   10546: sub symbclean {
                   10547:     my $symb=shift;
1.568     albertel 10548:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10549: # remove version from map
                   10550:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10551: 
1.210     www      10552: # remove version from URL
                   10553:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10554: 
1.507     www      10555: # remove wrapper
                   10556: 
1.510     www      10557:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10558:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10559:     return $symb;
1.409     www      10560: }
                   10561: 
                   10562: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10563: 
                   10564: sub encode_symb {
                   10565:     my ($map,$resid,$url)=@_;
                   10566:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10567: }
1.409     www      10568: 
                   10569: sub decode_symb {
1.568     albertel 10570:     my $symb=shift;
                   10571:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10572:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10573:     return (&fixversion($map),$resid,&fixversion($url));
                   10574: }
                   10575: 
                   10576: sub fixversion {
                   10577:     my $fn=shift;
1.609     banghart 10578:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10579:     my %bighash;
                   10580:     my $uri=&clutter($fn);
1.620     albertel 10581:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10582: # is this cached?
1.599     albertel 10583:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10584:     if (defined($cached)) { return $result; }
                   10585: # unfortunately not cached, or expired
1.620     albertel 10586:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10587: 	    &GDBM_READER(),0640)) {
                   10588:  	if ($bighash{'version_'.$uri}) {
                   10589:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10590:  	    unless (($version eq 'mostrecent') || 
                   10591: 		    ($version==&getversion($uri))) {
1.440     www      10592:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10593:  	    }
                   10594:  	}
                   10595:  	untie %bighash;
1.413     www      10596:     }
1.599     albertel 10597:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10598: }
                   10599: 
                   10600: sub deversion {
                   10601:     my $url=shift;
                   10602:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10603:     return $url;
1.210     www      10604: }
                   10605: 
1.31      www      10606: # ------------------------------------------------------ Return symb list entry
                   10607: 
                   10608: sub symbread {
1.249     www      10609:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10610:     my $cache_str;
                   10611:     if ($thisfn ne '') {
                   10612:         $cache_str='request.symbread.cached.'.$thisfn;
                   10613:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10614:             return $env{$cache_str};
                   10615:         }
1.1172.2.13  raeburn  10616:    } else {
1.242     www      10617: # no filename provided? try from environment
1.620     albertel 10618:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10619:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10620:         }
                   10621:         $thisfn=$env{'request.filename'};
1.44      www      10622:     }
1.569     albertel 10623:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10624: # is that filename actually a symb? Verify, clean, and return
                   10625:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10626: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10627: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10628: 	}
1.242     www      10629:     }
1.44      www      10630:     $thisfn=declutter($thisfn);
1.31      www      10631:     my %hash;
1.37      www      10632:     my %bighash;
                   10633:     my $syval='';
1.620     albertel 10634:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10635:         my $targetfn = $thisfn;
1.609     banghart 10636:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10637:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10638:         }
1.687     albertel 10639: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10640: 	    $targetfn=$1;
                   10641: 	}
1.620     albertel 10642:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10643:                       &GDBM_READER(),0640)) {
1.481     raeburn  10644: 	    $syval=$hash{$targetfn};
1.37      www      10645:             untie(%hash);
                   10646:         }
                   10647: # ---------------------------------------------------------- There was an entry
                   10648:         if ($syval) {
1.601     albertel 10649: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10650: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10651: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10652: 		    #return $env{$cache_str}='';
1.601     albertel 10653: 		#}    
                   10654: 		#$syval.=$1;
                   10655: 	    #}
1.37      www      10656:         } else {
                   10657: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10658:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10659:                             &GDBM_READER(),0640)) {
1.37      www      10660: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10661:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10662:               unless ($ids) { 
                   10663:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10664:               }
                   10665:               unless ($ids) {
                   10666: # alias?
                   10667: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10668:               }
1.37      www      10669:               if ($ids) {
                   10670: # ------------------------------------------------------------------- Has ID(s)
                   10671:                  my @possibilities=split(/\,/,$ids);
1.39      www      10672:                  if ($#possibilities==0) {
                   10673: # ----------------------------------------------- There is only one possibility
1.37      www      10674: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10675: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10676: 						    $resid,$thisfn);
1.249     www      10677:                  } elsif (!$donotrecurse) {
1.39      www      10678: # ------------------------------------------ There is more than one possibility
                   10679:                      my $realpossible=0;
1.800     albertel 10680:                      foreach my $id (@possibilities) {
                   10681: 			 my $file=$bighash{'src_'.$id};
1.39      www      10682:                          if (&allowed('bre',$file)) {
1.800     albertel 10683:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10684:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10685: 				$realpossible++;
1.626     albertel 10686:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10687: 						    $resid,$thisfn);
1.39      www      10688:                             }
                   10689: 			 }
1.191     harris41 10690:                      }
1.39      www      10691: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10692:                  } else {
                   10693:                      $syval='';
1.37      www      10694:                  }
                   10695: 	      }
                   10696:               untie(%bighash)
1.481     raeburn  10697:            }
1.31      www      10698:         }
1.62      www      10699:         if ($syval) {
1.620     albertel 10700: 	    return $env{$cache_str}=$syval;
1.62      www      10701:         }
1.31      www      10702:     }
1.949     raeburn  10703:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10704:     return $env{$cache_str}='';
1.31      www      10705: }
                   10706: 
                   10707: # ---------------------------------------------------------- Return random seed
                   10708: 
1.32      www      10709: sub numval {
                   10710:     my $txt=shift;
                   10711:     $txt=~tr/A-J/0-9/;
                   10712:     $txt=~tr/a-j/0-9/;
                   10713:     $txt=~tr/K-T/0-9/;
                   10714:     $txt=~tr/k-t/0-9/;
                   10715:     $txt=~tr/U-Z/0-5/;
                   10716:     $txt=~tr/u-z/0-5/;
                   10717:     $txt=~s/\D//g;
1.564     albertel 10718:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10719:     return int($txt);
1.368     albertel 10720: }
                   10721: 
1.484     albertel 10722: sub numval2 {
                   10723:     my $txt=shift;
                   10724:     $txt=~tr/A-J/0-9/;
                   10725:     $txt=~tr/a-j/0-9/;
                   10726:     $txt=~tr/K-T/0-9/;
                   10727:     $txt=~tr/k-t/0-9/;
                   10728:     $txt=~tr/U-Z/0-5/;
                   10729:     $txt=~tr/u-z/0-5/;
                   10730:     $txt=~s/\D//g;
                   10731:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10732:     my $total;
                   10733:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10734:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10735:     return int($total);
                   10736: }
                   10737: 
1.575     albertel 10738: sub numval3 {
                   10739:     use integer;
                   10740:     my $txt=shift;
                   10741:     $txt=~tr/A-J/0-9/;
                   10742:     $txt=~tr/a-j/0-9/;
                   10743:     $txt=~tr/K-T/0-9/;
                   10744:     $txt=~tr/k-t/0-9/;
                   10745:     $txt=~tr/U-Z/0-5/;
                   10746:     $txt=~tr/u-z/0-5/;
                   10747:     $txt=~s/\D//g;
                   10748:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10749:     my $total;
                   10750:     foreach my $val (@txts) { $total+=$val; }
                   10751:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10752:     return $total;
                   10753: }
                   10754: 
1.675     albertel 10755: sub digest {
                   10756:     my ($data)=@_;
                   10757:     my $digest=&Digest::MD5::md5($data);
                   10758:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10759:     my ($e,$f);
                   10760:     {
                   10761:         use integer;
                   10762:         $e=($a+$b);
                   10763:         $f=($c+$d);
                   10764:         if ($_64bit) {
                   10765:             $e=(($e<<32)>>32);
                   10766:             $f=(($f<<32)>>32);
                   10767:         }
                   10768:     }
                   10769:     if (wantarray) {
                   10770: 	return ($e,$f);
                   10771:     } else {
                   10772: 	my $g;
                   10773: 	{
                   10774: 	    use integer;
                   10775: 	    $g=($e+$f);
                   10776: 	    if ($_64bit) {
                   10777: 		$g=(($g<<32)>>32);
                   10778: 	    }
                   10779: 	}
                   10780: 	return $g;
                   10781:     }
                   10782: }
                   10783: 
1.368     albertel 10784: sub latest_rnd_algorithm_id {
1.675     albertel 10785:     return '64bit5';
1.366     albertel 10786: }
1.32      www      10787: 
1.503     albertel 10788: sub get_rand_alg {
                   10789:     my ($courseid)=@_;
1.790     albertel 10790:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10791:     if ($courseid) {
1.620     albertel 10792: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10793:     }
                   10794:     return &latest_rnd_algorithm_id();
                   10795: }
                   10796: 
1.562     albertel 10797: sub validCODE {
                   10798:     my ($CODE)=@_;
                   10799:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10800:     return 0;
                   10801: }
                   10802: 
1.491     albertel 10803: sub getCODE {
1.620     albertel 10804:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10805:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10806: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10807: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10808: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10809:     }
                   10810:     return undef;
                   10811: }
1.1133    foxr     10812: #
                   10813: #  Determines the random seed for a specific context:
                   10814: #
                   10815: # parameters:
                   10816: #   symb      - in course context the symb for the seed.
                   10817: #   course_id - The course id of the form domain_coursenum.
                   10818: #   domain    - Domain for the user.
                   10819: #   course    - Course for the user.
                   10820: #   cenv      - environment of the course.
                   10821: #
                   10822: # NOTE:
                   10823: #   All parameters are picked out of the environment if missing
                   10824: #   or not defined.
                   10825: #   If a symb cannot be determined the current time is used instead.
                   10826: #
                   10827: #  For a given well defined symb, courside, domain, username,
                   10828: #  and course environment, the seed is reproducible.
                   10829: #
1.31      www      10830: sub rndseed {
1.1133    foxr     10831:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10832:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10833:     if (!defined($symb)) {
1.366     albertel 10834: 	unless ($symb=$wsymb) { return time; }
                   10835:     }
1.1146    foxr     10836:     if (!defined $courseid) { 
                   10837: 	$courseid=$wcourseid; 
                   10838:     }
                   10839:     if (!defined $domain) { $domain=$wdomain; }
                   10840:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10841: 
                   10842:     my $which;
                   10843:     if (defined($cenv->{'rndseed'})) {
                   10844: 	$which = $cenv->{'rndseed'};
                   10845:     } else {
                   10846: 	$which =&get_rand_alg($courseid);
                   10847:     }
1.491     albertel 10848:     if (defined(&getCODE())) {
1.675     albertel 10849: 	if ($which eq '64bit5') {
                   10850: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10851: 	} elsif ($which eq '64bit4') {
1.575     albertel 10852: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10853: 	} else {
                   10854: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10855: 	}
1.675     albertel 10856:     } elsif ($which eq '64bit5') {
                   10857: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10858:     } elsif ($which eq '64bit4') {
                   10859: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10860:     } elsif ($which eq '64bit3') {
                   10861: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10862:     } elsif ($which eq '64bit2') {
                   10863: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10864:     } elsif ($which eq '64bit') {
                   10865: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10866:     }
                   10867:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10868: }
                   10869: 
                   10870: sub rndseed_32bit {
                   10871:     my ($symb,$courseid,$domain,$username)=@_;
                   10872:     {
                   10873: 	use integer;
                   10874: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10875: 	my $symbseed=numval($symb) << 22;
                   10876: 	my $namechck=unpack("%32C*",$username) << 17;
                   10877: 	my $nameseed=numval($username) << 12;
                   10878: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10879: 	my $courseseed=unpack("%32C*",$courseid);
                   10880: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10881: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10882: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10883: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10884: 	return $num;
                   10885:     }
                   10886: }
                   10887: 
                   10888: sub rndseed_64bit {
                   10889:     my ($symb,$courseid,$domain,$username)=@_;
                   10890:     {
                   10891: 	use integer;
                   10892: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10893: 	my $symbseed=numval($symb) << 10;
                   10894: 	my $namechck=unpack("%32S*",$username);
                   10895: 	
                   10896: 	my $nameseed=numval($username) << 21;
                   10897: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10898: 	my $courseseed=unpack("%32S*",$courseid);
                   10899: 	
                   10900: 	my $num1=$symbchck+$symbseed+$namechck;
                   10901: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10902: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10903: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10904: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10905: 	return "$num1,$num2";
1.155     albertel 10906:     }
1.366     albertel 10907: }
                   10908: 
1.443     albertel 10909: sub rndseed_64bit2 {
                   10910:     my ($symb,$courseid,$domain,$username)=@_;
                   10911:     {
                   10912: 	use integer;
                   10913: 	# strings need to be an even # of cahracters long, it it is odd the
                   10914:         # last characters gets thrown away
                   10915: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10916: 	my $symbseed=numval($symb) << 10;
                   10917: 	my $namechck=unpack("%32S*",$username.' ');
                   10918: 	
                   10919: 	my $nameseed=numval($username) << 21;
1.501     albertel 10920: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10921: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10922: 	
                   10923: 	my $num1=$symbchck+$symbseed+$namechck;
                   10924: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10925: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10926: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10927: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10928: 	return "$num1,$num2";
                   10929:     }
                   10930: }
                   10931: 
                   10932: sub rndseed_64bit3 {
                   10933:     my ($symb,$courseid,$domain,$username)=@_;
                   10934:     {
                   10935: 	use integer;
                   10936: 	# strings need to be an even # of cahracters long, it it is odd the
                   10937:         # last characters gets thrown away
                   10938: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10939: 	my $symbseed=numval2($symb) << 10;
                   10940: 	my $namechck=unpack("%32S*",$username.' ');
                   10941: 	
                   10942: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10943: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10944: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10945: 	
                   10946: 	my $num1=$symbchck+$symbseed+$namechck;
                   10947: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10948: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10949: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10950: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10951: 	
1.503     albertel 10952: 	return "$num1:$num2";
1.443     albertel 10953:     }
                   10954: }
                   10955: 
1.575     albertel 10956: sub rndseed_64bit4 {
                   10957:     my ($symb,$courseid,$domain,$username)=@_;
                   10958:     {
                   10959: 	use integer;
                   10960: 	# strings need to be an even # of cahracters long, it it is odd the
                   10961:         # last characters gets thrown away
                   10962: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10963: 	my $symbseed=numval3($symb) << 10;
                   10964: 	my $namechck=unpack("%32S*",$username.' ');
                   10965: 	
                   10966: 	my $nameseed=numval3($username) << 21;
                   10967: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10968: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10969: 	
                   10970: 	my $num1=$symbchck+$symbseed+$namechck;
                   10971: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10972: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10973: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10974: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10975: 	
1.575     albertel 10976: 	return "$num1:$num2";
                   10977:     }
                   10978: }
                   10979: 
1.675     albertel 10980: sub rndseed_64bit5 {
                   10981:     my ($symb,$courseid,$domain,$username)=@_;
                   10982:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10983:     return "$num1:$num2";
                   10984: }
                   10985: 
1.366     albertel 10986: sub rndseed_CODE_64bit {
                   10987:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10988:     {
1.366     albertel 10989: 	use integer;
1.443     albertel 10990: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10991: 	my $symbseed=numval2($symb);
1.491     albertel 10992: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10993: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10994: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10995: 	my $num1=$symbseed+$CODEchck;
                   10996: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10997: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10998: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10999: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11000: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11001: 	return "$num1:$num2";
1.366     albertel 11002:     }
                   11003: }
                   11004: 
1.575     albertel 11005: sub rndseed_CODE_64bit4 {
                   11006:     my ($symb,$courseid,$domain,$username)=@_;
                   11007:     {
                   11008: 	use integer;
                   11009: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11010: 	my $symbseed=numval3($symb);
                   11011: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11012: 	my $CODEseed=numval3(&getCODE());
                   11013: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11014: 	my $num1=$symbseed+$CODEchck;
                   11015: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11016: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11017: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11018: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11019: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11020: 	return "$num1:$num2";
                   11021:     }
                   11022: }
                   11023: 
1.675     albertel 11024: sub rndseed_CODE_64bit5 {
                   11025:     my ($symb,$courseid,$domain,$username)=@_;
                   11026:     my $code = &getCODE();
                   11027:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11028:     return "$num1:$num2";
                   11029: }
                   11030: 
1.366     albertel 11031: sub setup_random_from_rndseed {
                   11032:     my ($rndseed)=@_;
1.503     albertel 11033:     if ($rndseed =~/([,:])/) {
                   11034: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11035: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11036:     } else {
                   11037: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11038:     }
1.36      albertel 11039: }
                   11040: 
1.474     albertel 11041: sub latest_receipt_algorithm_id {
1.835     albertel 11042:     return 'receipt3';
1.474     albertel 11043: }
                   11044: 
1.480     www      11045: sub recunique {
                   11046:     my $fucourseid=shift;
                   11047:     my $unique;
1.835     albertel 11048:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11049: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11050: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11051:     } else {
                   11052: 	$unique=$perlvar{'lonReceipt'};
                   11053:     }
                   11054:     return unpack("%32C*",$unique);
                   11055: }
                   11056: 
                   11057: sub recprefix {
                   11058:     my $fucourseid=shift;
                   11059:     my $prefix;
1.835     albertel 11060:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11061: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11062: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11063:     } else {
                   11064: 	$prefix=$perlvar{'lonHostID'};
                   11065:     }
                   11066:     return unpack("%32C*",$prefix);
                   11067: }
                   11068: 
1.76      www      11069: sub ireceipt {
1.474     albertel 11070:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11071: 
                   11072:     my $return =&recprefix($fucourseid).'-';
                   11073: 
                   11074:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11075: 	$env{'request.state'} eq 'construct') {
                   11076: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11077: 	return $return;
                   11078:     }
                   11079: 
1.76      www      11080:     my $cuname=unpack("%32C*",$funame);
                   11081:     my $cudom=unpack("%32C*",$fudom);
                   11082:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11083:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11084:     my $cunique=&recunique($fucourseid);
1.474     albertel 11085:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11086:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11087: 
1.790     albertel 11088: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11089: 			       
                   11090: 	$return.= ($cunique%$cuname+
                   11091: 		   $cunique%$cudom+
                   11092: 		   $cusymb%$cuname+
                   11093: 		   $cusymb%$cudom+
                   11094: 		   $cucourseid%$cuname+
                   11095: 		   $cucourseid%$cudom+
                   11096: 		   $cpart%$cuname+
                   11097: 		   $cpart%$cudom);
                   11098:     } else {
                   11099: 	$return.= ($cunique%$cuname+
                   11100: 		   $cunique%$cudom+
                   11101: 		   $cusymb%$cuname+
                   11102: 		   $cusymb%$cudom+
                   11103: 		   $cucourseid%$cuname+
                   11104: 		   $cucourseid%$cudom);
                   11105:     }
                   11106:     return $return;
1.76      www      11107: }
                   11108: 
                   11109: sub receipt {
1.474     albertel 11110:     my ($part)=@_;
1.790     albertel 11111:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11112:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11113: }
1.260     ng       11114: 
1.790     albertel 11115: sub whichuser {
                   11116:     my ($passedsymb)=@_;
                   11117:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11118:     if (defined($env{'form.grade_symb'})) {
                   11119: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11120: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11121: 	if (!$allowed &&
                   11122: 	    exists($env{'request.course.sec'}) &&
                   11123: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11124: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11125: 			      '/'.$env{'request.course.sec'});
                   11126: 	}
                   11127: 	if ($allowed) {
                   11128: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11129: 	    $courseid=$tmp_courseid;
                   11130: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11131: 	    ($name)=&get_env_multiple('form.grade_username');
                   11132: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11133: 	}
                   11134:     }
                   11135:     if (!$passedsymb) {
                   11136: 	$symb=&symbread();
                   11137:     } else {
                   11138: 	$symb=$passedsymb;
                   11139:     }
                   11140:     $courseid=$env{'request.course.id'};
                   11141:     $domain=$env{'user.domain'};
                   11142:     $name=$env{'user.name'};
                   11143:     if ($name eq 'public' && $domain eq 'public') {
                   11144: 	if (!defined($env{'form.username'})) {
                   11145: 	    $env{'form.username'}.=time.rand(10000000);
                   11146: 	}
                   11147: 	$name.=$env{'form.username'};
                   11148:     }
                   11149:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11150: 
                   11151: }
                   11152: 
1.36      albertel 11153: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11154: # returns either the contents of the file or 
                   11155: # -1 if the file doesn't exist
1.481     raeburn  11156: #
                   11157: # if the target is a file that was uploaded via DOCS, 
                   11158: # a check will be made to see if a current copy exists on the local server,
                   11159: # if it does this will be served, otherwise a copy will be retrieved from
                   11160: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11161: # the local server.   
1.472     albertel 11162: 
1.36      albertel 11163: sub getfile {
1.538     albertel 11164:     my ($file) = @_;
1.609     banghart 11165:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11166:     &repcopy($file);
                   11167:     return &readfile($file);
                   11168: }
                   11169: 
                   11170: sub repcopy_userfile {
                   11171:     my ($file)=@_;
1.1142    raeburn  11172:     my $londocroot = $perlvar{'lonDocRoot'};
                   11173:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11174:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11175:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11176: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11177:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11178:     if (-e "$file") {
1.828     www      11179: # we already have a local copy, check it out
1.538     albertel 11180: 	my @fileinfo = stat($file);
1.828     www      11181: 	my $rtncode;
                   11182: 	my $info;
1.538     albertel 11183: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11184: 	if ($lwpresp ne 'ok') {
1.828     www      11185: # there is no such file anymore, even though we had a local copy
1.482     albertel 11186: 	    if ($rtncode eq '404') {
1.538     albertel 11187: 		unlink($file);
1.482     albertel 11188: 	    }
                   11189: 	    return -1;
                   11190: 	}
                   11191: 	if ($info < $fileinfo[9]) {
1.828     www      11192: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11193: 	    return 'ok';
1.828     www      11194: 	} else {
                   11195: # the file is outdated, get rid of it
                   11196: 	    unlink($file);
1.482     albertel 11197: 	}
1.828     www      11198:     }
                   11199: # one way or the other, at this point, we don't have the file
                   11200: # construct the correct path for the file
                   11201:     my @parts = ($cdom,$cnum); 
                   11202:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11203: 	push @parts, split(/\//,$1);
                   11204:     }
                   11205:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11206:     foreach my $part (@parts) {
                   11207: 	$path .= '/'.$part;
                   11208: 	if (!-e $path) {
                   11209: 	    mkdir($path,0770);
1.482     albertel 11210: 	}
                   11211:     }
1.828     www      11212: # now the path exists for sure
                   11213: # get a user agent
                   11214:     my $ua=new LWP::UserAgent;
                   11215:     my $transferfile=$file.'.in.transfer';
                   11216: # FIXME: this should flock
                   11217:     if (-e $transferfile) { return 'ok'; }
                   11218:     my $request;
                   11219:     $uri=~s/^\///;
1.980     raeburn  11220:     my $homeserver = &homeserver($cnum,$cdom);
                   11221:     my $protocol = $protocol{$homeserver};
                   11222:     $protocol = 'http' if ($protocol ne 'https');
                   11223:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11224:     my $response=$ua->request($request,$transferfile);
                   11225: # did it work?
                   11226:     if ($response->is_error()) {
                   11227: 	unlink($transferfile);
                   11228: 	&logthis("Userfile repcopy failed for $uri");
                   11229: 	return -1;
                   11230:     }
                   11231: # worked, rename the transfer file
                   11232:     rename($transferfile,$file);
1.607     raeburn  11233:     return 'ok';
1.481     raeburn  11234: }
                   11235: 
1.517     albertel 11236: sub tokenwrapper {
                   11237:     my $uri=shift;
1.980     raeburn  11238:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11239:     $uri=~s|^/||;
1.620     albertel 11240:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11241:     my $token=$1;
1.552     albertel 11242:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11243:     if ($udom && $uname && $file) {
                   11244: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11245:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11246:         my $homeserver = &homeserver($uname,$udom);
                   11247:         my $protocol = $protocol{$homeserver};
                   11248:         $protocol = 'http' if ($protocol ne 'https');
                   11249:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11250:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11251:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11252:     } else {
                   11253:         return '/adm/notfound.html';
                   11254:     }
                   11255: }
                   11256: 
1.828     www      11257: # call with reqtype HEAD: get last modification time
                   11258: # call with reqtype GET: get the file contents
                   11259: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11260: #
1.481     raeburn  11261: sub getuploaded {
                   11262:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11263:     $uri=~s/^\///;
1.980     raeburn  11264:     my $homeserver = &homeserver($cnum,$cdom);
                   11265:     my $protocol = $protocol{$homeserver};
                   11266:     $protocol = 'http' if ($protocol ne 'https');
                   11267:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11268:     my $ua=new LWP::UserAgent;
                   11269:     my $request=new HTTP::Request($reqtype,$uri);
                   11270:     my $response=$ua->request($request);
                   11271:     $$rtncode = $response->code;
1.482     albertel 11272:     if (! $response->is_success()) {
                   11273: 	return 'failed';
                   11274:     }      
                   11275:     if ($reqtype eq 'HEAD') {
1.486     www      11276: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11277:     } elsif ($reqtype eq 'GET') {
                   11278: 	$$info = $response->content;
1.472     albertel 11279:     }
1.482     albertel 11280:     return 'ok';
1.36      albertel 11281: }
                   11282: 
1.481     raeburn  11283: sub readfile {
                   11284:     my $file = shift;
                   11285:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11286:     my $fh;
                   11287:     open($fh,"<$file");
                   11288:     my $a='';
1.800     albertel 11289:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11290:     return $a;
                   11291: }
                   11292: 
1.36      albertel 11293: sub filelocation {
1.590     banghart 11294:     my ($dir,$file) = @_;
                   11295:     my $location;
                   11296:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11297: 
                   11298:     if ($file =~ m-^/adm/-) {
                   11299: 	$file=~s-^/adm/wrapper/-/-;
                   11300: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11301:     }
1.882     albertel 11302: 
1.1139    www      11303:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11304:         $location = $file;
1.609     banghart 11305:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11306:         my ($udom,$uname,$filename)=
1.811     albertel 11307:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11308:         my $home=&homeserver($uname,$udom);
                   11309:         my $is_me=0;
                   11310:         my @ids=&current_machine_ids();
                   11311:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11312:         if ($is_me) {
1.1117    foxr     11313:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11314:         } else {
                   11315:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11316:   	      $udom.'/'.$uname.'/'.$filename;
                   11317:         }
1.882     albertel 11318:     } elsif ($file =~ m-^/adm/-) {
                   11319: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11320:     } else {
                   11321:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11322:         $file=~s:^/(res|priv)/:/:;
                   11323:         my $space=$1;
1.590     banghart 11324:         if ( !( $file =~ m:^/:) ) {
                   11325:             $location = $dir. '/'.$file;
                   11326:         } else {
1.1142    raeburn  11327:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11328:         }
1.59      albertel 11329:     }
1.590     banghart 11330:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11331:     while ($location=~m{/\.\./}) {
                   11332: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11333: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11334: 	} else {
                   11335: 	    $location=~ s{/\.\./}{/}g;
                   11336: 	}
                   11337:     } #remove dir/..
1.590     banghart 11338:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11339:     return $location;
1.46      www      11340: }
1.36      albertel 11341: 
1.46      www      11342: sub hreflocation {
                   11343:     my ($dir,$file)=@_;
1.980     raeburn  11344:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11345: 	$file=filelocation($dir,$file);
1.700     albertel 11346:     } elsif ($file=~m-^/adm/-) {
                   11347: 	$file=~s-^/adm/wrapper/-/-;
                   11348: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11349:     }
                   11350:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11351: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11352:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11353: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11354: 	        {/uploaded/$1/$2/}x;
1.46      www      11355:     }
1.913     albertel 11356:     if ($file=~ m{^/userfiles/}) {
                   11357: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11358:     }
1.462     albertel 11359:     return $file;
1.465     albertel 11360: }
                   11361: 
1.1139    www      11362: 
                   11363: 
                   11364: 
                   11365: 
1.465     albertel 11366: sub current_machine_domains {
1.853     albertel 11367:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11368: }
                   11369: 
                   11370: sub machine_domains {
                   11371:     my ($hostname) = @_;
1.465     albertel 11372:     my @domains;
1.838     albertel 11373:     my %hostname = &all_hostnames();
1.465     albertel 11374:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11375: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11376: 	if ($hostname eq $name) {
1.844     albertel 11377: 	    push(@domains,&host_domain($id));
1.465     albertel 11378: 	}
                   11379:     }
                   11380:     return @domains;
                   11381: }
                   11382: 
                   11383: sub current_machine_ids {
1.853     albertel 11384:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11385: }
                   11386: 
                   11387: sub machine_ids {
                   11388:     my ($hostname) = @_;
                   11389:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11390:     my @ids;
1.888     albertel 11391:     my %name_to_host = &all_names();
1.889     albertel 11392:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11393: 	return @{ $name_to_host{$hostname} };
                   11394:     }
                   11395:     return;
1.31      www      11396: }
                   11397: 
1.824     raeburn  11398: sub additional_machine_domains {
                   11399:     my @domains;
                   11400:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11401:     while( my $line = <$fh>) {
                   11402:         $line =~ s/\s//g;
                   11403:         push(@domains,$line);
                   11404:     }
                   11405:     return @domains;
                   11406: }
                   11407: 
                   11408: sub default_login_domain {
                   11409:     my $domain = $perlvar{'lonDefDomain'};
                   11410:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11411:     foreach my $posdom (&current_machine_domains(),
                   11412:                         &additional_machine_domains()) {
                   11413:         if (lc($posdom) eq lc($testdomain)) {
                   11414:             $domain=$posdom;
                   11415:             last;
                   11416:         }
                   11417:     }
                   11418:     return $domain;
                   11419: }
                   11420: 
1.31      www      11421: # ------------------------------------------------------------- Declutters URLs
                   11422: 
                   11423: sub declutter {
                   11424:     my $thisfn=shift;
1.569     albertel 11425:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11426:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11427:     $thisfn=~s/^\///;
1.697     albertel 11428:     $thisfn=~s|^adm/wrapper/||;
                   11429:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11430:     $thisfn=~s/^res\///;
1.1172    bisitz   11431:     $thisfn=~s/^priv\///;
1.1032    raeburn  11432:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11433:         $thisfn=~s/\?.+$//;
                   11434:     }
1.268     www      11435:     return $thisfn;
                   11436: }
                   11437: 
                   11438: # ------------------------------------------------------------- Clutter up URLs
                   11439: 
                   11440: sub clutter {
                   11441:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11442:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11443: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11444:        $thisfn='/res'.$thisfn; 
                   11445:     }
1.1031    raeburn  11446:     if ($thisfn !~m|^/adm|) {
                   11447: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11448: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11449: 	} else {
                   11450: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11451: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11452: 	    if ($embstyle eq 'ssi'
                   11453: 		|| ($embstyle eq 'hdn')
                   11454: 		|| ($embstyle eq 'rat')
                   11455: 		|| ($embstyle eq 'prv')
                   11456: 		|| ($embstyle eq 'ign')) {
                   11457: 		#do nothing with these
                   11458: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11459: 		|| ($embstyle eq 'emb')
                   11460: 		|| ($embstyle eq 'wrp')) {
                   11461: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11462: 	    } elsif ($embstyle eq 'unk'
                   11463: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11464: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11465: 	    } else {
1.718     www      11466: #		&logthis("Got a blank emb style");
1.695     albertel 11467: 	    }
1.694     albertel 11468: 	}
                   11469:     }
1.31      www      11470:     return $thisfn;
1.12      www      11471: }
                   11472: 
1.787     albertel 11473: sub clutter_with_no_wrapper {
                   11474:     my $uri = &clutter(shift);
                   11475:     if ($uri =~ m-^/adm/-) {
                   11476: 	$uri =~ s-^/adm/wrapper/-/-;
                   11477: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11478:     }
                   11479:     return $uri;
                   11480: }
                   11481: 
1.557     albertel 11482: sub freeze_escape {
                   11483:     my ($value)=@_;
                   11484:     if (ref($value)) {
                   11485: 	$value=&nfreeze($value);
                   11486: 	return '__FROZEN__'.&escape($value);
                   11487:     }
                   11488:     return &escape($value);
                   11489: }
                   11490: 
1.11      www      11491: 
1.557     albertel 11492: sub thaw_unescape {
                   11493:     my ($value)=@_;
                   11494:     if ($value =~ /^__FROZEN__/) {
                   11495: 	substr($value,0,10,undef);
                   11496: 	$value=&unescape($value);
                   11497: 	return &thaw($value);
                   11498:     }
                   11499:     return &unescape($value);
                   11500: }
                   11501: 
1.436     albertel 11502: sub correct_line_ends {
                   11503:     my ($result)=@_;
                   11504:     $$result =~s/\r\n/\n/mg;
                   11505:     $$result =~s/\r/\n/mg;
1.415     albertel 11506: }
1.1       albertel 11507: # ================================================================ Main Program
                   11508: 
1.184     www      11509: sub goodbye {
1.204     albertel 11510:    &logthis("Starting Shut down");
1.443     albertel 11511: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11512:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11513: #converted
1.599     albertel 11514: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11515:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11516: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11517: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11518: #1.1 only
1.870     albertel 11519: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11520: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11521: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11522: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11523:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11524:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11525:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11526:    &flushcourselogs();
                   11527:    &logthis("Shutting down");
                   11528: }
                   11529: 
1.852     albertel 11530: sub get_dns {
1.1172.2.17  raeburn  11531:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11532:     if (!$ignore_cache) {
                   11533: 	my ($content,$cached)=
                   11534: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11535: 	if ($cached) {
1.1172.2.17  raeburn  11536: 	    &$func($content,$hashref);
1.869     albertel 11537: 	    return;
                   11538: 	}
                   11539:     }
                   11540: 
                   11541:     my %alldns;
1.852     albertel 11542:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11543:     foreach my $dns (<$config>) {
                   11544: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11545:         my $line = $1;
                   11546:         my ($host,$protocol) = split(/:/,$line);
                   11547:         if ($protocol ne 'https') {
                   11548:             $protocol = 'http';
                   11549:         }
                   11550: 	$alldns{$host} = $protocol;
1.869     albertel 11551:     }
                   11552:     while (%alldns) {
                   11553: 	my ($dns) = keys(%alldns);
1.852     albertel 11554: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11555:         $ua->timeout(30);
1.979     raeburn  11556: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11557: 	my $response=$ua->request($request);
1.979     raeburn  11558:         delete($alldns{$dns});
1.852     albertel 11559: 	next if ($response->is_error());
                   11560: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11561:         unless ($nocache) {
                   11562: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
                   11563:         }
                   11564: 	&$func(\@content,$hashref);
1.869     albertel 11565: 	return;
1.852     albertel 11566:     }
                   11567:     close($config);
1.871     albertel 11568:     my $which = (split('/',$url))[3];
                   11569:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11570:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11571:     my @content = <$config>;
1.1172.2.17  raeburn  11572:     &$func(\@content,$hashref);
                   11573:     return;
                   11574: }
                   11575: 
                   11576: # ------------------------------------------------------Get DNS checksums file
                   11577: sub parse_dns_checksums_tab {
                   11578:     my ($lines,$hashref) = @_;
                   11579:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11580:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11581:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11582:     my (%chksum,%revnum);
                   11583:     if (ref($lines) eq 'ARRAY') {
                   11584:         chomp(@{$lines});
                   11585:         my $versions = shift(@{$lines});
                   11586:         my %supported;
                   11587:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11588:             my $releaseslist = $1;
                   11589:             if ($releaseslist =~ /,/) {
                   11590:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11591:             } elsif ($releaseslist) {
                   11592:                 $supported{$releaseslist} = 1;
                   11593:             }
                   11594:         }
                   11595:         if ($supported{$release}) {
                   11596:             my $matchthis = 0;
                   11597:             foreach my $line (@{$lines}) {
                   11598:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11599:                     if ($matchthis) {
                   11600:                         last;
                   11601:                     } elsif ($1 eq $release) {
                   11602:                         $matchthis = 1;
                   11603:                     }
                   11604:                 } elsif ($matchthis) {
                   11605:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11606:                     $chksum{$file} = $shasum;
                   11607:                     $revnum{$file} = $version;
                   11608:                 }
                   11609:             }
                   11610:             if (ref($hashref) eq 'HASH') {
                   11611:                 %{$hashref} = (
                   11612:                                 sums     => \%chksum,
                   11613:                                 versions => \%revnum,
                   11614:                               );
                   11615:             }
                   11616:         }
                   11617:     }
1.869     albertel 11618:     return;
1.852     albertel 11619: }
1.1172.2.17  raeburn  11620: 
                   11621: sub fetch_dns_checksums {
                   11622:     my %checksums;
                   11623:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11624:              \%checksums);
                   11625:     return \%checksums;
                   11626: }
                   11627: 
1.327     albertel 11628: # ------------------------------------------------------------ Read domain file
                   11629: {
1.852     albertel 11630:     my $loaded;
1.846     albertel 11631:     my %domain;
                   11632: 
1.852     albertel 11633:     sub parse_domain_tab {
                   11634: 	my ($lines) = @_;
                   11635: 	foreach my $line (@$lines) {
                   11636: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11637: 
1.846     albertel 11638: 	    chomp($line);
1.852     albertel 11639: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11640: 	    my %this_domain;
                   11641: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11642: 			       'lang_def', 'city', 'longi', 'lati',
                   11643: 			       'primary') {
                   11644: 		$this_domain{$field} = shift(@elements);
                   11645: 	    }
                   11646: 	    $domain{$name} = \%this_domain;
1.852     albertel 11647: 	}
                   11648:     }
1.864     albertel 11649: 
                   11650:     sub reset_domain_info {
                   11651: 	undef($loaded);
                   11652: 	undef(%domain);
                   11653:     }
                   11654: 
1.852     albertel 11655:     sub load_domain_tab {
1.869     albertel 11656: 	my ($ignore_cache) = @_;
                   11657: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11658: 	my $fh;
                   11659: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11660: 	    my @lines = <$fh>;
                   11661: 	    &parse_domain_tab(\@lines);
1.448     albertel 11662: 	}
1.852     albertel 11663: 	close($fh);
                   11664: 	$loaded = 1;
1.327     albertel 11665:     }
1.846     albertel 11666: 
                   11667:     sub domain {
1.852     albertel 11668: 	&load_domain_tab() if (!$loaded);
                   11669: 
1.846     albertel 11670: 	my ($name,$what) = @_;
                   11671: 	return if ( !exists($domain{$name}) );
                   11672: 
                   11673: 	if (!$what) {
                   11674: 	    return $domain{$name}{'description'};
                   11675: 	}
                   11676: 	return $domain{$name}{$what};
                   11677:     }
1.974     raeburn  11678: 
                   11679:     sub domain_info {
                   11680:         &load_domain_tab() if (!$loaded);
                   11681:         return %domain;
                   11682:     }
                   11683: 
1.327     albertel 11684: }
                   11685: 
                   11686: 
1.1       albertel 11687: # ------------------------------------------------------------- Read hosts file
                   11688: {
1.838     albertel 11689:     my %hostname;
1.844     albertel 11690:     my %hostdom;
1.845     albertel 11691:     my %libserv;
1.852     albertel 11692:     my $loaded;
1.888     albertel 11693:     my %name_to_host;
1.1074    raeburn  11694:     my %internetdom;
1.1107    raeburn  11695:     my %LC_dns_serv;
1.852     albertel 11696: 
                   11697:     sub parse_hosts_tab {
                   11698: 	my ($file) = @_;
                   11699: 	foreach my $configline (@$file) {
                   11700: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11701:             chomp($configline);
                   11702: 	    if ($configline =~ /^\^/) {
                   11703:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11704:                     $LC_dns_serv{$1} = 1;
                   11705:                 }
                   11706:                 next;
                   11707:             }
1.1074    raeburn  11708: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11709: 	    $name=~s/\s//g;
                   11710: 	    if ($id && $domain && $role && $name) {
                   11711: 		$hostname{$id}=$name;
1.888     albertel 11712: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11713: 		$hostdom{$id}=$domain;
                   11714: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11715:                 if (defined($protocol)) {
                   11716:                     if ($protocol eq 'https') {
                   11717:                         $protocol{$id} = $protocol;
                   11718:                     } else {
                   11719:                         $protocol{$id} = 'http'; 
                   11720:                     }
1.968     raeburn  11721:                 } else {
1.969     raeburn  11722:                     $protocol{$id} = 'http';
1.968     raeburn  11723:                 }
1.1074    raeburn  11724:                 if (defined($intdom)) {
                   11725:                     $internetdom{$id} = $intdom;
                   11726:                 }
1.852     albertel 11727: 	    }
                   11728: 	}
                   11729:     }
1.864     albertel 11730:     
                   11731:     sub reset_hosts_info {
1.897     albertel 11732: 	&purge_remembered();
1.864     albertel 11733: 	&reset_domain_info();
                   11734: 	&reset_hosts_ip_info();
1.892     albertel 11735: 	undef(%name_to_host);
1.864     albertel 11736: 	undef(%hostname);
                   11737: 	undef(%hostdom);
                   11738: 	undef(%libserv);
                   11739: 	undef($loaded);
                   11740:     }
1.1       albertel 11741: 
1.852     albertel 11742:     sub load_hosts_tab {
1.869     albertel 11743: 	my ($ignore_cache) = @_;
                   11744: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11745: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11746: 	my @config = <$config>;
                   11747: 	&parse_hosts_tab(\@config);
                   11748: 	close($config);
                   11749: 	$loaded=1;
1.1       albertel 11750:     }
1.852     albertel 11751: 
1.838     albertel 11752:     sub hostname {
1.852     albertel 11753: 	&load_hosts_tab() if (!$loaded);
                   11754: 
1.838     albertel 11755: 	my ($lonid) = @_;
                   11756: 	return $hostname{$lonid};
                   11757:     }
1.845     albertel 11758: 
1.838     albertel 11759:     sub all_hostnames {
1.852     albertel 11760: 	&load_hosts_tab() if (!$loaded);
                   11761: 
1.838     albertel 11762: 	return %hostname;
                   11763:     }
1.845     albertel 11764: 
1.888     albertel 11765:     sub all_names {
                   11766: 	&load_hosts_tab() if (!$loaded);
                   11767: 
                   11768: 	return %name_to_host;
                   11769:     }
                   11770: 
1.974     raeburn  11771:     sub all_host_domain {
                   11772:         &load_hosts_tab() if (!$loaded);
                   11773:         return %hostdom;
                   11774:     }
                   11775: 
1.845     albertel 11776:     sub is_library {
1.852     albertel 11777: 	&load_hosts_tab() if (!$loaded);
                   11778: 
1.845     albertel 11779: 	return exists($libserv{$_[0]});
                   11780:     }
                   11781: 
                   11782:     sub all_library {
1.852     albertel 11783: 	&load_hosts_tab() if (!$loaded);
                   11784: 
1.845     albertel 11785: 	return %libserv;
                   11786:     }
                   11787: 
1.1062    droeschl 11788:     sub unique_library {
                   11789: 	#2x reverse removes all hostnames that appear more than once
                   11790:         my %unique = reverse &all_library();
                   11791:         return reverse %unique;
                   11792:     }
                   11793: 
1.841     albertel 11794:     sub get_servers {
1.852     albertel 11795: 	&load_hosts_tab() if (!$loaded);
                   11796: 
1.841     albertel 11797: 	my ($domain,$type) = @_;
                   11798: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11799: 	                                          : %hostname;
                   11800: 	my %result;
1.842     albertel 11801: 	if (ref($domain) eq 'ARRAY') {
                   11802: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11803: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11804: 		    $result{$host} = $hostname;
                   11805: 		}
                   11806: 	    }
                   11807: 	} else {
                   11808: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11809: 		if ($hostdom{$host} eq $domain) {
                   11810: 		    $result{$host} = $hostname;
                   11811: 		}
1.841     albertel 11812: 	    }
                   11813: 	}
                   11814: 	return %result;
                   11815:     }
1.845     albertel 11816: 
1.1062    droeschl 11817:     sub get_unique_servers {
                   11818:         my %unique = reverse &get_servers(@_);
                   11819: 	return reverse %unique;
                   11820:     }
                   11821: 
1.844     albertel 11822:     sub host_domain {
1.852     albertel 11823: 	&load_hosts_tab() if (!$loaded);
                   11824: 
1.844     albertel 11825: 	my ($lonid) = @_;
                   11826: 	return $hostdom{$lonid};
                   11827:     }
                   11828: 
1.841     albertel 11829:     sub all_domains {
1.852     albertel 11830: 	&load_hosts_tab() if (!$loaded);
                   11831: 
1.841     albertel 11832: 	my %seen;
                   11833: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11834: 	return @uniq;
                   11835:     }
1.1074    raeburn  11836: 
                   11837:     sub internet_dom {
                   11838:         &load_hosts_tab() if (!$loaded);
                   11839: 
                   11840:         my ($lonid) = @_;
                   11841:         return $internetdom{$lonid};
                   11842:     }
1.1107    raeburn  11843: 
                   11844:     sub is_LC_dns {
                   11845:         &load_hosts_tab() if (!$loaded);
                   11846: 
                   11847:         my ($hostname) = @_;
                   11848:         return exists($LC_dns_serv{$hostname});
                   11849:     }
                   11850: 
1.1       albertel 11851: }
                   11852: 
1.847     albertel 11853: { 
                   11854:     my %iphost;
1.856     albertel 11855:     my %name_to_ip;
                   11856:     my %lonid_to_ip;
1.869     albertel 11857: 
1.847     albertel 11858:     sub get_hosts_from_ip {
                   11859: 	my ($ip) = @_;
                   11860: 	my %iphosts = &get_iphost();
                   11861: 	if (ref($iphosts{$ip})) {
                   11862: 	    return @{$iphosts{$ip}};
                   11863: 	}
                   11864: 	return;
1.839     albertel 11865:     }
1.864     albertel 11866:     
                   11867:     sub reset_hosts_ip_info {
                   11868: 	undef(%iphost);
                   11869: 	undef(%name_to_ip);
                   11870: 	undef(%lonid_to_ip);
                   11871:     }
1.856     albertel 11872: 
                   11873:     sub get_host_ip {
                   11874: 	my ($lonid) = @_;
                   11875: 	if (exists($lonid_to_ip{$lonid})) {
                   11876: 	    return $lonid_to_ip{$lonid};
                   11877: 	}
                   11878: 	my $name=&hostname($lonid);
                   11879:    	my $ip = gethostbyname($name);
                   11880: 	return if (!$ip || length($ip) ne 4);
                   11881: 	$ip=inet_ntoa($ip);
                   11882: 	$name_to_ip{$name}   = $ip;
                   11883: 	$lonid_to_ip{$lonid} = $ip;
                   11884: 	return $ip;
                   11885:     }
1.847     albertel 11886:     
                   11887:     sub get_iphost {
1.869     albertel 11888: 	my ($ignore_cache) = @_;
1.894     albertel 11889: 
1.869     albertel 11890: 	if (!$ignore_cache) {
                   11891: 	    if (%iphost) {
                   11892: 		return %iphost;
                   11893: 	    }
                   11894: 	    my ($ip_info,$cached)=
                   11895: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11896: 	    if ($cached) {
                   11897: 		%iphost      = %{$ip_info->[0]};
                   11898: 		%name_to_ip  = %{$ip_info->[1]};
                   11899: 		%lonid_to_ip = %{$ip_info->[2]};
                   11900: 		return %iphost;
                   11901: 	    }
                   11902: 	}
1.894     albertel 11903: 
                   11904: 	# get yesterday's info for fallback
                   11905: 	my %old_name_to_ip;
                   11906: 	my ($ip_info,$cached)=
                   11907: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11908: 	if ($cached) {
                   11909: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11910: 	}
                   11911: 
1.888     albertel 11912: 	my %name_to_host = &all_names();
                   11913: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11914: 	    my $ip;
                   11915: 	    if (!exists($name_to_ip{$name})) {
                   11916: 		$ip = gethostbyname($name);
                   11917: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11918: 		    if (defined($old_name_to_ip{$name})) {
                   11919: 			$ip = $old_name_to_ip{$name};
                   11920: 			&logthis("Can't find $name defaulting to old $ip");
                   11921: 		    } else {
                   11922: 			&logthis("Name $name no IP found");
                   11923: 			next;
                   11924: 		    }
                   11925: 		} else {
                   11926: 		    $ip=inet_ntoa($ip);
1.847     albertel 11927: 		}
                   11928: 		$name_to_ip{$name} = $ip;
                   11929: 	    } else {
                   11930: 		$ip = $name_to_ip{$name};
1.653     albertel 11931: 	    }
1.888     albertel 11932: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11933: 		$lonid_to_ip{$id} = $ip;
                   11934: 	    }
                   11935: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11936: 	}
1.869     albertel 11937: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11938: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11939: 				      48*60*60);
1.869     albertel 11940: 
1.847     albertel 11941: 	return %iphost;
1.598     albertel 11942:     }
                   11943: 
1.992     raeburn  11944:     #
                   11945:     #  Given a DNS returns the loncapa host name for that DNS 
                   11946:     # 
                   11947:     sub host_from_dns {
                   11948:         my ($dns) = @_;
                   11949:         my @hosts;
                   11950:         my $ip;
                   11951: 
1.993     raeburn  11952:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11953:             $ip = $name_to_ip{$dns};
                   11954:         }
                   11955:         if (!$ip) {
                   11956:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11957:             if (length($ip) == 4) { 
                   11958: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11959:             }
                   11960:         }
                   11961:         if ($ip) {
                   11962: 	    @hosts = get_hosts_from_ip($ip);
                   11963: 	    return $hosts[0];
                   11964:         }
                   11965:         return undef;
1.986     foxr     11966:     }
1.992     raeburn  11967: 
1.1074    raeburn  11968:     sub get_internet_names {
                   11969:         my ($lonid) = @_;
                   11970:         return if ($lonid eq '');
                   11971:         my ($idnref,$cached)=
                   11972:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11973:         if ($cached) {
                   11974:             return $idnref;
                   11975:         }
                   11976:         my $ip = &get_host_ip($lonid);
                   11977:         my @hosts = &get_hosts_from_ip($ip);
                   11978:         my %iphost = &get_iphost();
                   11979:         my (@idns,%seen);
                   11980:         foreach my $id (@hosts) {
                   11981:             my $dom = &host_domain($id);
                   11982:             my $prim_id = &domain($dom,'primary');
                   11983:             my $prim_ip = &get_host_ip($prim_id);
                   11984:             next if ($seen{$prim_ip});
                   11985:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11986:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11987:                     my $intdom = &internet_dom($id);
                   11988:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11989:                         push(@idns,$intdom);
                   11990:                     }
                   11991:                 }
                   11992:             }
                   11993:             $seen{$prim_ip} = 1;
                   11994:         }
                   11995:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11996:     }
                   11997: 
1.986     foxr     11998: }
                   11999: 
1.1079    raeburn  12000: sub all_loncaparevs {
                   12001:     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);
                   12002: }
                   12003: 
1.862     albertel 12004: BEGIN {
                   12005: 
                   12006: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12007:     unless ($readit) {
                   12008: {
                   12009:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12010:     %perlvar = (%perlvar,%{$configvars});
                   12011: }
                   12012: 
                   12013: 
1.1       albertel 12014: # ------------------------------------------------------ Read spare server file
                   12015: {
1.448     albertel 12016:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12017: 
                   12018:     while (my $configline=<$config>) {
                   12019:        chomp($configline);
1.284     matthew  12020:        if ($configline) {
1.784     albertel 12021: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12022: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12023: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12024:        }
                   12025:     }
1.448     albertel 12026:     close($config);
1.1       albertel 12027: }
1.11      www      12028: # ------------------------------------------------------------ Read permissions
                   12029: {
1.448     albertel 12030:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12031: 
                   12032:     while (my $configline=<$config>) {
1.448     albertel 12033: 	chomp($configline);
                   12034: 	if ($configline) {
                   12035: 	    my ($role,$perm)=split(/ /,$configline);
                   12036: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12037: 	}
1.11      www      12038:     }
1.448     albertel 12039:     close($config);
1.11      www      12040: }
                   12041: 
                   12042: # -------------------------------------------- Read plain texts for permissions
                   12043: {
1.448     albertel 12044:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12045: 
                   12046:     while (my $configline=<$config>) {
1.448     albertel 12047: 	chomp($configline);
                   12048: 	if ($configline) {
1.742     raeburn  12049: 	    my ($short,@plain)=split(/:/,$configline);
                   12050:             %{$prp{$short}} = ();
                   12051: 	    if (@plain > 0) {
                   12052:                 $prp{$short}{'std'} = $plain[0];
                   12053:                 for (my $i=1; $i<@plain; $i++) {
                   12054:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12055:                 }
                   12056:             }
1.448     albertel 12057: 	}
1.135     www      12058:     }
1.448     albertel 12059:     close($config);
1.135     www      12060: }
                   12061: 
                   12062: # ---------------------------------------------------------- Read package table
                   12063: {
1.448     albertel 12064:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12065: 
                   12066:     while (my $configline=<$config>) {
1.483     albertel 12067: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12068: 	chomp($configline);
                   12069: 	my ($short,$plain)=split(/:/,$configline);
                   12070: 	my ($pack,$name)=split(/\&/,$short);
                   12071: 	if ($plain ne '') {
                   12072: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12073: 	    $packagetab{$short}=$plain; 
                   12074: 	}
1.11      www      12075:     }
1.448     albertel 12076:     close($config);
1.329     matthew  12077: }
                   12078: 
1.1073    raeburn  12079: # ---------------------------------------------------------- Read loncaparev table
                   12080: {
                   12081:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12082:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12083:             while (my $configline=<$config>) {
                   12084:                 chomp($configline);
                   12085:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12086:                 $loncaparevs{$hostid}=$loncaparev;
                   12087:             }
                   12088:             close($config);
                   12089:         }
                   12090:     }
                   12091: }
                   12092: 
1.1074    raeburn  12093: # ---------------------------------------------------------- Read serverhostID table
                   12094: {
                   12095:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12096:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12097:             while (my $configline=<$config>) {
                   12098:                 chomp($configline);
                   12099:                 my ($name,$id)=split(/:/,$configline);
                   12100:                 $serverhomeIDs{$name}=$id;
                   12101:             }
                   12102:             close($config);
                   12103:         }
                   12104:     }
                   12105: }
                   12106: 
1.1079    raeburn  12107: {
                   12108:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12109:     if (-e $file) {
                   12110:         my $parser = HTML::LCParser->new($file);
                   12111:         while (my $token = $parser->get_token()) {
                   12112:             if ($token->[0] eq 'S') {
                   12113:                 my $item = $token->[1];
                   12114:                 my $name = $token->[2]{'name'};
                   12115:                 my $value = $token->[2]{'value'};
                   12116:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12117:                     my $release = $parser->get_text();
                   12118:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12119:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12120:                 }
                   12121:             }
                   12122:         }
                   12123:     }
1.1073    raeburn  12124: }
                   12125: 
1.1138    raeburn  12126: # ---------------------------------------------------------- Read managers table
                   12127: {
                   12128:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12129:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12130:             while (my $configline=<$config>) {
                   12131:                 chomp($configline);
                   12132:                 next if ($configline =~ /^\#/);
                   12133:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12134:                     $managerstab{$configline} = 1;
                   12135:                 }
                   12136:             }
                   12137:             close($config);
                   12138:         }
                   12139:     }
                   12140: }
                   12141: 
1.329     matthew  12142: # ------------- set up temporary directory
                   12143: {
1.1117    foxr     12144:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12145: 
1.11      www      12146: }
                   12147: 
1.794     albertel 12148: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12149: 				'compress_threshold'=> 20_000,
                   12150:  			        });
1.185     www      12151: 
1.281     www      12152: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12153: $dumpcount=0;
1.958     www      12154: $locknum=0;
1.22      www      12155: 
1.163     harris41 12156: &logtouch();
1.672     albertel 12157: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12158: $readit=1;
1.564     albertel 12159:     {
                   12160: 	use integer;
                   12161: 	my $test=(2**32)+1;
1.568     albertel 12162: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12163: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12164:     }
1.1172.2.18  raeburn  12165: 
                   12166:     {
                   12167:         eval {
                   12168:             ($apache) =
                   12169:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12170:         };
                   12171:         if ($@) {
                   12172:            $apache = 1.3;
                   12173:         }
                   12174:     }
                   12175: 
1.195     www      12176: }
1.1       albertel 12177: }
1.179     www      12178: 
1.1       albertel 12179: 1;
1.191     harris41 12180: __END__
                   12181: 
1.243     albertel 12182: =pod
                   12183: 
1.191     harris41 12184: =head1 NAME
                   12185: 
1.243     albertel 12186: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12187: 
                   12188: =head1 SYNOPSIS
                   12189: 
1.243     albertel 12190: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12191: 
                   12192:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12193: 
1.243     albertel 12194: Common parameters:
                   12195: 
                   12196: =over 4
                   12197: 
                   12198: =item *
                   12199: 
                   12200: $uname : an internal username (if $cname expecting a course Id specifically)
                   12201: 
                   12202: =item *
                   12203: 
                   12204: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12205: 
                   12206: =item *
                   12207: 
                   12208: $symb : a resource instance identifier
                   12209: 
                   12210: =item *
                   12211: 
                   12212: $namespace : the name of a .db file that contains the data needed or
                   12213: being set.
                   12214: 
                   12215: =back
                   12216: 
1.394     bowersj2 12217: =head1 OVERVIEW
1.191     harris41 12218: 
1.394     bowersj2 12219: lonnet provides subroutines which interact with the
                   12220: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12221: about classes, users, and resources.
1.243     albertel 12222: 
                   12223: For many of these objects you can also use this to store data about
                   12224: them or modify them in various ways.
1.191     harris41 12225: 
1.394     bowersj2 12226: =head2 Symbs
1.191     harris41 12227: 
1.394     bowersj2 12228: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12229: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12230: map, the resource number of the resource in the map, and the URL of
                   12231: the resource itself. The latter is somewhat redundant, but might help
                   12232: if maps change.
                   12233: 
                   12234: An example is
                   12235: 
                   12236:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12237: 
                   12238: The respective map entry is
                   12239: 
                   12240:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12241:   title="Problem 2">
                   12242:  </resource>
                   12243: 
                   12244: Symbs are used by the random number generator, as well as to store and
                   12245: restore data specific to a certain instance of for example a problem.
                   12246: 
                   12247: =head2 Storing And Retrieving Data
                   12248: 
                   12249: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12250: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12251: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12252: is is the non-critical message twin of cstore. These functions are for
                   12253: handlers to store a perl hash to a user's permanent data space in an
                   12254: easy manner, and to retrieve it again on another call. It is expected
                   12255: that a handler would use this once at the beginning to retrieve data,
                   12256: and then again once at the end to send only the new data back.
                   12257: 
                   12258: The data is stored in the user's data directory on the user's
                   12259: homeserver under the ID of the course.
                   12260: 
                   12261: The hash that is returned by restore will have all of the previous
                   12262: value for all of the elements of the hash.
                   12263: 
                   12264: Example:
                   12265: 
                   12266:  #creating a hash
                   12267:  my %hash;
                   12268:  $hash{'foo'}='bar';
                   12269: 
                   12270:  #storing it
                   12271:  &Apache::lonnet::cstore(\%hash);
                   12272: 
                   12273:  #changing a value
                   12274:  $hash{'foo'}='notbar';
                   12275: 
                   12276:  #adding a new value
                   12277:  $hash{'bar'}='foo';
                   12278:  &Apache::lonnet::cstore(\%hash);
                   12279: 
                   12280:  #retrieving the hash
                   12281:  my %history=&Apache::lonnet::restore();
                   12282: 
                   12283:  #print the hash
                   12284:  foreach my $key (sort(keys(%history))) {
                   12285:    print("\%history{$key} = $history{$key}");
                   12286:  }
                   12287: 
                   12288: Will print out:
1.191     harris41 12289: 
1.394     bowersj2 12290:  %history{1:foo} = bar
                   12291:  %history{1:keys} = foo:timestamp
                   12292:  %history{1:timestamp} = 990455579
                   12293:  %history{2:bar} = foo
                   12294:  %history{2:foo} = notbar
                   12295:  %history{2:keys} = foo:bar:timestamp
                   12296:  %history{2:timestamp} = 990455580
                   12297:  %history{bar} = foo
                   12298:  %history{foo} = notbar
                   12299:  %history{timestamp} = 990455580
                   12300:  %history{version} = 2
                   12301: 
                   12302: Note that the special hash entries C<keys>, C<version> and
                   12303: C<timestamp> were added to the hash. C<version> will be equal to the
                   12304: total number of versions of the data that have been stored. The
                   12305: C<timestamp> attribute will be the UNIX time the hash was
                   12306: stored. C<keys> is available in every historical section to list which
                   12307: keys were added or changed at a specific historical revision of a
                   12308: hash.
                   12309: 
                   12310: B<Warning>: do not store the hash that restore returns directly. This
                   12311: will cause a mess since it will restore the historical keys as if the
                   12312: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12313: 
1.394     bowersj2 12314: Calling convention:
1.191     harris41 12315: 
1.394     bowersj2 12316:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12317:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12318: 
1.394     bowersj2 12319: For more detailed information, see lonnet specific documentation.
1.191     harris41 12320: 
1.394     bowersj2 12321: =head1 RETURN MESSAGES
1.191     harris41 12322: 
1.394     bowersj2 12323: =over 4
1.191     harris41 12324: 
1.394     bowersj2 12325: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12326: 
1.394     bowersj2 12327: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12328: when the connection is brought back up
1.191     harris41 12329: 
1.394     bowersj2 12330: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12331: for later delivery
1.191     harris41 12332: 
1.967     bisitz   12333: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12334: 
1.394     bowersj2 12335: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12336: that was requested
1.191     harris41 12337: 
1.243     albertel 12338: =back
1.191     harris41 12339: 
1.243     albertel 12340: =head1 PUBLIC SUBROUTINES
1.191     harris41 12341: 
1.243     albertel 12342: =head2 Session Environment Functions
1.191     harris41 12343: 
1.243     albertel 12344: =over 4
1.191     harris41 12345: 
1.394     bowersj2 12346: =item * 
                   12347: X<appenv()>
1.949     raeburn  12348: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12349: the user envirnoment file, and will be restored for each access this
1.620     albertel 12350: user makes during this session, also modifies the %env for the current
1.949     raeburn  12351: process. Optional rolesarrayref - if defined contains a reference to an array
                   12352: of roles which are exempt from the restriction on modifying user.role entries 
                   12353: in the user's environment.db and in %env.    
1.191     harris41 12354: 
                   12355: =item *
1.394     bowersj2 12356: X<delenv()>
1.987     raeburn  12357: B<delenv($delthis,$regexp)>: removes all items from the session
                   12358: environment file that begin with $delthis. If the 
                   12359: optional second arg - $regexp - is true, $delthis is treated as a 
                   12360: regular expression, otherwise \Q$delthis\E is used. 
                   12361: The values are also deleted from the current processes %env.
1.191     harris41 12362: 
1.795     albertel 12363: =item * get_env_multiple($name) 
                   12364: 
                   12365: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12366: values may be defined and end up as an array ref.
                   12367: 
                   12368: returns an array of values
                   12369: 
1.243     albertel 12370: =back
                   12371: 
                   12372: =head2 User Information
1.191     harris41 12373: 
1.243     albertel 12374: =over 4
1.191     harris41 12375: 
                   12376: =item *
1.394     bowersj2 12377: X<queryauthenticate()>
                   12378: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12379: authentication scheme
                   12380: 
                   12381: =item *
1.394     bowersj2 12382: X<authenticate()>
1.1073    raeburn  12383: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12384: authenticate user from domain's lib servers (first use the current
                   12385: one). C<$upass> should be the users password.
1.1073    raeburn  12386: $checkdefauth is optional (value is 1 if a check should be made to
                   12387:    authenticate user using default authentication method, and allow
                   12388:    account creation if username does not have account in the domain).
                   12389: $clientcancheckhost is optional (value is 1 if checking whether the
                   12390:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12391: 
                   12392: =item *
1.394     bowersj2 12393: X<homeserver()>
                   12394: B<homeserver($uname,$udom)>: find the server which has
                   12395: the user's directory and files (there must be only one), this caches
                   12396: the answer, and also caches if there is a borken connection.
1.191     harris41 12397: 
                   12398: =item *
1.394     bowersj2 12399: X<idget()>
                   12400: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12401: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12402: username, and only 1 username per ID in a specific domain) (returns
                   12403: hash: id=>name,id=>name)
1.191     harris41 12404: 
                   12405: =item *
1.394     bowersj2 12406: X<idrget()>
                   12407: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12408: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12409: 
                   12410: =item *
1.394     bowersj2 12411: X<idput()>
                   12412: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12413: 
                   12414: =item *
1.394     bowersj2 12415: X<rolesinit()>
1.1169    droeschl 12416: B<rolesinit($udom,$username)>: get user privileges.
                   12417: returns user role, first access and timer interval hashes
1.243     albertel 12418: 
                   12419: =item *
1.1171    droeschl 12420: X<privileged()>
                   12421: B<privileged($username,$domain)>: returns a true if user has a
                   12422: privileged and active role (i.e. su or dc), false otherwise.
                   12423: 
                   12424: =item *
1.551     albertel 12425: X<getsection()>
                   12426: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12427: course $cname, return section name/number or '' for "not in course"
                   12428: and '-1' for "no section"
                   12429: 
                   12430: =item *
1.394     bowersj2 12431: X<userenvironment()>
                   12432: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12433: passed in @what from the requested user's environment, returns a hash
                   12434: 
1.858     raeburn  12435: =item * 
                   12436: X<userlog_query()>
1.859     albertel 12437: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12438: activity.log file. %filters defines filters applied when parsing the
                   12439: log file. These can be start or end timestamps, or the type of action
                   12440: - log to look for Login or Logout events, check for Checkin or
                   12441: Checkout, role for role selection. The response is in the form
                   12442: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12443: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12444: 
1.243     albertel 12445: =back
                   12446: 
                   12447: =head2 User Roles
                   12448: 
                   12449: =over 4
                   12450: 
                   12451: =item *
                   12452: 
1.810     raeburn  12453: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12454:  F: full access
                   12455:  U,I,K: authentication modes (cxx only)
                   12456:  '': forbidden
                   12457:  1: user needs to choose course
                   12458:  2: browse allowed
1.766     albertel 12459:  A: passphrase authentication needed
1.243     albertel 12460: 
                   12461: =item *
                   12462: 
1.1172.2.13  raeburn  12463: constructaccess($url,$setpriv) : check for access to construction space URL
                   12464: 
                   12465: See if the owner domain and name in the URL match those in the
                   12466: expected environment.  If so, return three element list
                   12467: ($ownername,$ownerdomain,$ownerhome).
                   12468: 
                   12469: Otherwise return the null string.
                   12470: 
                   12471: If second argument 'setpriv' is true, it assigns the privileges,
                   12472: and returns the same three element list, unless the owner has
                   12473: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12474: in which case the null string is returned.
                   12475: 
                   12476: =item *
                   12477: 
1.243     albertel 12478: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12479: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12480: and course level
                   12481: 
                   12482: =item *
                   12483: 
1.988     raeburn  12484: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12485: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12486: $type is Course (default) or Community.
1.988     raeburn  12487: If $forcedefault evaluates to true, text returned will be default 
                   12488: text for $type. Otherwise, if this is a course, the text returned 
                   12489: will be a custom name for the role (if defined in the course's 
                   12490: environment).  If no custom name is defined the default is returned.
                   12491:    
1.832     raeburn  12492: =item *
                   12493: 
1.935     raeburn  12494: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12495: All arguments are optional. Returns a hash of a roles, either for
                   12496: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12497: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12498: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12499: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12500: For each key, value is set to colon-separated start and end times for
                   12501: the role.  If no username and domain are specified, will default to
1.934     raeburn  12502: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12503: of role statuses (active, future or previous), roles 
                   12504: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12505: to restrict the list of roles reported. If no array ref is 
                   12506: provided for types, will default to return only active roles.
1.834     albertel 12507: 
1.1172.2.13  raeburn  12508: =item *
                   12509: 
                   12510: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12511: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12512: 
                   12513: Additional optional arguments are: $type (if role checking is to be restricted
                   12514: to certain user status types -- previous (expired roles), active (currently
                   12515: available roles) or future (roles available in the future), and
                   12516: $hideprivileged -- if true will not report course roles for users who
                   12517: have active Domain Coordinator or Super User roles.
                   12518: 
1.243     albertel 12519: =back
                   12520: 
                   12521: =head2 User Modification
                   12522: 
                   12523: =over 4
                   12524: 
                   12525: =item *
                   12526: 
1.957     raeburn  12527: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12528: user for the level given by URL.  Optional start and end dates (leave empty
                   12529: string or zero for "no date")
1.191     harris41 12530: 
                   12531: =item *
                   12532: 
1.243     albertel 12533: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12534: change a users, password, possible return values are: ok,
                   12535: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12536: refused
1.191     harris41 12537: 
                   12538: =item *
                   12539: 
1.243     albertel 12540: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12541: 
                   12542: =item *
                   12543: 
1.1058    raeburn  12544: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12545:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12546: 
                   12547: will update user information (firstname,middlename,lastname,generation,
                   12548: permanentemail), and if forceid is true, student/employee ID also.
                   12549: A user's institutional affiliation(s) can also be updated.
                   12550: User information fields will not be overwritten with empty entries 
                   12551: unless the field is included in the $candelete array reference.
                   12552: This array is included when a single user is modified via "Manage Users",
                   12553: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12554: 
                   12555: =item *
                   12556: 
1.286     matthew  12557: modifystudent
                   12558: 
1.957     raeburn  12559: modify a student's enrollment and identification information.
1.286     matthew  12560: The course id is resolved based on the current users environment.  
                   12561: This means the envoking user must be a course coordinator or otherwise
                   12562: associated with a course.
                   12563: 
1.297     matthew  12564: This call is essentially a wrapper for lonnet::modifyuser and
                   12565: lonnet::modify_student_enrollment
1.286     matthew  12566: 
                   12567: Inputs: 
                   12568: 
                   12569: =over 4
                   12570: 
1.957     raeburn  12571: =item B<$udom> Student's loncapa domain
1.286     matthew  12572: 
1.957     raeburn  12573: =item B<$uname> Student's loncapa login name
1.286     matthew  12574: 
1.964     bisitz   12575: =item B<$uid> Student/Employee ID
1.286     matthew  12576: 
1.957     raeburn  12577: =item B<$umode> Student's authentication mode
1.286     matthew  12578: 
1.957     raeburn  12579: =item B<$upass> Student's password
1.286     matthew  12580: 
1.957     raeburn  12581: =item B<$first> Student's first name
1.286     matthew  12582: 
1.957     raeburn  12583: =item B<$middle> Student's middle name
1.286     matthew  12584: 
1.957     raeburn  12585: =item B<$last> Student's last name
1.286     matthew  12586: 
1.957     raeburn  12587: =item B<$gene> Student's generation
1.286     matthew  12588: 
1.957     raeburn  12589: =item B<$usec> Student's section in course
1.286     matthew  12590: 
                   12591: =item B<$end> Unix time of the roles expiration
                   12592: 
                   12593: =item B<$start> Unix time of the roles start date
                   12594: 
                   12595: =item B<$forceid> If defined, allow $uid to be changed
                   12596: 
                   12597: =item B<$desiredhome> server to use as home server for student
                   12598: 
1.957     raeburn  12599: =item B<$email> Student's permanent e-mail address
                   12600: 
                   12601: =item B<$type> Type of enrollment (auto or manual)
                   12602: 
1.963     raeburn  12603: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12604: 
                   12605: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12606: 
1.963     raeburn  12607: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12608: 
1.963     raeburn  12609: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12610: 
1.1172.2.19  raeburn  12611: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12612: 
                   12613: =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  12614: 
1.286     matthew  12615: =back
1.297     matthew  12616: 
                   12617: =item *
                   12618: 
                   12619: modify_student_enrollment
                   12620: 
                   12621: Change a students enrollment status in a class.  The environment variable
                   12622: 'role.request.course' must be defined for this function to proceed.
                   12623: 
                   12624: Inputs:
                   12625: 
                   12626: =over 4
                   12627: 
                   12628: =item $udom, students domain
                   12629: 
                   12630: =item $uname, students name
                   12631: 
                   12632: =item $uid, students user id
                   12633: 
                   12634: =item $first, students first name
                   12635: 
                   12636: =item $middle
                   12637: 
                   12638: =item $last
                   12639: 
                   12640: =item $gene
                   12641: 
                   12642: =item $usec
                   12643: 
                   12644: =item $end
                   12645: 
                   12646: =item $start
                   12647: 
1.957     raeburn  12648: =item $type
                   12649: 
                   12650: =item $locktype
                   12651: 
                   12652: =item $cid
                   12653: 
                   12654: =item $selfenroll
                   12655: 
                   12656: =item $context
                   12657: 
1.1172.2.19  raeburn  12658: =item $credits, number of credits student will earn from this class
                   12659: 
1.297     matthew  12660: =back
                   12661: 
1.191     harris41 12662: 
                   12663: =item *
                   12664: 
1.243     albertel 12665: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12666: custom role; give a custom role to a user for the level given by URL.  Specify
                   12667: name and domain of role author, and role name
1.191     harris41 12668: 
                   12669: =item *
                   12670: 
1.243     albertel 12671: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12672: 
                   12673: =item *
                   12674: 
1.243     albertel 12675: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12676: 
                   12677: =back
                   12678: 
                   12679: =head2 Course Infomation
                   12680: 
                   12681: =over 4
1.191     harris41 12682: 
                   12683: =item *
                   12684: 
1.1118    foxr     12685: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12686: specified course id, including all environment settings for the
                   12687: course, the description of the course will be in the hash under the
                   12688: key 'description'
1.191     harris41 12689: 
1.1118    foxr     12690: $options is an optional parameter that if supplied is a hash reference that controls
                   12691: what how this function works.  It has the following key/values:
                   12692: 
                   12693: =over 4
                   12694: 
                   12695: =item freshen_cache
                   12696: 
                   12697: If defined, and the environment cache for the course is valid, it is 
                   12698: returned in the returned hash.
                   12699: 
                   12700: =item one_time
                   12701: 
                   12702: If defined, the last cache time is set to _now_
                   12703: 
                   12704: =item user
                   12705: 
                   12706: If defined, the supplied username is used instead of the current user.
                   12707: 
                   12708: 
                   12709: =back
                   12710: 
1.191     harris41 12711: =item *
                   12712: 
1.624     albertel 12713: resdata($name,$domain,$type,@which) : request for current parameter
                   12714: setting for a specific $type, where $type is either 'course' or 'user',
                   12715: @what should be a list of parameters to ask about. This routine caches
                   12716: answers for 5 minutes.
1.243     albertel 12717: 
1.877     foxr     12718: =item *
                   12719: 
                   12720: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12721: data base, returning a hash that is keyed by the resource name and has
                   12722: values that are the resource value.  I believe that the timestamps and
                   12723: versions are also returned.
                   12724: 
1.243     albertel 12725: =back
                   12726: 
                   12727: =head2 Course Modification
                   12728: 
                   12729: =over 4
1.191     harris41 12730: 
                   12731: =item *
                   12732: 
1.243     albertel 12733: writecoursepref($courseid,%prefs) : write preferences (environment
                   12734: database) for a course
1.191     harris41 12735: 
                   12736: =item *
                   12737: 
1.1011    raeburn  12738: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12739: 
                   12740: =item *
                   12741: 
1.1038    raeburn  12742: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12743: 
1.1167    droeschl 12744: =item *
                   12745: 
                   12746: is_course($courseid), is_course($cdom, $cnum)
                   12747: 
                   12748: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12749: two component version $cdom, $cnum. It checks if the specified course exists.
                   12750: 
                   12751: Returns:
                   12752:     undef if the course doesn't exist, otherwise
                   12753:     in scalar context the combined courseid.
                   12754:     in list context the two components of the course identifier, domain and 
                   12755:     courseid.    
                   12756: 
1.243     albertel 12757: =back
                   12758: 
                   12759: =head2 Resource Subroutines
                   12760: 
                   12761: =over 4
1.191     harris41 12762: 
                   12763: =item *
                   12764: 
1.243     albertel 12765: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12766: 
                   12767: =item *
                   12768: 
1.243     albertel 12769: repcopy($filename) : subscribes to the requested file, and attempts to
                   12770: replicate from the owning library server, Might return
1.607     raeburn  12771: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12772: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12773: resource. Expects the local filesystem pathname
                   12774: (/home/httpd/html/res/....)
                   12775: 
                   12776: =back
                   12777: 
                   12778: =head2 Resource Information
                   12779: 
                   12780: =over 4
1.191     harris41 12781: 
                   12782: =item *
                   12783: 
1.243     albertel 12784: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12785: a vairety of different possible values, $varname should be a request
                   12786: string, and the other parameters can be used to specify who and what
                   12787: one is asking about.
                   12788: 
                   12789: Possible values for $varname are environment.lastname (or other item
                   12790: from the envirnment hash), user.name (or someother aspect about the
                   12791: user), resource.0.maxtries (or some other part and parameter of a
                   12792: resource)
1.204     albertel 12793: 
                   12794: =item *
                   12795: 
1.243     albertel 12796: directcondval($number) : get current value of a condition; reads from a state
                   12797: string
1.204     albertel 12798: 
                   12799: =item *
                   12800: 
1.243     albertel 12801: condval($condidx) : value of condition index based on state
1.204     albertel 12802: 
                   12803: =item *
                   12804: 
1.243     albertel 12805: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12806: resource's metadata, $what should be either a specific key, or either
                   12807: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12808: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12809: 
                   12810: this function automatically caches all requests
1.191     harris41 12811: 
                   12812: =item *
                   12813: 
1.243     albertel 12814: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12815: network of library servers; returns file handle of where SQL and regex results
                   12816: will be stored for query
1.191     harris41 12817: 
                   12818: =item *
                   12819: 
1.243     albertel 12820: symbread($filename) : return symbolic list entry (filename argument optional);
                   12821: returns the data handle
1.191     harris41 12822: 
                   12823: =item *
                   12824: 
1.1172.2.17  raeburn  12825: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12826: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12827: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12828: on failure, user must be in a course, as it assumes the existence of
                   12829: the course initial hash, and uses $env('request.course.id'}.  The third
                   12830: arg is an optional reference to a scalar.  If this arg is passed in the
                   12831: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12832: encrypted; otherwise it will be null.
1.243     albertel 12833: 
1.191     harris41 12834: =item *
                   12835: 
1.243     albertel 12836: symbclean($symb) : removes versions numbers from a symb, returns the
                   12837: cleaned symb
1.191     harris41 12838: 
                   12839: =item *
                   12840: 
1.243     albertel 12841: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12842: course map, user must be in a course for it to work.
1.191     harris41 12843: 
                   12844: =item *
                   12845: 
1.243     albertel 12846: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12847: 
                   12848: =item *
                   12849: 
1.243     albertel 12850: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12851: a random seed, all arguments are optional, if they aren't sent it uses the
                   12852: environment to derive them. Note: if symb isn't sent and it can't get one
                   12853: from &symbread it will use the current time as its return value
1.191     harris41 12854: 
                   12855: =item *
                   12856: 
1.243     albertel 12857: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12858: unfakeable, receipt
1.191     harris41 12859: 
                   12860: =item *
                   12861: 
1.620     albertel 12862: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12863: 
                   12864: =item *
                   12865: 
1.243     albertel 12866: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12867: 
                   12868: =item *
                   12869: 
1.243     albertel 12870: 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 12871: 
                   12872: =item *
                   12873: 
1.243     albertel 12874: 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 12875: 
                   12876: =item *
                   12877: 
1.243     albertel 12878: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12879: 
                   12880: =item *
                   12881: 
1.243     albertel 12882: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12883: forcing spreadsheet to reevaluate the resource scores next time.
                   12884: 
1.1172.2.13  raeburn  12885: =item *
                   12886: 
                   12887: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12888: when viewing in course context.
                   12889: 
                   12890:  input: six args -- filename (decluttered), course number, course domain,
                   12891:                     url, symb (if registered) and group (if this is a
                   12892:                     group item -- e.g., bulletin board, group page etc.).
                   12893: 
                   12894:  output: array of five scalars --
                   12895:          $cfile -- url for file editing if editable on current server
                   12896:          $home -- homeserver of resource (i.e., for author if published,
                   12897:                                           or course if uploaded.).
                   12898:          $switchserver --  1 if server switch will be needed.
                   12899:          $forceedit -- 1 if icon/link should be to go to edit mode
                   12900:          $forceview -- 1 if icon/link should be to go to view mode
                   12901: 
                   12902: =item *
                   12903: 
                   12904: is_course_upload($file,$cnum,$cdom)
                   12905: 
                   12906: Used in course context to determine if current file was uploaded to
                   12907: the course (i.e., would be found in /userfiles/docs on the course's
                   12908: homeserver.
                   12909: 
                   12910:   input: 3 args -- filename (decluttered), course number and course domain.
                   12911:   output: boolean -- 1 if file was uploaded.
                   12912: 
1.243     albertel 12913: =back
                   12914: 
                   12915: =head2 Storing/Retreiving Data
                   12916: 
                   12917: =over 4
1.191     harris41 12918: 
                   12919: =item *
                   12920: 
1.243     albertel 12921: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12922: for this url; hashref needs to be given and should be a \%hashname; the
                   12923: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12924: be derived from the env
1.191     harris41 12925: 
                   12926: =item *
                   12927: 
1.243     albertel 12928: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12929: uses critical subroutine
1.191     harris41 12930: 
                   12931: =item *
                   12932: 
1.243     albertel 12933: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12934: all args are optional
1.191     harris41 12935: 
                   12936: =item *
                   12937: 
1.717     albertel 12938: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12939: dumps the complete (or key matching regexp) namespace into a hash
                   12940: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12941: normally &store()ed into
                   12942: 
                   12943: $range should be either an integer '100' (give me the first 100
                   12944:                                            matching records)
                   12945:               or be  two integers sperated by a - with no spaces
                   12946:                  '30-50' (give me the 30th through the 50th matching
                   12947:                           records)
                   12948: 
                   12949: 
                   12950: =item *
                   12951: 
                   12952: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12953: replaces a &store() version of data with a replacement set of data
                   12954: for a particular resource in a namespace passed in the $storehash hash 
                   12955: reference
                   12956: 
                   12957: =item *
                   12958: 
1.243     albertel 12959: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12960: works very similar to store/cstore, but all data is stored in a
                   12961: temporary location and can be reset using tmpreset, $storehash should
                   12962: be a hash reference, returns nothing on success
1.191     harris41 12963: 
                   12964: =item *
                   12965: 
1.243     albertel 12966: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12967: similar to restore, but all data is stored in a temporary location and
                   12968: can be reset using tmpreset. Returns a hash of values on success,
                   12969: error string otherwise.
1.191     harris41 12970: 
                   12971: =item *
                   12972: 
1.243     albertel 12973: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12974: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12975: 
                   12976: =item *
                   12977: 
1.243     albertel 12978: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12979: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12980: 
                   12981: =item *
                   12982: 
1.243     albertel 12983: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12984: namesp ($udom and $uname are optional)
1.191     harris41 12985: 
                   12986: =item *
                   12987: 
1.702     albertel 12988: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12989: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12990: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12991: 
1.702     albertel 12992: $range should be either an integer '100' (give me the first 100
                   12993:                                            matching records)
                   12994:               or be  two integers sperated by a - with no spaces
                   12995:                  '30-50' (give me the 30th through the 50th matching
                   12996:                           records)
1.449     matthew  12997: =item *
                   12998: 
                   12999: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13000: $store can be a scalar, an array reference, or if the amount to be 
                   13001: incremented is > 1, a hash reference.
                   13002: 
                   13003: ($udom and $uname are optional)
1.191     harris41 13004: 
                   13005: =item *
                   13006: 
1.243     albertel 13007: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13008: ($udom and $uname are optional)
1.191     harris41 13009: 
                   13010: =item *
                   13011: 
1.243     albertel 13012: cput($namespace,$storehash,$udom,$uname) : critical put
                   13013: ($udom and $uname are optional)
1.191     harris41 13014: 
                   13015: =item *
                   13016: 
1.748     albertel 13017: newput($namespace,$storehash,$udom,$uname) :
                   13018: 
                   13019: Attempts to store the items in the $storehash, but only if they don't
                   13020: currently exist, if this succeeds you can be certain that you have 
                   13021: successfully created a new key value pair in the $namespace db.
                   13022: 
                   13023: 
                   13024: Args:
                   13025:  $namespace: name of database to store values to
                   13026:  $storehash: hashref to store to the db
                   13027:  $udom: (optional) domain of user containing the db
                   13028:  $uname: (optional) name of user caontaining the db
                   13029: 
                   13030: Returns:
                   13031:  'ok' -> succeeded in storing all keys of $storehash
                   13032:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13033:                         least <key> already existed in the db (other
                   13034:                         requested keys may also already exist)
1.967     bisitz   13035:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13036:  'con_lost' -> unable to contact request server
                   13037:  'refused' -> action was not allowed by remote machine
                   13038: 
                   13039: 
                   13040: =item *
                   13041: 
1.243     albertel 13042: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13043: reference filled in from namesp (encrypts the return communication)
                   13044: ($udom and $uname are optional)
1.191     harris41 13045: 
                   13046: =item *
                   13047: 
1.243     albertel 13048: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13049: critical subroutine
                   13050: 
1.806     raeburn  13051: =item *
                   13052: 
1.860     raeburn  13053: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13054: array reference filled in from namespace found in domain level on either
                   13055: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13056: 
                   13057: =item *
                   13058: 
1.860     raeburn  13059: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13060: domain level either on specified domain server ($uhome) or primary domain 
                   13061: server ($udom and $uhome are optional)
1.806     raeburn  13062: 
1.943     raeburn  13063: =item * 
                   13064: 
                   13065: get_domain_defaults($target_domain) : returns hash with defaults for
                   13066: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13067: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13068: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13069: Values are retrieved from cache (if current), or from domain's configuration.db
                   13070: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13071: or lonTabs/domain.tab. 
                   13072: 
                   13073: %domdefaults = &get_auth_defaults($target_domain);
                   13074: 
1.243     albertel 13075: =back
                   13076: 
                   13077: =head2 Network Status Functions
                   13078: 
                   13079: =over 4
1.191     harris41 13080: 
                   13081: =item *
                   13082: 
1.1137    raeburn  13083: dirlist() : return directory list based on URI (first arg).
                   13084: 
                   13085: Inputs: 1 required, 5 optional.
                   13086: 
                   13087: =over
                   13088: 
                   13089: =item 
                   13090: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13091: 
                   13092: =item
                   13093: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13094: 
                   13095: =item
                   13096: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13097: 
                   13098: =item
                   13099: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13100: 
                   13101: =item
                   13102: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13103: 
                   13104: =item 
                   13105: $alternateRoot - path to prepend in place of path from $uri.
                   13106: 
                   13107: =back
                   13108: 
                   13109: Returns: Array of up to two items.
                   13110: 
                   13111: =over
                   13112: 
                   13113: a reference to an array of files/subdirectories
                   13114: 
                   13115: =over
                   13116: 
                   13117: Each element in the array of files/subdirectories is a & separated list of
                   13118: item name and the result of running stat on the item.  If dirlist was requested
                   13119: for a file instead of a directory, the item name will be ''. For a directory 
                   13120: listing, if the item is a metadata file, the element will end &N&M 
                   13121: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13122: default copyright set (1).  
                   13123: 
                   13124: =back
                   13125: 
                   13126: a scalar containing error condition (if encountered).
                   13127: 
                   13128: =over
                   13129: 
                   13130: =item 
                   13131: no_host (no homeserver identified for $username:$domain).
                   13132: 
                   13133: =item 
                   13134: no_such_host (server contacted for listing not identified as valid host).
                   13135: 
                   13136: =item 
                   13137: con_lost (connection to remote server failed).
                   13138: 
                   13139: =item 
                   13140: refused (invalid $username:$domain received on lond side).
                   13141: 
                   13142: =item 
                   13143: no_such_dir (directory at specified path on lond side does not exist). 
                   13144: 
                   13145: =item 
                   13146: empty (directory at specified path on lond side is empty).
                   13147: 
                   13148: =over
                   13149: 
                   13150: This is currently not encountered because the &ls3, &ls2, 
                   13151: &ls (_handler) routines on the lond side do not filter out
                   13152: . and .. from a directory listing. 
                   13153: 
                   13154: =back
                   13155: 
                   13156: =back
                   13157: 
                   13158: =back
1.191     harris41 13159: 
                   13160: =item *
                   13161: 
1.243     albertel 13162: spareserver() : find server with least workload from spare.tab
                   13163: 
1.986     foxr     13164: 
                   13165: =item *
                   13166: 
                   13167: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13168: if there is no corresponding loncapa host.
                   13169: 
1.243     albertel 13170: =back
                   13171: 
1.986     foxr     13172: 
1.243     albertel 13173: =head2 Apache Request
                   13174: 
                   13175: =over 4
1.191     harris41 13176: 
                   13177: =item *
                   13178: 
1.243     albertel 13179: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13180: localhost, posts hash
                   13181: 
                   13182: =back
                   13183: 
                   13184: =head2 Data to String to Data
                   13185: 
                   13186: =over 4
1.191     harris41 13187: 
                   13188: =item *
                   13189: 
1.243     albertel 13190: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13191: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13192: 
                   13193: =item *
                   13194: 
1.243     albertel 13195: hashref2str($hashref) : convert a hashref into a string complete with
                   13196: escaping and '=' and '&' separators, supports elements that are
                   13197: arrayrefs and hashrefs
1.191     harris41 13198: 
                   13199: =item *
                   13200: 
1.243     albertel 13201: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13202: with escaping and '&' separators, supports elements that are arrayrefs
                   13203: and hashrefs
1.191     harris41 13204: 
                   13205: =item *
                   13206: 
1.243     albertel 13207: str2hash($string) : convert string to hash using unescaping and
                   13208: splitting on '=' and '&', supports elements that are arrayrefs and
                   13209: hashrefs
1.191     harris41 13210: 
                   13211: =item *
                   13212: 
1.243     albertel 13213: str2array($string) : convert string to hash using unescaping and
                   13214: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13215: 
                   13216: =back
                   13217: 
                   13218: =head2 Logging Routines
                   13219: 
                   13220: 
                   13221: These routines allow one to make log messages in the lonnet.log and
                   13222: lonnet.perm logfiles.
1.191     harris41 13223: 
1.1119    foxr     13224: =over 4
                   13225: 
1.191     harris41 13226: =item *
                   13227: 
1.243     albertel 13228: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13229: 
                   13230: =item *
                   13231: 
1.243     albertel 13232: logthis() : append message to the normal lonnet.log file, it gets
                   13233: preiodically rolled over and deleted.
1.191     harris41 13234: 
                   13235: =item *
                   13236: 
1.243     albertel 13237: logperm() : append a permanent message to lonnet.perm.log, this log
                   13238: file never gets deleted by any automated portion of the system, only
                   13239: messages of critical importance should go in here.
                   13240: 
1.1119    foxr     13241: 
1.243     albertel 13242: =back
                   13243: 
                   13244: =head2 General File Helper Routines
                   13245: 
                   13246: =over 4
1.191     harris41 13247: 
                   13248: =item *
                   13249: 
1.481     raeburn  13250: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13251: (a) files in /uploaded
                   13252:   (i) If a local copy of the file exists - 
                   13253:       compares modification date of local copy with last-modified date for 
                   13254:       definitive version stored on home server for course. If local copy is 
                   13255:       stale, requests a new version from the home server and stores it. 
                   13256:       If the original has been removed from the home server, then local copy 
                   13257:       is unlinked.
                   13258:   (ii) If local copy does not exist -
                   13259:       requests the file from the home server and stores it. 
                   13260:   
                   13261:   If $caller is 'uploadrep':  
                   13262:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13263:     for request for files originally uploaded via DOCS. 
                   13264:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13265:   
                   13266:   Otherwise:
                   13267:      This indicates a call from the content generation phase of the request.
                   13268:      -  returns the entire contents of the file or -1.
                   13269:      
                   13270: (b) files in /res
                   13271:    - returns the entire contents of a file or -1; 
                   13272:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13273: 
1.712     albertel 13274: 
                   13275: =item *
                   13276: 
                   13277: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13278:                   reference
                   13279: 
                   13280: returns either a stat() list of data about the file or an empty list
                   13281: if the file doesn't exist or couldn't find out about it (connection
                   13282: problems or user unknown)
                   13283: 
1.191     harris41 13284: =item *
                   13285: 
1.243     albertel 13286: filelocation($dir,$file) : returns file system location of a file
                   13287: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13288: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13289: and a file of ../bob will become /a/bob)
1.191     harris41 13290: 
                   13291: =item *
                   13292: 
                   13293: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13294: filelocation except for hrefs
                   13295: 
                   13296: =item *
                   13297: 
                   13298: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13299: 
1.243     albertel 13300: =back
                   13301: 
1.608     albertel 13302: =head2 Usererfile file routines (/uploaded*)
                   13303: 
                   13304: =over 4
                   13305: 
                   13306: =item *
                   13307: 
                   13308: userfileupload(): main rotine for putting a file in a user or course's
                   13309:                   filespace, arguments are,
                   13310: 
1.620     albertel 13311:  formname - required - this is the name of the element in $env where the
1.608     albertel 13312:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13313:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13314:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13315:  context - if coursedoc, store the file in the course of the active role
                   13316:              of the current user; 
                   13317:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13318:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13319:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13320:          if undefined, it will be placed in "unknown"
                   13321: 
                   13322:  (This routine calls clean_filename() to remove any dangerous
                   13323:  characters from the filename, and then calls finuserfileupload() to
                   13324:  complete the transaction)
                   13325: 
                   13326:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13327:  and /adm/notfound.html if unsuccessful
                   13328: 
                   13329: =item *
                   13330: 
                   13331: clean_filename(): routine for cleaing a filename up for storage in
                   13332:                  userfile space, argument is:
                   13333: 
                   13334:  filename - proposed filename
                   13335: 
                   13336: returns: the new clean filename
                   13337: 
                   13338: =item *
                   13339: 
1.1090    raeburn  13340: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13341: userspace, probably shouldn't be called directly
                   13342: 
                   13343:   docuname: username or courseid of destination for the file
                   13344:   docudom: domain of user/course of destination for the file
                   13345:   formname: same as for userfileupload()
1.1090    raeburn  13346:   fname: filename (including subdirectories) for the file
                   13347:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13348:   allfiles: reference to hash used to store objects found by parser
                   13349:   codebase: reference to hash used for codebases of java objects found by parser
                   13350:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13351:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13352:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13353:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13354:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13355:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13356:   mimetype: reference to scalar to accommodate mime type determined
                   13357:             from File::MMagic if $parser = parse.
1.608     albertel 13358: 
                   13359:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13360:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13361:  was 'overwrite').
                   13362:  
1.608     albertel 13363: 
                   13364: =item *
                   13365: 
                   13366: renameuserfile(): renames an existing userfile to a new name
                   13367: 
                   13368:   Args:
                   13369:    docuname: username or courseid of destination for the file
                   13370:    docudom: domain of user/course of destination for the file
                   13371:    old: current file name (including any subdirs under userfiles)
                   13372:    new: desired file name (including any subdirs under userfiles)
                   13373: 
                   13374: =item *
                   13375: 
                   13376: mkdiruserfile(): creates a directory is a userfiles dir
                   13377: 
                   13378:   Args:
                   13379:    docuname: username or courseid of destination for the file
                   13380:    docudom: domain of user/course of destination for the file
                   13381:    dir: dir to create (including any subdirs under userfiles)
                   13382: 
                   13383: =item *
                   13384: 
                   13385: removeuserfile(): removes a file that exists in userfiles
                   13386: 
                   13387:   Args:
                   13388:    docuname: username or courseid of destination for the file
                   13389:    docudom: domain of user/course of destination for the file
                   13390:    fname: filname to delete (including any subdirs under userfiles)
                   13391: 
                   13392: =item *
                   13393: 
                   13394: removeuploadedurl(): convience function for removeuserfile()
                   13395: 
                   13396:   Args:
                   13397:    url:  a full /uploaded/... url to delete
                   13398: 
1.747     albertel 13399: =item * 
                   13400: 
                   13401: get_portfile_permissions():
                   13402:   Args:
                   13403:     domain: domain of user or course contain the portfolio files
                   13404:     user: name of user or num of course contain the portfolio files
                   13405:   Returns:
                   13406:     hashref of a dump of the proper file_permissions.db
                   13407:    
                   13408: 
                   13409: =item * 
                   13410: 
                   13411: get_access_controls():
                   13412: 
                   13413: Args:
                   13414:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13415:   group: (optional) the group you want the files associated with
                   13416:   file: (optional) the file you want access info on
                   13417: 
                   13418: Returns:
1.749     raeburn  13419:     a hash (keys are file names) of hashes containing
                   13420:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13421:         values are XML containing access control settings (see below) 
1.747     albertel 13422: 
                   13423: Internal notes:
                   13424: 
1.749     raeburn  13425:  access controls are stored in file_permissions.db as key=value pairs.
                   13426:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13427:         where scope -> public,guest,course,group,domains or users.
                   13428:               end -> UNIX time for end of access (0 -> no end date)
                   13429:               start -> UNIX time for start of access
                   13430: 
                   13431:     value -> XML description of access control
                   13432:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13433:             <start></start>
                   13434:             <end></end>
                   13435: 
                   13436:             <password></password>  for scope type = guest
                   13437: 
                   13438:             <domain></domain>     for scope type = course or group
                   13439:             <number></number>
                   13440:             <roles id="">
                   13441:              <role></role>
                   13442:              <access></access>
                   13443:              <section></section>
                   13444:              <group></group>
                   13445:             </roles>
                   13446: 
                   13447:             <dom></dom>         for scope type = domains
                   13448: 
                   13449:             <users>             for scope type = users
                   13450:              <user>
                   13451:               <uname></uname>
                   13452:               <udom></udom>
                   13453:              </user>
                   13454:             </users>
                   13455:            </scope> 
                   13456:               
                   13457:  Access data is also aggregated for each file in an additional key=value pair:
                   13458:  key -> path to file/file_name\0accesscontrol 
                   13459:  value -> reference to hash
                   13460:           hash contains key = value pairs
                   13461:           where key = uniqueID:scope_end_start
                   13462:                 value = UNIX time record was last updated
                   13463: 
                   13464:           Used to improve speed of look-ups of access controls for each file.  
                   13465:  
                   13466:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13467: 
1.1172.2.13  raeburn  13468: =item *
                   13469: 
1.749     raeburn  13470: modify_access_controls():
                   13471: 
                   13472: Modifies access controls for a portfolio file
                   13473: Args
                   13474: 1. file name
                   13475: 2. reference to hash of required changes,
                   13476: 3. domain
                   13477: 4. username
                   13478:   where domain,username are the domain of the portfolio owner 
                   13479:   (either a user or a course) 
                   13480: 
                   13481: Returns:
                   13482: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13483: 2. result of deletions ('ok' or 'error', with error message).
                   13484: 3. reference to hash of any new or updated access controls.
                   13485: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13486:    key = integer (inbound ID)
1.1172.2.13  raeburn  13487:    value = uniqueID
                   13488: 
                   13489: =item *
                   13490: 
                   13491: get_timebased_id():
                   13492: 
                   13493: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13494: course via the Course Editor (e.g., folders, composite pages,
                   13495: group bulletin boards).
                   13496: 
                   13497: Args: (first three required; six others optional)
                   13498: 
                   13499: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13500:    docssequence, or name of group
                   13501: 
                   13502: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13503:    e.g., num, boardids
                   13504: 
                   13505: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13506:    file will be named nohist_namespace.db
                   13507: 
                   13508: 4. cdom: domain of course; default is current course domain from %env
                   13509: 
                   13510: 5. cnum: course number; default is current course number from %env
                   13511: 
                   13512: 6. idtype: set to concat if an additional digit is to be appended to the
                   13513:    unix timestamp to form the suffix, if the plain timestamp is already
                   13514:    in use.  Default is to not do this, but simply increment the unix
                   13515:    timestamp by 1 until a unique key is obtained.
                   13516: 
                   13517: 7. who: holder of locking key; defaults to user:domain for user.
                   13518: 
                   13519: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13520:    retrying); default is 3.
                   13521: 
                   13522: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13523: 
                   13524: Returns:
                   13525: 
                   13526: 1. suffix obtained (numeric)
                   13527: 
                   13528: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13529: 
                   13530: 3. error: contains (localized) error message if an error occurred.
                   13531: 
1.747     albertel 13532: 
1.608     albertel 13533: =back
                   13534: 
1.243     albertel 13535: =head2 HTTP Helper Routines
                   13536: 
                   13537: =over 4
                   13538: 
1.191     harris41 13539: =item *
                   13540: 
                   13541: escape() : unpack non-word characters into CGI-compatible hex codes
                   13542: 
                   13543: =item *
                   13544: 
                   13545: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13546: 
1.243     albertel 13547: =back
                   13548: 
                   13549: =head1 PRIVATE SUBROUTINES
                   13550: 
                   13551: =head2 Underlying communication routines (Shouldn't call)
                   13552: 
                   13553: =over 4
                   13554: 
                   13555: =item *
                   13556: 
                   13557: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13558: 
                   13559: =item *
                   13560: 
                   13561: reply() : uses subreply to send a message to remote machine, logs all failures
                   13562: 
                   13563: =item *
                   13564: 
                   13565: critical() : passes a critical message to another server; if cannot
                   13566: get through then place message in connection buffer directory and
                   13567: returns con_delayed, if incapable of saving message, returns
                   13568: con_failed
                   13569: 
                   13570: =item *
                   13571: 
                   13572: reconlonc() : tries to reconnect lonc client processes.
                   13573: 
                   13574: =back
                   13575: 
                   13576: =head2 Resource Access Logging
                   13577: 
                   13578: =over 4
                   13579: 
                   13580: =item *
                   13581: 
                   13582: flushcourselogs() : flush (save) buffer logs and access logs
                   13583: 
                   13584: =item *
                   13585: 
                   13586: courselog($what) : save message for course in hash
                   13587: 
                   13588: =item *
                   13589: 
                   13590: courseacclog($what) : save message for course using &courselog().  Perform
                   13591: special processing for specific resource types (problems, exams, quizzes, etc).
                   13592: 
1.191     harris41 13593: =item *
                   13594: 
                   13595: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13596: as a PerlChildExitHandler
1.243     albertel 13597: 
                   13598: =back
                   13599: 
                   13600: =head2 Other
                   13601: 
                   13602: =over 4
                   13603: 
                   13604: =item *
                   13605: 
                   13606: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13607: 
                   13608: =back
                   13609: 
                   13610: =cut
1.877     foxr     13611: 

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