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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.18! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.17 2013/02/02 03:30:24 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') {
                   2007:         foreach my $item ('canuse_pdfforms') {
                   2008:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   2009:         }
                   2010:     }
1.1073    raeburn  2011:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2012:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2013:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2014:         }
                   2015:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2016:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2017:         }
                   2018:     }
1.943     raeburn  2019:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2020:                                   $cachetime);
                   2021:     return %domdefaults;
                   2022: }
                   2023: 
1.344     www      2024: # --------------------------------------------------- Assign a key to a student
                   2025: 
                   2026: sub assign_access_key {
1.364     www      2027: #
                   2028: # a valid key looks like uname:udom#comments
                   2029: # comments are being appended
                   2030: #
1.498     www      2031:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2032:     $kdom=
1.620     albertel 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2034:     $knum=
1.620     albertel 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2036:     $cdom=
1.620     albertel 2037:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2038:     $cnum=
1.620     albertel 2039:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2040:     $udom=$env{'user.name'} unless (defined($udom));
                   2041:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2042:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2043:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2044:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2045:                                                   # assigned to this person
                   2046:                                                   # - this should not happen,
1.345     www      2047:                                                   # unless something went wrong
                   2048:                                                   # the first time around
                   2049: # ready to assign
1.364     www      2050:         $logentry=$1.'; '.$logentry;
1.496     www      2051:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2052:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2053: # key now belongs to user
1.346     www      2054: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2055:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2056:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2057:                 return 'ok';
                   2058:             } else {
                   2059:                 return 
                   2060:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2061: 	    }
                   2062:         } else {
                   2063:             return 'error: Could not assign key, try again later.';
                   2064:         }
1.364     www      2065:     } elsif (!$existing{$ckey}) {
1.345     www      2066: # the key does not exist
                   2067: 	return 'error: The key does not exist';
                   2068:     } else {
                   2069: # the key is somebody else's
                   2070: 	return 'error: The key is already in use';
                   2071:     }
1.344     www      2072: }
                   2073: 
1.364     www      2074: # ------------------------------------------ put an additional comment on a key
                   2075: 
                   2076: sub comment_access_key {
                   2077: #
                   2078: # a valid key looks like uname:udom#comments
                   2079: # comments are being appended
                   2080: #
                   2081:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2082:     $cdom=
1.620     albertel 2083:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2084:     $cnum=
1.620     albertel 2085:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2086:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2087:     if ($existing{$ckey}) {
                   2088:         $existing{$ckey}.='; '.$logentry;
                   2089: # ready to assign
1.367     www      2090:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2091:                                                  $cdom,$cnum) eq 'ok') {
                   2092: 	    return 'ok';
                   2093:         } else {
                   2094: 	    return 'error: Count not store comment.';
                   2095:         }
                   2096:     } else {
                   2097: # the key does not exist
                   2098: 	return 'error: The key does not exist';
                   2099:     }
                   2100: }
                   2101: 
1.344     www      2102: # ------------------------------------------------------ Generate a set of keys
                   2103: 
                   2104: sub generate_access_keys {
1.364     www      2105:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2106:     $cdom=
1.620     albertel 2107:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2108:     $cnum=
1.620     albertel 2109:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2110:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2111:     unless (($cdom) && ($cnum)) { return 0; }
                   2112:     if ($number>10000) { return 0; }
                   2113:     sleep(2); # make sure don't get same seed twice
                   2114:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2115:     my $total=0;
                   2116:     for (my $i=1;$i<=$number;$i++) {
                   2117:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2118:                   sprintf("%lx",int(100000*rand)).'-'.
                   2119:                   sprintf("%lx",int(100000*rand));
                   2120:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2121:        $newkey=~s/0/h/g; # and also 0 and O
                   2122:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2123:        if ($existing{$newkey}) {
                   2124:            $i--;
                   2125:        } else {
1.364     www      2126: 	  if (&put('accesskeys',
                   2127:               { $newkey => '# generated '.localtime().
1.620     albertel 2128:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2129:                            '; '.$logentry },
                   2130: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2131:               $total++;
                   2132: 	  }
                   2133:        }
                   2134:     }
1.620     albertel 2135:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2136:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2137:     return $total;
                   2138: }
                   2139: 
                   2140: # ------------------------------------------------------- Validate an accesskey
                   2141: 
                   2142: sub validate_access_key {
                   2143:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2144:     $cdom=
1.620     albertel 2145:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2146:     $cnum=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2148:     $udom=$env{'user.domain'} unless (defined($udom));
                   2149:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2150:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2151:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2152: }
                   2153: 
                   2154: # ------------------------------------- Find the section of student in a course
1.652     albertel 2155: sub devalidate_getsection_cache {
                   2156:     my ($udom,$unam,$courseid)=@_;
                   2157:     my $hashid="$udom:$unam:$courseid";
                   2158:     &devalidate_cache_new('getsection',$hashid);
                   2159: }
1.298     matthew  2160: 
1.815     albertel 2161: sub courseid_to_courseurl {
                   2162:     my ($courseid) = @_;
                   2163:     #already url style courseid
                   2164:     return $courseid if ($courseid =~ m{^/});
                   2165: 
                   2166:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2167: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2168: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2169: 	return "/$cdom/$cnum";
                   2170:     }
                   2171: 
                   2172:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2173:     if (exists($courseinfo{'num'})) {
                   2174: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2175:     }
                   2176: 
                   2177:     return undef;
                   2178: }
                   2179: 
1.298     matthew  2180: sub getsection {
                   2181:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2182:     my $cachetime=1800;
1.551     albertel 2183: 
                   2184:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2185:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2186:     if (defined($cached)) { return $result; }
                   2187: 
1.298     matthew  2188:     my %Pending; 
                   2189:     my %Expired;
                   2190:     #
                   2191:     # Each role can either have not started yet (pending), be active, 
                   2192:     #    or have expired.
                   2193:     #
                   2194:     # If there is an active role, we are done.
                   2195:     #
                   2196:     # If there is more than one role which has not started yet, 
                   2197:     #     choose the one which will start sooner
                   2198:     # If there is one role which has not started yet, return it.
                   2199:     #
                   2200:     # If there is more than one expired role, choose the one which ended last.
                   2201:     # If there is a role which has expired, return it.
                   2202:     #
1.815     albertel 2203:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2204:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2205:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2206:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2207:         my $section=$1;
                   2208:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2209:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2210:         my $now=time;
1.548     albertel 2211:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2212:             $Expired{$end}=$section;
                   2213:             next;
                   2214:         }
1.548     albertel 2215:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2216:             $Pending{$start}=$section;
                   2217:             next;
                   2218:         }
1.599     albertel 2219:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2220:     }
                   2221:     #
                   2222:     # Presumedly there will be few matching roles from the above
                   2223:     # loop and the sorting time will be negligible.
                   2224:     if (scalar(keys(%Pending))) {
                   2225:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2226:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2227:     } 
                   2228:     if (scalar(keys(%Expired))) {
                   2229:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2230:         my $time = pop(@sorted);
1.599     albertel 2231:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2232:     }
1.599     albertel 2233:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2234: }
1.70      www      2235: 
1.599     albertel 2236: sub save_cache {
                   2237:     &purge_remembered();
1.722     albertel 2238:     #&Apache::loncommon::validate_page();
1.620     albertel 2239:     undef(%env);
1.780     albertel 2240:     undef($env_loaded);
1.599     albertel 2241: }
1.452     albertel 2242: 
1.599     albertel 2243: my $to_remember=-1;
                   2244: my %remembered;
                   2245: my %accessed;
                   2246: my $kicks=0;
                   2247: my $hits=0;
1.849     albertel 2248: sub make_key {
                   2249:     my ($name,$id) = @_;
1.872     albertel 2250:     if (length($id) > 65 
                   2251: 	&& length(&escape($id)) > 200) {
                   2252: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2253:     }
1.849     albertel 2254:     return &escape($name.':'.$id);
                   2255: }
                   2256: 
1.599     albertel 2257: sub devalidate_cache_new {
                   2258:     my ($name,$id,$debug) = @_;
                   2259:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2260:     $id=&make_key($name,$id);
1.599     albertel 2261:     $memcache->delete($id);
                   2262:     delete($remembered{$id});
                   2263:     delete($accessed{$id});
                   2264: }
                   2265: 
                   2266: sub is_cached_new {
                   2267:     my ($name,$id,$debug) = @_;
1.849     albertel 2268:     $id=&make_key($name,$id);
1.599     albertel 2269:     if (exists($remembered{$id})) {
1.1133    foxr     2270: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2271: 	$accessed{$id}=[&gettimeofday()];
                   2272: 	$hits++;
                   2273: 	return ($remembered{$id},1);
                   2274:     }
                   2275:     my $value = $memcache->get($id);
                   2276:     if (!(defined($value))) {
                   2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2278: 	return (undef,undef);
1.416     albertel 2279:     }
1.599     albertel 2280:     if ($value eq '__undef__') {
                   2281: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2282: 	$value=undef;
                   2283:     }
                   2284:     &make_room($id,$value,$debug);
                   2285:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2286:     return ($value,1);
                   2287: }
                   2288: 
                   2289: sub do_cache_new {
                   2290:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2291:     $id=&make_key($name,$id);
1.599     albertel 2292:     my $setvalue=$value;
                   2293:     if (!defined($setvalue)) {
                   2294: 	$setvalue='__undef__';
                   2295:     }
1.623     albertel 2296:     if (!defined($time) ) {
                   2297: 	$time=600;
                   2298:     }
1.599     albertel 2299:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2300:     my $result = $memcache->set($id,$setvalue,$time);
                   2301:     if (! $result) {
1.872     albertel 2302: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2303: 	$memcache->disconnect_all();
1.872     albertel 2304:     }
1.600     albertel 2305:     # need to make a copy of $value
1.919     albertel 2306:     &make_room($id,$value,$debug);
1.599     albertel 2307:     return $value;
                   2308: }
                   2309: 
                   2310: sub make_room {
                   2311:     my ($id,$value,$debug)=@_;
1.919     albertel 2312: 
                   2313:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2314:                                     : $value;
1.599     albertel 2315:     if ($to_remember<0) { return; }
                   2316:     $accessed{$id}=[&gettimeofday()];
                   2317:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2318:     my $to_kick;
                   2319:     my $max_time=0;
                   2320:     foreach my $other (keys(%accessed)) {
                   2321: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2322: 	    $to_kick=$other;
                   2323: 	    $max_time=&tv_interval($accessed{$other});
                   2324: 	}
                   2325:     }
                   2326:     delete($remembered{$to_kick});
                   2327:     delete($accessed{$to_kick});
                   2328:     $kicks++;
                   2329:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2330:     return;
                   2331: }
                   2332: 
1.599     albertel 2333: sub purge_remembered {
1.604     albertel 2334:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2335:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2336:     undef(%remembered);
                   2337:     undef(%accessed);
1.428     albertel 2338: }
1.70      www      2339: # ------------------------------------- Read an entry from a user's environment
                   2340: 
                   2341: sub userenvironment {
                   2342:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2343:     my $items;
                   2344:     foreach my $item (@what) {
                   2345:         $items.=&escape($item).'&';
                   2346:     }
                   2347:     $items=~s/\&$//;
1.70      www      2348:     my %returnhash=();
1.1009    raeburn  2349:     my $uhome = &homeserver($unam,$udom);
                   2350:     unless ($uhome eq 'no_host') {
                   2351:         my @answer=split(/\&/, 
                   2352:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2353:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2354:             return %returnhash;
                   2355:         }
1.1009    raeburn  2356:         my $i;
                   2357:         for ($i=0;$i<=$#what;$i++) {
                   2358: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2359:         }
1.70      www      2360:     }
                   2361:     return %returnhash;
1.1       albertel 2362: }
                   2363: 
1.617     albertel 2364: # ---------------------------------------------------------- Get a studentphoto
                   2365: sub studentphoto {
                   2366:     my ($udom,$unam,$ext) = @_;
                   2367:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2368:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2369:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2370:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2371:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2372:             } else {
                   2373:                 my ($result,$perm_reqd)=
1.707     albertel 2374: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2375:                 if ($result eq 'ok') {
                   2376:                     if (!($perm_reqd eq 'yes')) {
                   2377:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2378:                     }
                   2379:                 }
                   2380:             }
                   2381:         }
                   2382:     } else {
                   2383:         my ($result,$perm_reqd) = 
1.707     albertel 2384: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2385:         if ($result eq 'ok') {
                   2386:             if (!($perm_reqd eq 'yes')) {
                   2387:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2388:             }
                   2389:         }
                   2390:     }
                   2391:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2392: }
                   2393: 
                   2394: sub retrievestudentphoto {
                   2395:     my ($udom,$unam,$ext,$type) = @_;
                   2396:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2397:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2398:     if ($ret eq 'ok') {
                   2399:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2400:         if ($type eq 'thumbnail') {
                   2401:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2402:         }
                   2403:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2404:         return $tokenurl;
                   2405:     } else {
                   2406:         if ($type eq 'thumbnail') {
                   2407:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2408:         } else { 
                   2409:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2410:         }
1.617     albertel 2411:     }
                   2412: }
                   2413: 
1.263     www      2414: # -------------------------------------------------------------------- New chat
                   2415: 
                   2416: sub chatsend {
1.724     raeburn  2417:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2418:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2419:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2420:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2421:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2422: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2423: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2424: }
                   2425: 
                   2426: # ------------------------------------------ Find current version of a resource
                   2427: 
                   2428: sub getversion {
                   2429:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2430:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2431:     return &currentversion(&filelocation('',$fname));
                   2432: }
                   2433: 
                   2434: sub currentversion {
                   2435:     my $fname=shift;
                   2436:     my $author=$fname;
                   2437:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2438:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2439:     my $home=&homeserver($uname,$udom);
1.292     www      2440:     if ($home eq 'no_host') { 
                   2441:         return -1; 
                   2442:     }
1.1112    www      2443:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2444:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2445: 	return -1;
                   2446:     }
1.1112    www      2447:     return $answer;
1.263     www      2448: }
                   2449: 
1.1111    www      2450: #
                   2451: # Return special version number of resource if set by override, empty otherwise
                   2452: #
                   2453: sub usedversion {
                   2454:     my $fname=shift;
                   2455:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2456:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2457:     if ($urlversion) { return $urlversion; }
                   2458:     return '';
                   2459: }
                   2460: 
1.1       albertel 2461: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2462: 
1.1       albertel 2463: sub subscribe {
                   2464:     my $fname=shift;
1.761     raeburn  2465:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2466:     $fname=~s/[\n\r]//g;
1.1       albertel 2467:     my $author=$fname;
                   2468:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2469:     my ($udom,$uname)=split(/\//,$author);
                   2470:     my $home=homeserver($uname,$udom);
1.335     albertel 2471:     if ($home eq 'no_host') {
                   2472:         return 'not_found';
1.1       albertel 2473:     }
                   2474:     my $answer=reply("sub:$fname",$home);
1.64      www      2475:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2476: 	$answer.=' by '.$home;
                   2477:     }
1.1       albertel 2478:     return $answer;
                   2479: }
                   2480:     
1.8       www      2481: # -------------------------------------------------------------- Replicate file
                   2482: 
                   2483: sub repcopy {
                   2484:     my $filename=shift;
1.23      www      2485:     $filename=~s/\/+/\//g;
1.1142    raeburn  2486:     my $londocroot = $perlvar{'lonDocRoot'};
                   2487:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2488:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2489:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2490: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2491: 	return &repcopy_userfile($filename);
                   2492:     }
1.532     albertel 2493:     $filename=~s/[\n\r]//g;
1.8       www      2494:     my $transname="$filename.in.transfer";
1.828     www      2495: # FIXME: this should flock
1.607     raeburn  2496:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2497:     my $remoteurl=subscribe($filename);
1.64      www      2498:     if ($remoteurl =~ /^con_lost by/) {
                   2499: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2500:            return 'unavailable';
1.8       www      2501:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2502: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2503: 	   return 'not_found';
1.64      www      2504:     } elsif ($remoteurl =~ /^rejected by/) {
                   2505: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2506:            return 'forbidden';
1.20      www      2507:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2508:            return 'ok';
1.8       www      2509:     } else {
1.290     www      2510:         my $author=$filename;
                   2511:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2512:         my ($udom,$uname)=split(/\//,$author);
                   2513:         my $home=homeserver($uname,$udom);
                   2514:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2515:            my @parts=split(/\//,$filename);
                   2516:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2517:            if ($path ne "$londocroot/res") {
1.8       www      2518:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2519: 	       return 'bad_request';
1.8       www      2520:            }
                   2521:            my $count;
                   2522:            for ($count=5;$count<$#parts;$count++) {
                   2523:                $path.="/$parts[$count]";
                   2524:                if ((-e $path)!=1) {
                   2525: 		   mkdir($path,0777);
                   2526:                }
                   2527:            }
                   2528:            my $ua=new LWP::UserAgent;
                   2529:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2530:            my $response=$ua->request($request,$transname);
                   2531:            if ($response->is_error()) {
                   2532: 	       unlink($transname);
                   2533:                my $message=$response->status_line;
1.672     albertel 2534:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2535:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2536:                return 'unavailable';
1.8       www      2537:            } else {
1.16      www      2538: 	       if ($remoteurl!~/\.meta$/) {
                   2539:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2540:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2541:                   if ($mresponse->is_error()) {
                   2542: 		      unlink($filename.'.meta');
                   2543:                       &logthis(
1.672     albertel 2544:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2545:                   }
                   2546: 	       }
1.8       www      2547:                rename($transname,$filename);
1.607     raeburn  2548:                return 'ok';
1.8       www      2549:            }
1.290     www      2550:        }
1.8       www      2551:     }
1.330     www      2552: }
                   2553: 
                   2554: # ------------------------------------------------ Get server side include body
                   2555: sub ssi_body {
1.381     albertel 2556:     my ($filelink,%form)=@_;
1.606     matthew  2557:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2558:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2559:     }
1.953     www      2560:     my $output='';
                   2561:     my $response;
1.980     raeburn  2562:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2563:        ($output,$response)=&externalssi($filelink);
1.953     www      2564:     } else {
1.1004    droeschl 2565:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2566:        $filelink .= 'inhibitmenu=yes';
1.953     www      2567:        ($output,$response)=&ssi($filelink,%form);
                   2568:     }
1.778     albertel 2569:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2570:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2571:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2572:     if (wantarray) {
                   2573:         return ($output, $response);
                   2574:     } else {
                   2575:         return $output;
                   2576:     }
1.8       www      2577: }
                   2578: 
1.15      www      2579: # --------------------------------------------------------- Server Side Include
                   2580: 
1.782     albertel 2581: sub absolute_url {
                   2582:     my ($host_name) = @_;
                   2583:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2584:     if ($host_name eq '') {
                   2585: 	$host_name = $ENV{'SERVER_NAME'};
                   2586:     }
                   2587:     return $protocol.$host_name;
                   2588: }
                   2589: 
1.942     foxr     2590: #
                   2591: #   Server side include.
                   2592: # Parameters:
                   2593: #  fn     Possibly encrypted resource name/id.
                   2594: #  form   Hash that describes how the rendering should be done
                   2595: #         and other things.
1.944     foxr     2596: # Returns:
1.950     raeburn  2597: #   Scalar context: The content of the response.
                   2598: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2599: #     
1.15      www      2600: sub ssi {
                   2601: 
1.944     foxr     2602:     my ($fn,%form)=@_;
1.15      www      2603:     my $ua=new LWP::UserAgent;
1.23      www      2604:     my $request;
1.711     albertel 2605: 
                   2606:     $form{'no_update_last_known'}=1;
1.895     albertel 2607:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2608:     if (%form) {
1.782     albertel 2609:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2610:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2611:     } else {
1.782     albertel 2612:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2613:     }
                   2614: 
1.15      www      2615:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2616:     my $response= $ua->request($request);
1.944     foxr     2617:     if (wantarray) {
1.1172.2.3  raeburn  2618: 	return ($response->content, $response);
1.944     foxr     2619:     } else {
1.1172.2.3  raeburn  2620: 	return $response->content;
1.942     foxr     2621:     }
1.324     www      2622: }
                   2623: 
                   2624: sub externalssi {
                   2625:     my ($url)=@_;
                   2626:     my $ua=new LWP::UserAgent;
                   2627:     my $request=new HTTP::Request('GET',$url);
                   2628:     my $response=$ua->request($request);
1.954     raeburn  2629:     if (wantarray) {
                   2630:         return ($response->content, $response);
                   2631:     } else {
                   2632:         return $response->content;
                   2633:     }
1.15      www      2634: }
1.254     www      2635: 
1.492     albertel 2636: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2637: 
                   2638: sub allowuploaded {
                   2639:     my ($srcurl,$url)=@_;
                   2640:     $url=&clutter(&declutter($url));
                   2641:     my $dir=$url;
                   2642:     $dir=~s/\/[^\/]+$//;
                   2643:     my %httpref=();
                   2644:     my $httpurl=&hreflocation('',$url);
                   2645:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2646:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2647: }
1.477     raeburn  2648: 
1.1172.2.13  raeburn  2649: #
                   2650: # Determine if the current user should be able to edit a particular resource,
                   2651: # when viewing in course context.
                   2652: # (a) When viewing resource used to determine if "Edit" item is included in
                   2653: #     Functions.
                   2654: # (b) When displaying folder contents in course editor, used to determine if
                   2655: #     "Edit" link will be displayed alongside resource.
                   2656: #
                   2657: #  input: six args -- filename (decluttered), course number, course domain,
                   2658: #                   url, symb (if registered) and group (if this is a group
                   2659: #                   item -- e.g., bulletin board, group page etc.).
                   2660: #  output: array of five scalars --
                   2661: #          $cfile -- url for file editing if editable on current server
                   2662: #          $home -- homeserver of resource (i.e., for author if published,
                   2663: #                                           or course if uploaded.).
                   2664: #          $switchserver --  1 if server switch will be needed.
                   2665: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2666: #          $forceview -- 1 if icon/link should be to go to view mode
                   2667: #
                   2668: 
                   2669: sub can_edit_resource {
                   2670:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2671:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2672: #
                   2673: # For aboutme pages user can only edit his/her own.
                   2674: #
                   2675:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2676:         my ($sdom,$sname) = ($1,$2);
                   2677:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2678:             $home = $env{'user.home'};
                   2679:             $cfile = $resurl;
                   2680:             if ($env{'form.forceedit'}) {
                   2681:                 $forceview = 1;
                   2682:             } else {
                   2683:                 $forceedit = 1;
                   2684:             }
                   2685:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2686:         } else {
                   2687:             return;
                   2688:         }
                   2689:     }
                   2690: 
                   2691:     if ($env{'request.course.id'}) {
                   2692:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2693:         if ($group ne '') {
                   2694: # if this is a group homepage or group bulletin board, check group privs
                   2695:             my $allowed = 0;
                   2696:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2697:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2698:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2699:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2700:                     $allowed = 1;
                   2701:                 }
                   2702:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2703:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2704:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2705:                     $allowed = 1;
                   2706:                 }
                   2707:             }
                   2708:             if ($allowed) {
                   2709:                 $home=&homeserver($cnum,$cdom);
                   2710:                 if ($env{'form.forceedit'}) {
                   2711:                     $forceview = 1;
                   2712:                 } else {
                   2713:                     $forceedit = 1;
                   2714:                 }
                   2715:                 $cfile = $resurl;
                   2716:             } else {
                   2717:                 return;
                   2718:             }
                   2719:         } else {
1.1172.2.15  raeburn  2720:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2721:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2722:                     return;
                   2723:                 }
                   2724:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2725: #
                   2726: # No edit allowed where CC has switched to student role.
                   2727: #
                   2728:                 return;
                   2729:             }
                   2730:         }
                   2731:     }
                   2732: 
                   2733:     if ($file ne '') {
                   2734:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2735:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2736:                 $uploaded = 1;
                   2737:                 $incourse = 1;
                   2738:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2739:                     $cfile = &hreflocation('',$file);
                   2740:                     if ($env{'form.forceedit'}) {
                   2741:                         $forceview = 1;
                   2742:                     } else {
                   2743:                         $forceedit = 1;
                   2744:                     }
                   2745:                 }
                   2746:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2747:                 $incourse = 1;
                   2748:                 if ($env{'form.forceedit'}) {
                   2749:                     $forceview = 1;
                   2750:                 } else {
                   2751:                     $forceedit = 1;
                   2752:                 }
                   2753:                 $cfile = $resurl;
                   2754:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2755:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2756:                     $incourse = 1;
                   2757:                     if ($env{'form.forceedit'}) {
                   2758:                         $forceview = 1;
                   2759:                     } else {
                   2760:                         $forceedit = 1;
                   2761:                     }
                   2762:                     $cfile = $resurl;
                   2763:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2764:                     $incourse = 1;
                   2765:                     $cfile = $resurl.'/smpedit';
                   2766:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2767:                     $incourse = 1;
                   2768:                     if ($env{'form.forceedit'}) {
                   2769:                         $forceview = 1;
                   2770:                     } else {
                   2771:                         $forceedit = 1;
                   2772:                     }
                   2773:                     $cfile = $resurl;
1.1172.2.15  raeburn  2774:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2775:                     $incourse = 1;
                   2776:                     if ($env{'form.forceedit'}) {
                   2777:                         $forceview = 1;
                   2778:                     } else {
                   2779:                         $forceedit = 1;
                   2780:                     }
                   2781:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2782:                 }
                   2783:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2784:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2785:                 if (&is_on_map($template)) {
                   2786:                     $incourse = 1;
                   2787:                     $forceview = 1;
                   2788:                     $cfile = $template;
                   2789:                 }
                   2790:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2791:                     $incourse = 1;
                   2792:                     if ($env{'form.forceedit'}) {
                   2793:                         $forceview = 1;
                   2794:                     } else {
                   2795:                         $forceedit = 1;
                   2796:                     }
                   2797:                     $cfile = $resurl;
                   2798:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2799:                 $incourse = 1;
                   2800:                 $forceview = 1;
                   2801:                 if ($symb) {
                   2802:                     my ($map,$id,$res)=&decode_symb($symb);
                   2803:                     $env{'request.symb'} = $symb;
                   2804:                     $cfile = &clutter($res);
                   2805:                 } else {
                   2806:                     $cfile = $env{'form.suppurl'};
                   2807:                     $cfile =~ s{^http://}{};
                   2808:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2809:                 }
                   2810:             }
                   2811:         }
                   2812:         if ($uploaded || $incourse) {
                   2813:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2814:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2815:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2816:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2817:             # Check that the user has permission to edit this resource
                   2818:             my $setpriv = 1;
                   2819:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2820:             if (defined($cfudom)) {
                   2821:                 $home=&homeserver($cfuname,$cfudom);
                   2822:                 $cfile=$file;
                   2823:             }
                   2824:         }
                   2825:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2826:             (($home ne '') && ($home ne 'no_host'))) {
                   2827:             my @ids=&current_machine_ids();
                   2828:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2829:                 $switchserver=1;
                   2830:             }
                   2831:         }
                   2832:     }
                   2833:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2834: }
                   2835: 
                   2836: sub is_course_upload {
                   2837:     my ($file,$cnum,$cdom) = @_;
                   2838:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2839:     $uploadpath =~ s{^\/}{};
                   2840:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2841:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2842:         return 1;
                   2843:     }
                   2844:     return;
                   2845: }
                   2846: 
                   2847: sub in_course {
                   2848:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2849:     if ($hideprivileged) {
                   2850:         my $skipuser;
                   2851:         if (&privileged($uname,$udom)) {
                   2852:             $skipuser = 1;
                   2853:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2854:             if ($coursehash{'nothideprivileged'}) {
                   2855:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2856:                     my $user;
                   2857:                     if ($item =~ /:/) {
                   2858:                         $user = $item;
                   2859:                     } else {
                   2860:                         $user = join(':',split(/[\@]/,$item));
                   2861:                     }
                   2862:                     if ($user eq $uname.':'.$udom) {
                   2863:                         undef($skipuser);
                   2864:                         last;
                   2865:                     }
                   2866:                 }
                   2867:             }
                   2868:             if ($skipuser) {
                   2869:                 return 0;
                   2870:             }
                   2871:         }
                   2872:     }
                   2873:     $type ||= 'any';
                   2874:     if (!defined($cdom) || !defined($cnum)) {
                   2875:         my $cid  = $env{'request.course.id'};
                   2876:         $cdom = $env{'course.'.$cid.'.domain'};
                   2877:         $cnum = $env{'course.'.$cid.'.num'};
                   2878:     }
                   2879:     my $typesref;
                   2880:     if (($type eq 'any') || ($type eq 'all')) {
                   2881:         $typesref = ['active','previous','future'];
                   2882:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2883:         $typesref = [$type];
                   2884:     }
                   2885:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2886:                               $typesref,undef,[$cdom]);
                   2887:     my ($tmp) = keys(%roles);
                   2888:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2889:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2890:     if (@course_roles > 0) {
                   2891:         return 1;
                   2892:     }
                   2893:     return 0;
                   2894: }
                   2895: 
1.478     albertel 2896: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2897: # input: action, courseID, current domain, intended
1.637     raeburn  2898: #        path to file, source of file, instruction to parse file for objects,
                   2899: #        ref to hash for embedded objects,
                   2900: #        ref to hash for codebase of java objects.
1.1095    raeburn  2901: #        reference to scalar to accommodate mime type determined
                   2902: #          from File::MMagic if $parser = parse.
1.637     raeburn  2903: #
1.485     raeburn  2904: # output: url to file (if action was uploaddoc), 
                   2905: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2906: #
1.478     albertel 2907: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2908: # course.
1.477     raeburn  2909: #
1.478     albertel 2910: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2911: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2912: #          course's home server.
1.477     raeburn  2913: #
1.478     albertel 2914: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2915: #          be copied from $source (current location) to 
                   2916: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2917: #         and will then be copied to
                   2918: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2919: #         course's home server.
1.485     raeburn  2920: #
1.481     raeburn  2921: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2922: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2923: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2924: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2925: #         in course's home server.
1.637     raeburn  2926: #
1.477     raeburn  2927: 
                   2928: sub process_coursefile {
1.1095    raeburn  2929:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2930:         $mimetype)=@_;
1.477     raeburn  2931:     my $fetchresult;
1.638     albertel 2932:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2933:     if ($action eq 'propagate') {
1.638     albertel 2934:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2935: 			     $home);
1.481     raeburn  2936:     } else {
1.477     raeburn  2937:         my $fpath = '';
                   2938:         my $fname = $file;
1.478     albertel 2939:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2940:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2941:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2942:         if ($action eq 'copy') {
                   2943:             if ($source eq '') {
                   2944:                 $fetchresult = 'no source file';
                   2945:                 return $fetchresult;
                   2946:             } else {
                   2947:                 my $destination = $filepath.'/'.$fname;
                   2948:                 rename($source,$destination);
                   2949:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2950:                                  $home);
1.481     raeburn  2951:             }
                   2952:         } elsif ($action eq 'uploaddoc') {
                   2953:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2954:             print $fh $env{'form.'.$source};
1.481     raeburn  2955:             close($fh);
1.637     raeburn  2956:             if ($parser eq 'parse') {
1.1024    raeburn  2957:                 my $mm = new File::MMagic;
1.1095    raeburn  2958:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2959:                 if ($type eq 'text/html') {
1.1024    raeburn  2960:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2961:                     unless ($parse_result eq 'ok') {
                   2962:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2963:                     }
1.637     raeburn  2964:                 }
1.1095    raeburn  2965:                 if (ref($mimetype)) {
                   2966:                     $$mimetype = $type;
                   2967:                 } 
1.637     raeburn  2968:             }
1.477     raeburn  2969:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2970:                                  $home);
1.481     raeburn  2971:             if ($fetchresult eq 'ok') {
                   2972:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2973:             } else {
                   2974:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2975:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2976:                 return '/adm/notfound.html';
                   2977:             }
1.477     raeburn  2978:         }
                   2979:     }
1.485     raeburn  2980:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2981:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2982:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2983:     }
                   2984:     return $fetchresult;
                   2985: }
                   2986: 
1.637     raeburn  2987: sub build_filepath {
                   2988:     my ($fpath) = @_;
                   2989:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2990:     unless ($fpath eq '') {
                   2991:         my @parts=split('/',$fpath);
                   2992:         foreach my $part (@parts) {
                   2993:             $filepath.= '/'.$part;
                   2994:             if ((-e $filepath)!=1) {
                   2995:                 mkdir($filepath,0777);
                   2996:             }
                   2997:         }
                   2998:     }
                   2999:     return $filepath;
                   3000: }
                   3001: 
                   3002: sub store_edited_file {
1.638     albertel 3003:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3004:     my $file = $primary_url;
                   3005:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3006:     my $fpath = '';
                   3007:     my $fname = $file;
                   3008:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3009:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3010:     my $filepath = &build_filepath($fpath);
                   3011:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3012:     print $fh $content;
                   3013:     close($fh);
1.638     albertel 3014:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3015:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3016: 			  $home);
1.637     raeburn  3017:     if ($$fetchresult eq 'ok') {
                   3018:         return '/uploaded/'.$fpath.'/'.$fname;
                   3019:     } else {
1.638     albertel 3020:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3021: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3022:         return '/adm/notfound.html';
                   3023:     }
                   3024: }
                   3025: 
1.531     albertel 3026: sub clean_filename {
1.831     albertel 3027:     my ($fname,$args)=@_;
1.315     www      3028: # Replace Windows backslashes by forward slashes
1.257     www      3029:     $fname=~s/\\/\//g;
1.831     albertel 3030:     if (!$args->{'keep_path'}) {
                   3031:         # Get rid of everything but the actual filename
                   3032: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3033:     }
1.315     www      3034: # Replace spaces by underscores
                   3035:     $fname=~s/\s+/\_/g;
                   3036: # Replace all other weird characters by nothing
1.831     albertel 3037:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3038: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3039: # numbers
                   3040:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3041:     return $fname;
                   3042: }
1.1051    raeburn  3043: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3044: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3045: # image with the same aspect ratio as the original, but with dimensions which do 
                   3046: # not exceed $resizewidth and $resizeheight.
                   3047:  
1.984     neumanie 3048: sub resizeImage {
1.1051    raeburn  3049:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3050:     my $ima = Image::Magick->new;
                   3051:     my $resized;
                   3052:     if (-e $img_path) {
                   3053:         $ima->Read($img_path);
                   3054:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3055:             my $width = $ima->Get('width');
                   3056:             my $height = $ima->Get('height');
                   3057:             if ($width > $resizewidth) {
                   3058: 	        my $factor = $width/$resizewidth;
                   3059:                 my $newheight = $height/$factor;
                   3060:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3061:                 $resized = 1;
                   3062:             }
                   3063:         }
                   3064:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3065:             my $width = $ima->Get('width');
                   3066:             my $height = $ima->Get('height');
                   3067:             if ($height > $resizeheight) {
                   3068:                 my $factor = $height/$resizeheight;
                   3069:                 my $newwidth = $width/$factor;
                   3070:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3071:                 $resized = 1;
                   3072:             }
                   3073:         }
                   3074:         if ($resized) {
                   3075:             $ima->Write($img_path);
                   3076:         }
                   3077:     }
                   3078:     return;
1.977     amueller 3079: }
                   3080: 
1.608     albertel 3081: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3082: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3083: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3084: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3085: #                                    canceloverwrite, or ''. 
                   3086: #                   if 'coursedoc': upload to the current course
                   3087: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3088: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3089: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3090: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3091: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3092: #        $allfiles - reference to hash for embedded objects
                   3093: #        $codebase - reference to hash for codebase of java objects
                   3094: #        $desuname - username for permanent storage of uploaded file
                   3095: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3096: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3097: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3098: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3099: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3100: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3101: #                    from File::MMagic.
1.858     raeburn  3102: # 
1.686     albertel 3103: # output: url of file in userspace, or error: <message> 
                   3104: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3105: 
1.531     albertel 3106: sub userfileupload {
1.1090    raeburn  3107:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3108:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3109:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3110:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3111:     $fname=&clean_filename($fname);
1.1090    raeburn  3112:     # See if there is anything left
1.257     www      3113:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3114:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3115:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3116:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3117:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3118:         my $now = time;
1.1090    raeburn  3119:         my $filepath;
1.1095    raeburn  3120:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3121:              $filepath = 'tmp/helprequests/'.$now;
                   3122:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3123:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3124:                          '_'.$env{'user.domain'}.'/pending';
                   3125:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3126:             my ($docuname,$docudom);
                   3127:             if ($destudom) {
                   3128:                 $docudom = $destudom;
                   3129:             } else {
                   3130:                 $docudom = $env{'user.domain'};
                   3131:             }
                   3132:             if ($destuname) {
                   3133:                 $docuname = $destuname;
                   3134:             } else {
                   3135:                 $docuname = $env{'user.name'};
                   3136:             }
                   3137:             if (exists($env{'form.group'})) {
                   3138:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3139:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3140:             }
                   3141:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3142:             if ($context eq 'canceloverwrite') {
                   3143:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3144:                 if (-e  $tempfile) {
                   3145:                     my @info = stat($tempfile);
                   3146:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3147:                         unlink($tempfile);
                   3148:                     }
                   3149:                 }
                   3150:                 return;
1.523     raeburn  3151:             }
                   3152:         }
1.1090    raeburn  3153:         # Create the directory if not present
1.741     raeburn  3154:         my @parts=split(/\//,$filepath);
                   3155:         my $fullpath = $perlvar{'lonDaemons'};
                   3156:         for (my $i=0;$i<@parts;$i++) {
                   3157:             $fullpath .= '/'.$parts[$i];
                   3158:             if ((-e $fullpath)!=1) {
                   3159:                 mkdir($fullpath,0777);
                   3160:             }
                   3161:         }
                   3162:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3163:         print $fh $env{'form.'.$formname};
                   3164:         close($fh);
1.1090    raeburn  3165:         if ($context eq 'existingfile') {
                   3166:             my @info = stat($fullpath.'/'.$fname);
                   3167:             return ($fullpath.'/'.$fname,$info[9]);
                   3168:         } else {
                   3169:             return $fullpath.'/'.$fname;
                   3170:         }
1.523     raeburn  3171:     }
1.995     raeburn  3172:     if ($subdir eq 'scantron') {
                   3173:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3174:     } else {
1.995     raeburn  3175:         $fname="$subdir/$fname";
                   3176:     }
1.1090    raeburn  3177:     if ($context eq 'coursedoc') {
1.638     albertel 3178: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3179: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3180:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3181:             return &finishuserfileupload($docuname,$docudom,
                   3182: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3183: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3184:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3185:         } else {
1.620     albertel 3186:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3187:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3188: 				       $fname,$formname,$parser,
1.1095    raeburn  3189: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3190:         }
1.719     banghart 3191:     } elsif (defined($destuname)) {
                   3192:         my $docuname=$destuname;
                   3193:         my $docudom=$destudom;
1.860     raeburn  3194: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3195: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3196:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3197:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3198:     } else {
1.638     albertel 3199:         my $docuname=$env{'user.name'};
                   3200:         my $docudom=$env{'user.domain'};
1.714     raeburn  3201:         if (exists($env{'form.group'})) {
                   3202:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3203:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3204:         }
1.860     raeburn  3205: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3206: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3207:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3208:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3209:     }
1.271     www      3210: }
                   3211: 
                   3212: sub finishuserfileupload {
1.860     raeburn  3213:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3214:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3215:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3216:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3217:   
1.860     raeburn  3218:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3219:     $file=$fname;
                   3220:     if ($fname=~m|/|) {
                   3221:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3222: 	$path.=$fnamepath.'/';
                   3223:     }
1.259     www      3224:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3225:     my $count;
                   3226:     for ($count=4;$count<=$#parts;$count++) {
                   3227:         $filepath.="/$parts[$count]";
                   3228:         if ((-e $filepath)!=1) {
                   3229: 	    mkdir($filepath,0777);
                   3230:         }
                   3231:     }
1.984     neumanie 3232: 
1.258     www      3233: # Save the file
                   3234:     {
1.701     albertel 3235: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3236: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3237: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3238: 	    return '/adm/notfound.html';
                   3239: 	}
1.1090    raeburn  3240:         if ($context eq 'overwrite') {
1.1117    foxr     3241:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3242:             my $target = $filepath.'/'.$file;
                   3243:             if (-e $source) {
                   3244:                 my @info = stat($source);
                   3245:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3246:                     unless (&File::Copy::move($source,$target)) {
                   3247:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3248:                         return "Moving from $source failed";
                   3249:                     }
                   3250:                 } else {
                   3251:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3252:                 }
                   3253:             } else {
                   3254:                 return "Temporary file: $source missing";
                   3255:             }
                   3256:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3257: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3258: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3259: 	    return '/adm/notfound.html';
                   3260: 	}
1.570     albertel 3261: 	close(FH);
1.1051    raeburn  3262:         if ($resizewidth && $resizeheight) {
                   3263:             my $mm = new File::MMagic;
                   3264:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3265:             if ($mime_type =~ m{^image/}) {
                   3266: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3267:             }  
1.977     amueller 3268: 	}
1.258     www      3269:     }
1.1152    raeburn  3270:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3271:         if (ref($mimetype)) {
                   3272:             if ($$mimetype eq '') {
                   3273:                 my $mm = new File::MMagic;
                   3274:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3275:                 $$mimetype = $type;
                   3276:             }
                   3277:         }
                   3278:     }
1.637     raeburn  3279:     if ($parser eq 'parse') {
1.1152    raeburn  3280:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3281:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3282:                                                        $allfiles,$codebase);
                   3283:             unless ($parse_result eq 'ok') {
                   3284:                 &logthis('Failed to parse '.$filepath.$file.
                   3285: 	   	         ' for embedded media: '.$parse_result); 
                   3286:             }
1.637     raeburn  3287:         }
                   3288:     }
1.860     raeburn  3289:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3290:         my $input = $filepath.'/'.$file;
                   3291:         my $output = $filepath.'/'.'tn-'.$file;
                   3292:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3293:         system("convert -sample $thumbsize $input $output");
                   3294:         if (-e $filepath.'/'.'tn-'.$file) {
                   3295:             $fetchthumb  = 1; 
                   3296:         }
                   3297:     }
1.858     raeburn  3298:  
1.259     www      3299: # Notify homeserver to grep it
                   3300: #
1.984     neumanie 3301:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3302:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3303:     if ($fetchresult eq 'ok') {
1.860     raeburn  3304:         if ($fetchthumb) {
                   3305:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3306:             if ($thumbresult ne 'ok') {
                   3307:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3308:                          $docuhome.': '.$thumbresult);
                   3309:             }
                   3310:         }
1.259     www      3311: #
1.258     www      3312: # Return the URL to it
1.494     albertel 3313:         return '/uploaded/'.$path.$file;
1.263     www      3314:     } else {
1.494     albertel 3315:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3316: 		 ': '.$fetchresult);
1.263     www      3317:         return '/adm/notfound.html';
1.858     raeburn  3318:     }
1.493     albertel 3319: }
                   3320: 
1.637     raeburn  3321: sub extract_embedded_items {
1.961     raeburn  3322:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3323:     my @state = ();
1.1164    raeburn  3324:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3325:     my %javafiles = (
                   3326:                       codebase => '',
                   3327:                       code => '',
                   3328:                       archive => ''
                   3329:                     );
                   3330:     my %mediafiles = (
                   3331:                       src => '',
                   3332:                       movie => '',
                   3333:                      );
1.648     raeburn  3334:     my $p;
                   3335:     if ($content) {
                   3336:         $p = HTML::LCParser->new($content);
                   3337:     } else {
1.961     raeburn  3338:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3339:     }
1.641     albertel 3340:     while (my $t=$p->get_token()) {
1.640     albertel 3341: 	if ($t->[0] eq 'S') {
                   3342: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3343: 	    push(@state, $tagname);
1.648     raeburn  3344:             if (lc($tagname) eq 'allow') {
                   3345:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3346:             }
1.640     albertel 3347: 	    if (lc($tagname) eq 'img') {
                   3348: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3349: 	    }
1.886     albertel 3350: 	    if (lc($tagname) eq 'a') {
                   3351: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3352: 	    }
1.645     raeburn  3353:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3354:                 my $src;
1.645     raeburn  3355:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3356:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3357:                 } else {
1.1164    raeburn  3358:                     if ($attr->{'src'} ne '') {
                   3359:                         $src = $attr->{'src'};
                   3360:                         &add_filetype($allfiles,$src,'src');
                   3361:                     }
                   3362:                 }
                   3363:                 my $text = $p->get_trimmed_text();
                   3364:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3365:                     my @swfargs = split(/,/,$1);
                   3366:                     foreach my $item (@swfargs) {
                   3367:                         $item =~ s/["']//g;
                   3368:                         $item =~ s/^\s+//;
                   3369:                         $item =~ s/\s+$//;
                   3370:                     }
                   3371:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3372:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3373:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3374:                         } else {
                   3375:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3376:                         }
                   3377:                     }
1.645     raeburn  3378:                 }
                   3379:             }
                   3380:             if (lc($tagname) eq 'link') {
                   3381:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3382:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3383:                 }
                   3384:             }
1.640     albertel 3385: 	    if (lc($tagname) eq 'object' ||
                   3386: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3387: 		foreach my $item (keys(%javafiles)) {
                   3388: 		    $javafiles{$item} = '';
                   3389: 		}
1.1164    raeburn  3390:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3391:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3392:                 }
1.640     albertel 3393: 	    }
                   3394: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3395: 		my $name = lc($attr->{'name'});
                   3396: 		foreach my $item (keys(%javafiles)) {
                   3397: 		    if ($name eq $item) {
                   3398: 			$javafiles{$item} = $attr->{'value'};
                   3399: 			last;
                   3400: 		    }
                   3401: 		}
1.1164    raeburn  3402:                 my $pathfrom;
1.640     albertel 3403: 		foreach my $item (keys(%mediafiles)) {
                   3404: 		    if ($name eq $item) {
1.1164    raeburn  3405:                         $pathfrom = $attr->{'value'};
                   3406:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3407: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3408: 			last;
                   3409: 		    }
                   3410: 		}
1.1164    raeburn  3411:                 if ($name eq 'flashvars') {
                   3412:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3413:                 }
                   3414:                 if ($pathfrom ne '') {
                   3415:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3416:                                          $pathfrom);
                   3417:                 }
1.640     albertel 3418: 	    }
                   3419: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3420: 		foreach my $item (keys(%javafiles)) {
                   3421: 		    if ($attr->{$item}) {
                   3422: 			$javafiles{$item} = $attr->{$item};
                   3423: 			last;
                   3424: 		    }
                   3425: 		}
                   3426: 		foreach my $item (keys(%mediafiles)) {
                   3427: 		    if ($attr->{$item}) {
                   3428: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3429: 			last;
                   3430: 		    }
                   3431: 		}
1.1164    raeburn  3432:                 if (lc($tagname) eq 'embed') {
                   3433:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3434:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3435:                                              $attr->{'src'});
                   3436:                     }
                   3437:                 }
1.640     albertel 3438: 	    }
1.1164    raeburn  3439:             if ($t->[4] =~ m{/>$}) {
                   3440:                 pop(@state);  
                   3441:             }
1.640     albertel 3442: 	} elsif ($t->[0] eq 'E') {
                   3443: 	    my ($tagname) = ($t->[1]);
                   3444: 	    if ($javafiles{'codebase'} ne '') {
                   3445: 		$javafiles{'codebase'} .= '/';
                   3446: 	    }  
                   3447: 	    if (lc($tagname) eq 'applet' ||
                   3448: 		lc($tagname) eq 'object' ||
                   3449: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3450: 		) {
                   3451: 		foreach my $item (keys(%javafiles)) {
                   3452: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3453: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3454: 			&add_filetype($allfiles,$file,$item);
                   3455: 		    }
                   3456: 		}
                   3457: 	    } 
                   3458: 	    pop @state;
                   3459: 	}
                   3460:     }
1.1164    raeburn  3461:     foreach my $id (sort(keys(%flashvars))) {
                   3462:         if ($shockwave{$id} ne '') {
                   3463:             my @pairs = split(/\&/,$flashvars{$id});
                   3464:             foreach my $pair (@pairs) {
                   3465:                 my ($key,$value) = split(/\=/,$pair);
                   3466:                 if ($key eq 'thumb') {
                   3467:                     &add_filetype($allfiles,$value,$key);
                   3468:                 } elsif ($key eq 'content') {
                   3469:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3470:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3471:                     if ($ext ne '') {
                   3472:                         &add_filetype($allfiles,$path.$value,$ext);
                   3473:                     }
                   3474:                 }
                   3475:             }
                   3476:         }
                   3477:     }
1.637     raeburn  3478:     return 'ok';
                   3479: }
                   3480: 
1.639     albertel 3481: sub add_filetype {
                   3482:     my ($allfiles,$file,$type)=@_;
                   3483:     if (exists($allfiles->{$file})) {
                   3484: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3485: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3486: 	}
                   3487:     } else {
                   3488: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3489:     }
                   3490: }
                   3491: 
1.1164    raeburn  3492: sub embedded_dependency {
                   3493:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3494:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3495:         if (($identifier ne '') &&
                   3496:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3497:             ($pathfrom ne '')) {
                   3498:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3499:             foreach my $dep (@{$related->{$identifier}}) {
                   3500:                 &add_filetype($allfiles,$path.$dep,'object');
                   3501:             }
                   3502:         }
                   3503:     }
                   3504:     return;
                   3505: }
                   3506: 
1.493     albertel 3507: sub removeuploadedurl {
1.984     neumanie 3508:     my ($url)=@_;	
                   3509:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3510:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3511: }
                   3512: 
                   3513: sub removeuserfile {
                   3514:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3515:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3516:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3517:     if ($result eq 'ok') {	
1.798     raeburn  3518:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3519:             my $metafile = $fname.'.meta';
                   3520:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3521: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3522:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3523:             my $sqlresult = 
1.823     albertel 3524:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3525:                                         'portfolio_metadata',$group,
                   3526:                                         'delete');
1.798     raeburn  3527:         }
                   3528:     }
                   3529:     return $result;
1.257     www      3530: }
1.15      www      3531: 
1.530     albertel 3532: sub mkdiruserfile {
                   3533:     my ($docuname,$docudom,$dir)=@_;
                   3534:     my $home=&homeserver($docuname,$docudom);
                   3535:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3536: }
                   3537: 
1.531     albertel 3538: sub renameuserfile {
                   3539:     my ($docuname,$docudom,$old,$new)=@_;
                   3540:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3541:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3542:                         &escape("$old").':'.&escape("$new"),$home);
                   3543:     if ($result eq 'ok') {
                   3544:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3545:             my $oldmeta = $old.'.meta';
                   3546:             my $newmeta = $new.'.meta';
                   3547:             my $metaresult = 
                   3548:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3549: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3550:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3551:             my $sqlresult = 
1.823     albertel 3552:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3553:                                         'portfolio_metadata',$group,
                   3554:                                         'delete');
1.798     raeburn  3555:         }
                   3556:     }
                   3557:     return $result;
1.531     albertel 3558: }
                   3559: 
1.14      www      3560: # ------------------------------------------------------------------------- Log
                   3561: 
                   3562: sub log {
                   3563:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3564:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3565: }
                   3566: 
                   3567: # ------------------------------------------------------------------ Course Log
1.352     www      3568: #
                   3569: # This routine flushes several buffers of non-mission-critical nature
                   3570: #
1.157     www      3571: 
                   3572: sub flushcourselogs {
1.352     www      3573:     &logthis('Flushing log buffers');
                   3574: #
                   3575: # course logs
                   3576: # This is a log of all transactions in a course, which can be used
                   3577: # for data mining purposes
                   3578: #
                   3579: # It also collects the courseid database, which lists last transaction
                   3580: # times and course titles for all courseids
                   3581: #
                   3582:     my %courseidbuffer=();
1.921     raeburn  3583:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3584:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3585: 		          &escape($courselogs{$crsid}),
                   3586: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3587: 	    delete $courselogs{$crsid};
                   3588:         } else {
                   3589:             &logthis('Failed to flush log buffer for '.$crsid);
                   3590:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3591:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3592:                         " exceeded maximum size, deleting.</font>");
                   3593:                delete $courselogs{$crsid};
                   3594:             }
1.352     www      3595:         }
1.920     raeburn  3596:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3597:             'description' => $coursedescrbuf{$crsid},
                   3598:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3599:             'type'        => $coursetypebuf{$crsid},
                   3600:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3601:         };
1.191     harris41 3602:     }
1.352     www      3603: #
                   3604: # Write course id database (reverse lookup) to homeserver of courses 
                   3605: # Is used in pickcourse
                   3606: #
1.840     albertel 3607:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3608:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3609:                                     $courseidbuffer{$crs_home},
                   3610:                                     $crs_home,'timeonly');
1.352     www      3611:     }
                   3612: #
                   3613: # File accesses
                   3614: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3615: #
1.449     matthew  3616:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3617:         if ($entry =~ /___count$/) {
                   3618:             my ($dom,$name);
1.807     albertel 3619:             ($dom,$name,undef)=
1.811     albertel 3620: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3621:             if (! defined($dom) || $dom eq '' || 
                   3622:                 ! defined($name) || $name eq '') {
1.620     albertel 3623:                 my $cid = $env{'request.course.id'};
                   3624:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3625:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3626:             }
1.450     matthew  3627:             my $value = $accesshash{$entry};
                   3628:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3629:             my %temphash=($url => $value);
1.449     matthew  3630:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3631:             if ($result eq 'ok') {
                   3632:                 delete $accesshash{$entry};
                   3633:             }
                   3634:         } else {
1.811     albertel 3635:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3636:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3637:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3638:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3639:                 delete $accesshash{$entry};
                   3640:             }
1.185     www      3641:         }
1.191     harris41 3642:     }
1.352     www      3643: #
                   3644: # Roles
                   3645: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3646: #
1.800     albertel 3647:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3648:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3649: 	    split(/\:/,$entry);
                   3650:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3651:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3652:                 $rudom,$runame) eq 'ok') {
                   3653: 	    delete $userrolehash{$entry};
                   3654:         }
                   3655:     }
1.662     raeburn  3656: #
                   3657: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3658: #
                   3659:     my %domrolebuffer = ();
1.1000    raeburn  3660:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3661:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3662:         if ($domrolebuffer{$rudom}) {
                   3663:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3664:                       '='.&escape($domainrolehash{$entry});
                   3665:         } else {
                   3666:             $domrolebuffer{$rudom}.=&escape($entry).
                   3667:                       '='.&escape($domainrolehash{$entry});
                   3668:         }
                   3669:         delete $domainrolehash{$entry};
                   3670:     }
                   3671:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3672: 	my %servers = &get_servers($dom,'library');
                   3673: 	foreach my $tryserver (keys(%servers)) {
                   3674: 	    unless (&reply('domroleput:'.$dom.':'.
                   3675: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3676: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3677: 	    }
1.662     raeburn  3678:         }
                   3679:     }
1.186     www      3680:     $dumpcount++;
1.157     www      3681: }
                   3682: 
                   3683: sub courselog {
                   3684:     my $what=shift;
1.158     www      3685:     $what=time.':'.$what;
1.620     albertel 3686:     unless ($env{'request.course.id'}) { return ''; }
                   3687:     $coursedombuf{$env{'request.course.id'}}=
                   3688:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3689:     $coursenumbuf{$env{'request.course.id'}}=
                   3690:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3691:     $coursehombuf{$env{'request.course.id'}}=
                   3692:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3693:     $coursedescrbuf{$env{'request.course.id'}}=
                   3694:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3695:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3696:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3697:     $courseownerbuf{$env{'request.course.id'}}=
                   3698:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3699:     $coursetypebuf{$env{'request.course.id'}}=
                   3700:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3701:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3702: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3703:     } else {
1.620     albertel 3704: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3705:     }
1.620     albertel 3706:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3707: 	&flushcourselogs();
                   3708:     }
1.158     www      3709: }
                   3710: 
                   3711: sub courseacclog {
                   3712:     my $fnsymb=shift;
1.620     albertel 3713:     unless ($env{'request.course.id'}) { return ''; }
                   3714:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3715:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3716:         $what.=':POST';
1.583     matthew  3717:         # FIXME: Probably ought to escape things....
1.800     albertel 3718: 	foreach my $key (keys(%env)) {
                   3719:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3720:                 my $formitem = $1;
                   3721:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3722:                     $what.=':'.$formitem.'='.$env{$key};
                   3723:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3724:                     $what.=':'.$formitem.'='.$env{$key};
                   3725:                 }
1.158     www      3726:             }
1.191     harris41 3727:         }
1.583     matthew  3728:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3729:         # FIXME: We should not be depending on a form parameter that someone
                   3730:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3731:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3732:             $what.= ':POST';
                   3733:             # FIXME: Probably ought to escape things....
                   3734:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3735:                                  'crsdiscuss') {
1.620     albertel 3736:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3737:             }
                   3738:         }
1.158     www      3739:     }
                   3740:     &courselog($what);
1.149     www      3741: }
                   3742: 
1.185     www      3743: sub countacc {
                   3744:     my $url=&declutter(shift);
1.458     matthew  3745:     return if (! defined($url) || $url eq '');
1.620     albertel 3746:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3747: #
                   3748: # Mark that this url was used in this course
                   3749: #
1.620     albertel 3750:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3751: #
                   3752: # Increase the access count for this resource in this child process
                   3753: #
1.281     www      3754:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3755:     $accesshash{$key}++;
1.185     www      3756: }
1.349     www      3757: 
1.361     www      3758: sub linklog {
                   3759:     my ($from,$to)=@_;
                   3760:     $from=&declutter($from);
                   3761:     $to=&declutter($to);
                   3762:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3763:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3764: }
1.1160    www      3765: 
                   3766: sub statslog {
                   3767:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3768:     if ($users<2) { return; }
                   3769:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3770:             'course'       => $env{'request.course.id'},
                   3771:             'sections'     => '"all"',
                   3772:             'num_students' => $users,
                   3773:             'part'         => $part,
                   3774:             'symb'         => $symb,
                   3775:             'mean_tries'   => $av_attempts,
                   3776:             'deg_of_diff'  => $degdiff});
                   3777:     foreach my $key (keys(%dynstore)) {
                   3778:         $accesshash{$key}=$dynstore{$key};
                   3779:     }
                   3780: }
1.361     www      3781:   
1.349     www      3782: sub userrolelog {
                   3783:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3784:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3785:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3786:        $userrolehash
                   3787:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3788:                     =$tend.':'.$tstart;
1.662     raeburn  3789:     }
1.1169    droeschl 3790:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3791:        $userrolehash
                   3792:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3793:                     =$tend.':'.$tstart;
                   3794:     }
1.1169    droeschl 3795:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3796:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3797:        $domainrolehash
                   3798:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3799:                     = $tend.':'.$tstart;
                   3800:     }
1.351     www      3801: }
                   3802: 
1.957     raeburn  3803: sub courserolelog {
                   3804:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3805:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3806:         my $cdom = $1;
                   3807:         my $cnum = $2;
                   3808:         my $sec = $3;
                   3809:         my $namespace = 'rolelog';
                   3810:         my %storehash = (
                   3811:                            role    => $trole,
                   3812:                            start   => $tstart,
                   3813:                            end     => $tend,
                   3814:                            selfenroll => $selfenroll,
                   3815:                            context    => $context,
                   3816:                         );
                   3817:         if ($trole eq 'gr') {
                   3818:             $namespace = 'groupslog';
                   3819:             $storehash{'group'} = $sec;
                   3820:         } else {
                   3821:             $storehash{'section'} = $sec;
                   3822:         }
                   3823:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3824:                    $domain,$cnum,$cdom);
                   3825:         if (($trole ne 'st') || ($sec ne '')) {
                   3826:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3827:         }
                   3828:     }
                   3829:     return;
                   3830: }
                   3831: 
1.1172.2.9  raeburn  3832: sub domainrolelog {
                   3833:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3834:     if ($area =~ m{^/($match_domain)/$}) {
                   3835:         my $cdom = $1;
                   3836:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3837:         my $namespace = 'rolelog';
                   3838:         my %storehash = (
                   3839:                            role    => $trole,
                   3840:                            start   => $tstart,
                   3841:                            end     => $tend,
                   3842:                            context => $context,
                   3843:                         );
                   3844:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3845:                    $domain,$domconfiguser,$cdom);
                   3846:     }
                   3847:     return;
                   3848: 
                   3849: }
                   3850: 
                   3851: sub coauthorrolelog {
                   3852:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3853:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3854:         my $audom = $1;
                   3855:         my $auname = $2;
                   3856:         my $namespace = 'rolelog';
                   3857:         my %storehash = (
                   3858:                            role    => $trole,
                   3859:                            start   => $tstart,
                   3860:                            end     => $tend,
                   3861:                            context => $context,
                   3862:                         );
                   3863:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3864:                    $domain,$auname,$audom);
                   3865:     }
                   3866:     return;
                   3867: }
                   3868: 
1.351     www      3869: sub get_course_adv_roles {
1.948     raeburn  3870:     my ($cid,$codes) = @_;
1.620     albertel 3871:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3872:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3873:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3874:     my %nothide=();
1.800     albertel 3875:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3876:         if ($user !~ /:/) {
                   3877: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3878:         } else {
                   3879:             $nothide{$user}=1;
                   3880:         }
1.470     www      3881:     }
1.351     www      3882:     my %returnhash=();
                   3883:     my %dumphash=
                   3884:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3885:     my $now=time;
1.997     raeburn  3886:     my %privileged;
1.1000    raeburn  3887:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3888: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3889:         if (($tstart) && ($tstart<0)) { next; }
                   3890:         if (($tend) && ($tend<$now)) { next; }
                   3891:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3892:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3893: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3894:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3895:             my %dompersonnel =
1.998     raeburn  3896:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3897:             $privileged{$domain} = {};
                   3898:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3899:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3900:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3901:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3902:                         $privileged{$udom}{$uname} = 1;
                   3903:                     }
                   3904:                 }
                   3905:             }
                   3906:         }
                   3907:         if ((exists($privileged{$domain}{$username})) && 
                   3908:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3909: 	if ($role eq 'cr') { next; }
1.948     raeburn  3910:         if ($codes) {
                   3911:             if ($section) { $role .= ':'.$section; }
                   3912:             if ($returnhash{$role}) {
                   3913:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3914:             } else {
                   3915:                 $returnhash{$role}=$username.':'.$domain;
                   3916:             }
1.351     www      3917:         } else {
1.988     raeburn  3918:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3919:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3920:             if ($returnhash{$key}) {
                   3921: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3922:             } else {
                   3923:                 $returnhash{$key}=$username.':'.$domain;
                   3924:             }
1.351     www      3925:         }
1.948     raeburn  3926:     }
1.400     www      3927:     return %returnhash;
                   3928: }
                   3929: 
                   3930: sub get_my_roles {
1.937     raeburn  3931:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3932:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3933:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3934:     my (%dumphash,%nothide);
1.1086    raeburn  3935:     if ($context eq 'userroles') {
1.1166    raeburn  3936:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3937:     } else {
                   3938:         %dumphash=
1.400     www      3939:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3940:         if ($hidepriv) {
                   3941:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3942:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3943:                 if ($user !~ /:/) {
                   3944:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3945:                 } else {
                   3946:                     $nothide{$user} = 1;
                   3947:                 }
                   3948:             }
                   3949:         }
1.858     raeburn  3950:     }
1.400     www      3951:     my %returnhash=();
                   3952:     my $now=time;
1.999     raeburn  3953:     my %privileged;
1.800     albertel 3954:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3955:         my ($role,$tend,$tstart);
                   3956:         if ($context eq 'userroles') {
1.1149    raeburn  3957:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3958: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3959:         } else {
                   3960:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3961:         }
1.400     www      3962:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3963:         my $status = 'active';
1.939     raeburn  3964:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3965:             $status = 'previous';
                   3966:         } 
                   3967:         if (($tstart) && ($now<$tstart)) {
                   3968:             $status = 'future';
                   3969:         }
                   3970:         if (ref($types) eq 'ARRAY') {
                   3971:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3972:                 next;
                   3973:             } 
                   3974:         } else {
                   3975:             if ($status ne 'active') {
                   3976:                 next;
                   3977:             }
                   3978:         }
1.867     raeburn  3979:         my ($rolecode,$username,$domain,$section,$area);
                   3980:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3981:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3982:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3983:         } else {
                   3984:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3985:         }
1.832     raeburn  3986:         if (ref($roledoms) eq 'ARRAY') {
                   3987:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3988:                 next;
                   3989:             }
                   3990:         }
                   3991:         if (ref($roles) eq 'ARRAY') {
                   3992:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3993:                 if ($role =~ /^cr\//) {
                   3994:                     if (!grep(/^cr$/,@{$roles})) {
                   3995:                         next;
                   3996:                     }
1.1104    raeburn  3997:                 } elsif ($role =~ /^gr\//) {
                   3998:                     if (!grep(/^gr$/,@{$roles})) {
                   3999:                         next;
                   4000:                     }
1.922     raeburn  4001:                 } else {
                   4002:                     next;
                   4003:                 }
1.832     raeburn  4004:             }
1.867     raeburn  4005:         }
1.937     raeburn  4006:         if ($hidepriv) {
1.999     raeburn  4007:             if ($context eq 'userroles') {
                   4008:                 if ((&privileged($username,$domain)) &&
                   4009:                     (!$nothide{$username.':'.$domain})) {
                   4010:                     next;
                   4011:                 }
                   4012:             } else {
                   4013:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4014:                     my %dompersonnel =
                   4015:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4016:                     $privileged{$domain} = {};
                   4017:                     if (keys(%dompersonnel)) {
                   4018:                         foreach my $server (keys(%dompersonnel)) {
                   4019:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4020:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4021:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4022:                                     $privileged{$udom}{$uname} = $trole;
                   4023:                                 }
                   4024:                             }
                   4025:                         }
                   4026:                     }
                   4027:                 }
                   4028:                 if (exists($privileged{$domain}{$username})) {
                   4029:                     if (!$nothide{$username.':'.$domain}) {
                   4030:                         next;
                   4031:                     }
                   4032:                 }
1.937     raeburn  4033:             }
                   4034:         }
1.933     raeburn  4035:         if ($withsec) {
                   4036:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4037:                 $tstart.':'.$tend;
                   4038:         } else {
                   4039:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4040:         }
1.832     raeburn  4041:     }
1.373     www      4042:     return %returnhash;
1.399     www      4043: }
                   4044: 
                   4045: # ----------------------------------------------------- Frontpage Announcements
                   4046: #
                   4047: #
                   4048: 
                   4049: sub postannounce {
                   4050:     my ($server,$text)=@_;
1.844     albertel 4051:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4052:     unless ($text=~/\w/) { $text=''; }
                   4053:     return &reply('setannounce:'.&escape($text),$server);
                   4054: }
                   4055: 
                   4056: sub getannounce {
1.448     albertel 4057: 
                   4058:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4059: 	my $announcement='';
1.800     albertel 4060: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4061: 	close($fh);
1.399     www      4062: 	if ($announcement=~/\w/) { 
                   4063: 	    return 
                   4064:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4065:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4066: 	} else {
                   4067: 	    return '';
                   4068: 	}
                   4069:     } else {
                   4070: 	return '';
                   4071:     }
1.351     www      4072: }
1.353     www      4073: 
                   4074: # ---------------------------------------------------------- Course ID routines
                   4075: # Deal with domain's nohist_courseid.db files
                   4076: #
                   4077: 
                   4078: sub courseidput {
1.921     raeburn  4079:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4080:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4081:     my $outcome;
                   4082:     if ($caller eq 'timeonly') {
                   4083:         my $cids = '';
                   4084:         foreach my $item (keys(%$storehash)) {
                   4085:             $cids.=&escape($item).'&';
                   4086:         }
                   4087:         $cids=~s/\&$//;
                   4088:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4089:                           $coursehome);       
                   4090:     } else {
                   4091:         my $items = '';
                   4092:         foreach my $item (keys(%$storehash)) {
                   4093:             $items.= &escape($item).'='.
                   4094:                      &freeze_escape($$storehash{$item}).'&';
                   4095:         }
                   4096:         $items=~s/\&$//;
                   4097:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4098:                           $coursehome);
1.918     raeburn  4099:     }
                   4100:     if ($outcome eq 'unknown_cmd') {
                   4101:         my $what;
                   4102:         foreach my $cid (keys(%$storehash)) {
                   4103:             $what .= &escape($cid).'=';
1.921     raeburn  4104:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4105:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4106:             }
                   4107:             $what =~ s/\:$/&/;
                   4108:         }
                   4109:         $what =~ s/\&$//;  
                   4110:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4111:     } else {
                   4112:         return $outcome;
                   4113:     }
1.353     www      4114: }
                   4115: 
                   4116: sub courseiddump {
1.921     raeburn  4117:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4118:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4119:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4120:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4121:     my $as_hash = 1;
                   4122:     my %returnhash;
                   4123:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4124:     my %libserv = &all_library();
                   4125:     foreach my $tryserver (keys(%libserv)) {
                   4126:         if ( (  $hostidflag == 1 
                   4127: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4128: 	     || (!defined($hostidflag)) ) {
                   4129: 
1.918     raeburn  4130: 	    if (($domfilter eq '') ||
                   4131: 		(&host_domain($tryserver) eq $domfilter)) {
                   4132:                 my $rep = 
                   4133:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4134:                          $sincefilter.':'.&escape($descfilter).':'.
                   4135:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   4136:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  4137:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  4138:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  4139:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  4140:                          &escape($cc_clone).':'.$cloneonly.':'.
                   4141:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  4142:                          &escape($creationcontext).':'.$domcloner,
                   4143:                          $tryserver);
1.918     raeburn  4144:                 my @pairs=split(/\&/,$rep);
                   4145:                 foreach my $item (@pairs) {
                   4146:                     my ($key,$value)=split(/\=/,$item,2);
                   4147:                     $key = &unescape($key);
                   4148:                     next if ($key =~ /^error: 2 /);
                   4149:                     my $result = &thaw_unescape($value);
                   4150:                     if (ref($result) eq 'HASH') {
                   4151:                         $returnhash{$key}=$result;
                   4152:                     } else {
1.921     raeburn  4153:                         my @responses = split(/:/,$value);
                   4154:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4155:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4156:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4157:                         }
1.1008    raeburn  4158:                     }
1.353     www      4159:                 }
                   4160:             }
                   4161:         }
                   4162:     }
                   4163:     return %returnhash;
                   4164: }
                   4165: 
1.1055    raeburn  4166: sub courselastaccess {
                   4167:     my ($cdom,$cnum,$hostidref) = @_;
                   4168:     my %returnhash;
                   4169:     if ($cdom && $cnum) {
                   4170:         my $chome = &homeserver($cnum,$cdom);
                   4171:         if ($chome ne 'no_host') {
                   4172:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4173:             &extract_lastaccess(\%returnhash,$rep);
                   4174:         }
                   4175:     } else {
                   4176:         if (!$cdom) { $cdom=''; }
                   4177:         my %libserv = &all_library();
                   4178:         foreach my $tryserver (keys(%libserv)) {
                   4179:             if (ref($hostidref) eq 'ARRAY') {
                   4180:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4181:             } 
                   4182:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4183:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4184:                 &extract_lastaccess(\%returnhash,$rep);
                   4185:             }
                   4186:         }
                   4187:     }
                   4188:     return %returnhash;
                   4189: }
                   4190: 
                   4191: sub extract_lastaccess {
                   4192:     my ($returnhash,$rep) = @_;
                   4193:     if (ref($returnhash) eq 'HASH') {
                   4194:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4195:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4196:                  $rep eq '') {
                   4197:             my @pairs=split(/\&/,$rep);
                   4198:             foreach my $item (@pairs) {
                   4199:                 my ($key,$value)=split(/\=/,$item,2);
                   4200:                 $key = &unescape($key);
                   4201:                 next if ($key =~ /^error: 2 /);
                   4202:                 $returnhash->{$key} = &thaw_unescape($value);
                   4203:             }
                   4204:         }
                   4205:     }
                   4206:     return;
                   4207: }
                   4208: 
1.658     raeburn  4209: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4210: 
                   4211: sub dcmailput {
1.685     raeburn  4212:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4213:     my $status = &Apache::lonnet::critical(
1.740     www      4214:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4215:        &escape($message),$server);
1.662     raeburn  4216:     return $status;
                   4217: }
                   4218: 
1.658     raeburn  4219: sub dcmaildump {
                   4220:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4221:     my %returnhash=();
1.846     albertel 4222: 
                   4223:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4224:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4225:                                                          &escape($enddate).':';
                   4226: 	my @esc_senders=map { &escape($_)} @$senders;
                   4227: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4228: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4229:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4230:             if (($key) && ($value)) {
                   4231:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4232:             }
                   4233:         }
                   4234:     }
                   4235:     return %returnhash;
                   4236: }
1.662     raeburn  4237: # ---------------------------------------------------------- Domain roles
                   4238: 
                   4239: sub get_domain_roles {
                   4240:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4241:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4242:         $startdate = '.';
                   4243:     }
1.1018    raeburn  4244:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4245:         $enddate = '.';
                   4246:     }
1.922     raeburn  4247:     my $rolelist;
                   4248:     if (ref($roles) eq 'ARRAY') {
                   4249:         $rolelist = join(':',@{$roles});
                   4250:     }
1.662     raeburn  4251:     my %personnel = ();
1.841     albertel 4252: 
                   4253:     my %servers = &get_servers($dom,'library');
                   4254:     foreach my $tryserver (keys(%servers)) {
                   4255: 	%{$personnel{$tryserver}}=();
                   4256: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4257: 					    &escape($startdate).':'.
                   4258: 					    &escape($enddate).':'.
                   4259: 					    &escape($rolelist), $tryserver))) {
                   4260: 	    my ($key,$value) = split(/\=/,$line,2);
                   4261: 	    if (($key) && ($value)) {
                   4262: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4263: 	    }
                   4264: 	}
1.662     raeburn  4265:     }
                   4266:     return %personnel;
                   4267: }
1.658     raeburn  4268: 
1.1057    www      4269: # ----------------------------------------------------------- Interval timing 
1.149     www      4270: 
1.1153    www      4271: {
                   4272: # Caches needed for speedup of navmaps
                   4273: # We don't want to cache this for very long at all (5 seconds at most)
                   4274: # 
                   4275: # The user for whom we cache
                   4276: my $cachedkey='';
                   4277: # The cached times for this user
                   4278: my %cachedtimes=();
                   4279: # When this was last done
                   4280: my $cachedtime=();
                   4281: 
                   4282: sub load_all_first_access {
1.1154    raeburn  4283:     my ($uname,$udom)=@_;
1.1156    www      4284:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4285:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4286:         return;
                   4287:     }
                   4288:     $cachedtime=time;
                   4289:     $cachedkey=$uname.':'.$udom;
                   4290:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4291: }
                   4292: 
1.504     albertel 4293: sub get_first_access {
1.1162    raeburn  4294:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4295:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4296:     if ($argsymb) { $symb=$argsymb; }
                   4297:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4298:     if ($argmap) { $map = $argmap; }
1.926     albertel 4299:     if ($type eq 'course') {
                   4300: 	$res='course';
                   4301:     } elsif ($type eq 'map') {
1.588     albertel 4302: 	$res=&symbread($map);
                   4303:     } else {
                   4304: 	$res=$symb;
                   4305:     }
1.1153    www      4306:     &load_all_first_access($uname,$udom);
                   4307:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4308: }
                   4309: 
                   4310: sub set_first_access {
1.1162    raeburn  4311:     my ($type,$interval)=@_;
1.790     albertel 4312:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4313:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4314:     if ($type eq 'course') {
                   4315: 	$res='course';
                   4316:     } elsif ($type eq 'map') {
1.588     albertel 4317: 	$res=&symbread($map);
                   4318:     } else {
                   4319: 	$res=$symb;
                   4320:     }
1.1153    www      4321:     $cachedkey='';
1.1162    raeburn  4322:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4323:     if (!$firstaccess) {
1.1162    raeburn  4324:         my $start = time;
                   4325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4326:                           $udom,$uname);
                   4327:         if ($putres eq 'ok') {
                   4328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4329:                  $udom,$uname); 
                   4330:             &appenv(
                   4331:                      {
                   4332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4334:                      }
                   4335:                   );
                   4336:         }
                   4337:         return $putres;
1.505     albertel 4338:     }
                   4339:     return 'already_set';
1.504     albertel 4340: }
1.1153    www      4341: }
1.110     www      4342: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4343: 
                   4344: sub expirespread {
                   4345:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4346:     my $cid=$env{'request.course.id'}; 
1.110     www      4347:     if ($cid) {
                   4348:        my $now=time;
                   4349:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4350:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4351:                             $env{'course.'.$cid.'.num'}.
1.110     www      4352: 	        	    ':nohist_expirationdates:'.
                   4353:                             &escape($key).'='.$now,
1.620     albertel 4354:                             $env{'course.'.$cid.'.home'})
1.110     www      4355:     }
                   4356:     return 'ok';
1.14      www      4357: }
                   4358: 
1.109     www      4359: # ----------------------------------------------------- Devalidate Spreadsheets
                   4360: 
                   4361: sub devalidate {
1.325     www      4362:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4363:     my $cid=$env{'request.course.id'}; 
1.109     www      4364:     if ($cid) {
1.391     matthew  4365:         # delete the stored spreadsheets for
                   4366:         # - the student level sheet of this user in course's homespace
                   4367:         # - the assessment level sheet for this resource 
                   4368:         #   for this user in user's homespace
1.553     albertel 4369: 	# - current conditional state info
1.325     www      4370: 	my $key=$uname.':'.$udom.':';
1.109     www      4371:         my $status=
1.299     matthew  4372: 	    &del('nohist_calculatedsheets',
1.391     matthew  4373: 		 [$key.'studentcalc:'],
1.620     albertel 4374: 		 $env{'course.'.$cid.'.domain'},
                   4375: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4376: 		.' '.
                   4377: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4378: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4379:         unless ($status eq 'ok ok') {
                   4380:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4381:                     $uname.' at '.$udom.' for '.
1.109     www      4382: 		    $symb.': '.$status);
1.133     albertel 4383:         }
1.553     albertel 4384: 	&delenv('user.state.'.$cid);
1.109     www      4385:     }
                   4386: }
                   4387: 
1.265     albertel 4388: sub get_scalar {
                   4389:     my ($string,$end) = @_;
                   4390:     my $value;
                   4391:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4392: 	$value = $1;
                   4393:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4394: 	$value = $1;
                   4395:     }
                   4396:     return &unescape($value);
                   4397: }
                   4398: 
                   4399: sub array2str {
                   4400:   my (@array) = @_;
                   4401:   my $result=&arrayref2str(\@array);
                   4402:   $result=~s/^__ARRAY_REF__//;
                   4403:   $result=~s/__END_ARRAY_REF__$//;
                   4404:   return $result;
                   4405: }
                   4406: 
1.204     albertel 4407: sub arrayref2str {
                   4408:   my ($arrayref) = @_;
1.265     albertel 4409:   my $result='__ARRAY_REF__';
1.204     albertel 4410:   foreach my $elem (@$arrayref) {
1.265     albertel 4411:     if(ref($elem) eq 'ARRAY') {
                   4412:       $result.=&arrayref2str($elem).'&';
                   4413:     } elsif(ref($elem) eq 'HASH') {
                   4414:       $result.=&hashref2str($elem).'&';
                   4415:     } elsif(ref($elem)) {
                   4416:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4417:     } else {
                   4418:       $result.=&escape($elem).'&';
                   4419:     }
                   4420:   }
                   4421:   $result=~s/\&$//;
1.265     albertel 4422:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4423:   return $result;
                   4424: }
                   4425: 
1.168     albertel 4426: sub hash2str {
1.204     albertel 4427:   my (%hash) = @_;
                   4428:   my $result=&hashref2str(\%hash);
1.265     albertel 4429:   $result=~s/^__HASH_REF__//;
                   4430:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4431:   return $result;
                   4432: }
                   4433: 
                   4434: sub hashref2str {
                   4435:   my ($hashref)=@_;
1.265     albertel 4436:   my $result='__HASH_REF__';
1.800     albertel 4437:   foreach my $key (sort(keys(%$hashref))) {
                   4438:     if (ref($key) eq 'ARRAY') {
                   4439:       $result.=&arrayref2str($key).'=';
                   4440:     } elsif (ref($key) eq 'HASH') {
                   4441:       $result.=&hashref2str($key).'=';
                   4442:     } elsif (ref($key)) {
1.265     albertel 4443:       $result.='=';
1.800     albertel 4444:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4445:     } else {
1.1132    raeburn  4446: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4447:     }
                   4448: 
1.800     albertel 4449:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4450:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4451:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4452:       $result.=&hashref2str($hashref->{$key}).'&';
                   4453:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4454:        $result.='&';
1.800     albertel 4455:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4456:     } else {
1.800     albertel 4457:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4458:     }
                   4459:   }
1.168     albertel 4460:   $result=~s/\&$//;
1.265     albertel 4461:   $result .= '__END_HASH_REF__';
1.168     albertel 4462:   return $result;
                   4463: }
                   4464: 
                   4465: sub str2hash {
1.265     albertel 4466:     my ($string)=@_;
                   4467:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4468:     return %$hash;
                   4469: }
                   4470: 
                   4471: sub str2hashref {
1.168     albertel 4472:   my ($string) = @_;
1.265     albertel 4473: 
                   4474:   my %hash;
                   4475: 
                   4476:   if($string !~ /^__HASH_REF__/) {
                   4477:       if (! ($string eq '' || !defined($string))) {
                   4478: 	  $hash{'error'}='Not hash reference';
                   4479:       }
                   4480:       return (\%hash, $string);
                   4481:   }
                   4482: 
                   4483:   $string =~ s/^__HASH_REF__//;
                   4484: 
                   4485:   while($string !~ /^__END_HASH_REF__/) {
                   4486:       #key
                   4487:       my $key='';
                   4488:       if($string =~ /^__HASH_REF__/) {
                   4489:           ($key, $string)=&str2hashref($string);
                   4490:           if(defined($key->{'error'})) {
                   4491:               $hash{'error'}='Bad data';
                   4492:               return (\%hash, $string);
                   4493:           }
                   4494:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4495:           ($key, $string)=&str2arrayref($string);
                   4496:           if($key->[0] eq 'Array reference error') {
                   4497:               $hash{'error'}='Bad data';
                   4498:               return (\%hash, $string);
                   4499:           }
                   4500:       } else {
                   4501:           $string =~ s/^(.*?)=//;
1.267     albertel 4502: 	  $key=&unescape($1);
1.265     albertel 4503:       }
                   4504:       $string =~ s/^=//;
                   4505: 
                   4506:       #value
                   4507:       my $value='';
                   4508:       if($string =~ /^__HASH_REF__/) {
                   4509:           ($value, $string)=&str2hashref($string);
                   4510:           if(defined($value->{'error'})) {
                   4511:               $hash{'error'}='Bad data';
                   4512:               return (\%hash, $string);
                   4513:           }
                   4514:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4515:           ($value, $string)=&str2arrayref($string);
                   4516:           if($value->[0] eq 'Array reference error') {
                   4517:               $hash{'error'}='Bad data';
                   4518:               return (\%hash, $string);
                   4519:           }
                   4520:       } else {
                   4521: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4522:       }
                   4523:       $string =~ s/^&//;
                   4524: 
                   4525:       $hash{$key}=$value;
1.204     albertel 4526:   }
1.265     albertel 4527: 
                   4528:   $string =~ s/^__END_HASH_REF__//;
                   4529: 
                   4530:   return (\%hash, $string);
1.204     albertel 4531: }
                   4532: 
                   4533: sub str2array {
1.265     albertel 4534:     my ($string)=@_;
                   4535:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4536:     return @$array;
                   4537: }
                   4538: 
                   4539: sub str2arrayref {
1.204     albertel 4540:   my ($string) = @_;
1.265     albertel 4541:   my @array;
                   4542: 
                   4543:   if($string !~ /^__ARRAY_REF__/) {
                   4544:       if (! ($string eq '' || !defined($string))) {
                   4545: 	  $array[0]='Array reference error';
                   4546:       }
                   4547:       return (\@array, $string);
                   4548:   }
                   4549: 
                   4550:   $string =~ s/^__ARRAY_REF__//;
                   4551: 
                   4552:   while($string !~ /^__END_ARRAY_REF__/) {
                   4553:       my $value='';
                   4554:       if($string =~ /^__HASH_REF__/) {
                   4555:           ($value, $string)=&str2hashref($string);
                   4556:           if(defined($value->{'error'})) {
                   4557:               $array[0] ='Array reference error';
                   4558:               return (\@array, $string);
                   4559:           }
                   4560:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4561:           ($value, $string)=&str2arrayref($string);
                   4562:           if($value->[0] eq 'Array reference error') {
                   4563:               $array[0] ='Array reference error';
                   4564:               return (\@array, $string);
                   4565:           }
                   4566:       } else {
                   4567: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4568:       }
                   4569:       $string =~ s/^&//;
                   4570: 
                   4571:       push(@array, $value);
1.191     harris41 4572:   }
1.265     albertel 4573: 
                   4574:   $string =~ s/^__END_ARRAY_REF__//;
                   4575: 
                   4576:   return (\@array, $string);
1.168     albertel 4577: }
                   4578: 
1.167     albertel 4579: # -------------------------------------------------------------------Temp Store
                   4580: 
1.168     albertel 4581: sub tmpreset {
                   4582:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4583:   if (!$symb) {
                   4584:     $symb=&symbread();
1.620     albertel 4585:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4586:   }
                   4587:   $symb=escape($symb);
                   4588: 
1.620     albertel 4589:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4590:   $namespace=~s/\//\_/g;
                   4591:   $namespace=~s/\W//g;
                   4592: 
1.620     albertel 4593:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4594:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4595:   if ($domain eq 'public' && $stuname eq 'public') {
                   4596:       $stuname=$ENV{'REMOTE_ADDR'};
                   4597:   }
1.1117    foxr     4598:   my $path=LONCAPA::tempdir();
1.168     albertel 4599:   my %hash;
                   4600:   if (tie(%hash,'GDBM_File',
                   4601: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4602: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4603:     foreach my $key (keys(%hash)) {
1.180     albertel 4604:       if ($key=~ /:$symb/) {
1.168     albertel 4605: 	delete($hash{$key});
                   4606:       }
                   4607:     }
                   4608:   }
                   4609: }
                   4610: 
1.167     albertel 4611: sub tmpstore {
1.168     albertel 4612:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4613: 
                   4614:   if (!$symb) {
                   4615:     $symb=&symbread();
1.620     albertel 4616:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4617:   }
                   4618:   $symb=escape($symb);
                   4619: 
                   4620:   if (!$namespace) {
                   4621:     # I don't think we would ever want to store this for a course.
                   4622:     # it seems this will only be used if we don't have a course.
1.620     albertel 4623:     #$namespace=$env{'request.course.id'};
1.168     albertel 4624:     #if (!$namespace) {
1.620     albertel 4625:       $namespace=$env{'request.state'};
1.168     albertel 4626:     #}
                   4627:   }
                   4628:   $namespace=~s/\//\_/g;
                   4629:   $namespace=~s/\W//g;
1.620     albertel 4630:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4631:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4632:   if ($domain eq 'public' && $stuname eq 'public') {
                   4633:       $stuname=$ENV{'REMOTE_ADDR'};
                   4634:   }
1.168     albertel 4635:   my $now=time;
                   4636:   my %hash;
1.1117    foxr     4637:   my $path=LONCAPA::tempdir();
1.168     albertel 4638:   if (tie(%hash,'GDBM_File',
                   4639: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4640: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4641:     $hash{"version:$symb"}++;
                   4642:     my $version=$hash{"version:$symb"};
                   4643:     my $allkeys=''; 
                   4644:     foreach my $key (keys(%$storehash)) {
                   4645:       $allkeys.=$key.':';
1.591     albertel 4646:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4647:     }
                   4648:     $hash{"$version:$symb:timestamp"}=$now;
                   4649:     $allkeys.='timestamp';
                   4650:     $hash{"$version:keys:$symb"}=$allkeys;
                   4651:     if (untie(%hash)) {
                   4652:       return 'ok';
                   4653:     } else {
                   4654:       return "error:$!";
                   4655:     }
                   4656:   } else {
                   4657:     return "error:$!";
                   4658:   }
                   4659: }
1.167     albertel 4660: 
1.168     albertel 4661: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4662: 
1.168     albertel 4663: sub tmprestore {
                   4664:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4665: 
1.168     albertel 4666:   if (!$symb) {
                   4667:     $symb=&symbread();
1.620     albertel 4668:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4669:   }
                   4670:   $symb=escape($symb);
                   4671: 
1.620     albertel 4672:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4673: 
1.620     albertel 4674:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4675:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4676:   if ($domain eq 'public' && $stuname eq 'public') {
                   4677:       $stuname=$ENV{'REMOTE_ADDR'};
                   4678:   }
1.168     albertel 4679:   my %returnhash;
                   4680:   $namespace=~s/\//\_/g;
                   4681:   $namespace=~s/\W//g;
                   4682:   my %hash;
1.1117    foxr     4683:   my $path=LONCAPA::tempdir();
1.168     albertel 4684:   if (tie(%hash,'GDBM_File',
                   4685: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4686: 	  &GDBM_READER(),0640)) {
1.168     albertel 4687:     my $version=$hash{"version:$symb"};
                   4688:     $returnhash{'version'}=$version;
                   4689:     my $scope;
                   4690:     for ($scope=1;$scope<=$version;$scope++) {
                   4691:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4692:       my @keys=split(/:/,$vkeys);
                   4693:       my $key;
                   4694:       $returnhash{"$scope:keys"}=$vkeys;
                   4695:       foreach $key (@keys) {
1.591     albertel 4696: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4697: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4698:       }
                   4699:     }
1.168     albertel 4700:     if (!(untie(%hash))) {
                   4701:       return "error:$!";
                   4702:     }
                   4703:   } else {
                   4704:     return "error:$!";
                   4705:   }
                   4706:   return %returnhash;
1.167     albertel 4707: }
                   4708: 
1.9       www      4709: # ----------------------------------------------------------------------- Store
                   4710: 
                   4711: sub store {
1.124     www      4712:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4713:     my $home='';
                   4714: 
1.168     albertel 4715:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4716: 
1.213     www      4717:     $symb=&symbclean($symb);
1.122     albertel 4718:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4719: 
1.620     albertel 4720:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4721:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4722: 
                   4723:     &devalidate($symb,$stuname,$domain);
1.109     www      4724: 
                   4725:     $symb=escape($symb);
1.187     www      4726:     if (!$namespace) { 
1.620     albertel 4727:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4728:           return ''; 
                   4729:        } 
                   4730:     }
1.620     albertel 4731:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4732: 
                   4733:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4734:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4735: 
1.12      www      4736:     my $namevalue='';
1.800     albertel 4737:     foreach my $key (keys(%$storehash)) {
                   4738:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4739:     }
1.12      www      4740:     $namevalue=~s/\&$//;
1.187     www      4741:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4742:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4743: }
                   4744: 
1.47      www      4745: # -------------------------------------------------------------- Critical Store
                   4746: 
                   4747: sub cstore {
1.124     www      4748:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4749:     my $home='';
                   4750: 
1.168     albertel 4751:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4752: 
1.213     www      4753:     $symb=&symbclean($symb);
1.122     albertel 4754:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4755: 
1.620     albertel 4756:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4757:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4758: 
                   4759:     &devalidate($symb,$stuname,$domain);
1.109     www      4760: 
                   4761:     $symb=escape($symb);
1.187     www      4762:     if (!$namespace) { 
1.620     albertel 4763:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4764:           return ''; 
                   4765:        } 
                   4766:     }
1.620     albertel 4767:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4768: 
                   4769:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4770:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4771: 
1.47      www      4772:     my $namevalue='';
1.800     albertel 4773:     foreach my $key (keys(%$storehash)) {
                   4774:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4775:     }
1.47      www      4776:     $namevalue=~s/\&$//;
1.187     www      4777:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4778:     return critical
                   4779:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4780: }
                   4781: 
1.9       www      4782: # --------------------------------------------------------------------- Restore
                   4783: 
                   4784: sub restore {
1.124     www      4785:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4786:     my $home='';
                   4787: 
1.168     albertel 4788:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4789: 
1.122     albertel 4790:     if (!$symb) {
                   4791:       unless ($symb=escape(&symbread())) { return ''; }
                   4792:     } else {
1.213     www      4793:       $symb=&escape(&symbclean($symb));
1.122     albertel 4794:     }
1.188     www      4795:     if (!$namespace) { 
1.620     albertel 4796:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4797:           return ''; 
                   4798:        } 
                   4799:     }
1.620     albertel 4800:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4801:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4802:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4803:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4804: 
1.12      www      4805:     my %returnhash=();
1.800     albertel 4806:     foreach my $line (split(/\&/,$answer)) {
                   4807: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4808:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4809:     }
1.75      www      4810:     my $version;
                   4811:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4812:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4813:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4814:        }
1.75      www      4815:     }
1.13      www      4816:     return %returnhash;
1.34      www      4817: }
                   4818: 
                   4819: # ---------------------------------------------------------- Course Description
1.1118    foxr     4820: #
                   4821: #  
1.34      www      4822: 
                   4823: sub coursedescription {
1.731     albertel 4824:     my ($courseid,$args)=@_;
1.34      www      4825:     $courseid=~s/^\///;
1.49      www      4826:     $courseid=~s/\_/\//g;
1.34      www      4827:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4828:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4829:     my $normalid=$cdomain.'_'.$cnum;
                   4830:     # need to always cache even if we get errors otherwise we keep 
                   4831:     # trying and trying and trying to get the course description.
                   4832:     my %envhash=();
                   4833:     my %returnhash=();
1.731     albertel 4834:     
                   4835:     my $expiretime=600;
                   4836:     if ($env{'request.course.id'} eq $normalid) {
                   4837: 	$expiretime=120;
                   4838:     }
                   4839: 
                   4840:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4841:     if (!$args->{'freshen_cache'}
                   4842: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4843: 	foreach my $key (keys(%env)) {
                   4844: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4845: 	    my ($setting) = $1;
                   4846: 	    $returnhash{$setting} = $env{$key};
                   4847: 	}
                   4848: 	return %returnhash;
                   4849:     }
                   4850: 
1.1118    foxr     4851:     # get the data again
                   4852: 
1.731     albertel 4853:     if (!$args->{'one_time'}) {
                   4854: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4855:     }
1.811     albertel 4856: 
1.34      www      4857:     if ($chome ne 'no_host') {
1.302     albertel 4858:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4859:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4860: 	   my $username = $env{'user.name'}; # Defult username
                   4861: 	   if(defined $args->{'user'}) {
                   4862: 	       $username = $args->{'user'};
                   4863: 	   }
1.129     albertel 4864:            $returnhash{'home'}= $chome;
                   4865: 	   $returnhash{'domain'} = $cdomain;
                   4866: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4867:            if (!defined($returnhash{'type'})) {
                   4868:                $returnhash{'type'} = 'Course';
                   4869:            }
1.130     albertel 4870:            while (my ($name,$value) = each %returnhash) {
1.53      www      4871:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4872:            }
1.270     www      4873:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4874:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4875: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4876:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4877:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4878:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4879:        }
                   4880:     }
1.731     albertel 4881:     if (!$args->{'one_time'}) {
1.949     raeburn  4882: 	&appenv(\%envhash);
1.731     albertel 4883:     }
1.302     albertel 4884:     return %returnhash;
1.461     www      4885: }
                   4886: 
1.1080    raeburn  4887: sub update_released_required {
                   4888:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4889:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4890:         $cid = $env{'request.course.id'};
                   4891:         $cdom = $env{'course.'.$cid.'.domain'};
                   4892:         $cnum = $env{'course.'.$cid.'.num'};
                   4893:         $chome = $env{'course.'.$cid.'.home'};
                   4894:     }
                   4895:     if ($needsrelease) {
                   4896:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4897:         my $needsupdate;
                   4898:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4899:             $needsupdate = 1;
                   4900:         } else {
                   4901:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4902:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4903:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4904:                 $needsupdate = 1;
                   4905:             }
                   4906:         }
                   4907:         if ($needsupdate) {
                   4908:             my %needshash = (
                   4909:                              'internal.releaserequired' => $needsrelease,
                   4910:                             );
                   4911:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4912:             if ($putresult eq 'ok') {
                   4913:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4914:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4915:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4916:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4917:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4918:                 }
                   4919:             }
                   4920:         }
                   4921:     }
                   4922:     return;
                   4923: }
                   4924: 
1.461     www      4925: # -------------------------------------------------See if a user is privileged
                   4926: 
                   4927: sub privileged {
                   4928:     my ($username,$domain)=@_;
1.1170    droeschl 4929: 
                   4930:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4931:     my $now = time;
                   4932: 
                   4933:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4934:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4935:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4936:                 return 1 unless ($tend && $tend < $now) 
                   4937:                     or ($tstart && $tstart > $now);
                   4938:             }
1.461     www      4939: 	}
1.1170    droeschl 4940: 
1.461     www      4941:     return 0;
1.9       www      4942: }
1.1       albertel 4943: 
1.103     harris41 4944: # -------------------------------------------------------- Get user privileges
1.11      www      4945: 
                   4946: sub rolesinit {
1.1169    droeschl 4947:     my ($domain, $username) = @_;
                   4948:     my %userroles = ('user.login.time' => time);
                   4949:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4950: 
                   4951:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4952:     # also, blocking can be triggered by an activating timer
                   4953:     # it's saved in the user's %env.
                   4954:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4955:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4956:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4957:         %timerintchk, %timerintenv);
                   4958: 
1.1162    raeburn  4959:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4960:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4961:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4962:     }
1.1169    droeschl 4963: 
1.1162    raeburn  4964:     foreach my $key (keys(%timerinterval)) {
                   4965:         my ($cid,$rest) = split(/\0/,$key);
                   4966:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4967:     }
1.1169    droeschl 4968: 
1.11      www      4969:     my %allroles=();
1.1162    raeburn  4970:     my %allgroups=();
1.11      www      4971: 
1.1169    droeschl 4972:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4973:         my $role = $rolesdump{$area};
                   4974:         $area =~ s/\_\w\w$//;
                   4975: 
                   4976:         my ($trole, $tend, $tstart, $group_privs);
                   4977: 
                   4978:         if ($role =~ /^cr/) {
                   4979:         # Custom role, defined by a user 
                   4980:         # e.g., user.role.cr/msu/smith/mynewrole
                   4981:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4982:                 $trole = $1;
                   4983:                 ($tend, $tstart) = split('_', $2);
                   4984:             } else {
                   4985:                 $trole = $role;
                   4986:             }
                   4987:         } elsif ($role =~ m|^gr/|) {
                   4988:         # Role of member in a group, defined within a course/community
                   4989:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4990:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4991:             next if $tstart eq '-1';
                   4992:             ($trole, $group_privs) = split(/\//, $trole);
                   4993:             $group_privs = &unescape($group_privs);
                   4994:         } else {
                   4995:         # Just a normal role, defined in roles.tab
                   4996:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4997:         }
                   4998: 
                   4999:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5000:                  $username);
                   5001:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5002: 
                   5003:         # role expired or not available yet?
                   5004:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5005:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5006: 
                   5007:         next if $area eq '' or $trole eq '';
                   5008: 
                   5009:         my $spec = "$trole.$area";
                   5010:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5011: 
                   5012:         if ($trole =~ /^cr\//) {
                   5013:         # Custom role, defined by a user
                   5014:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5015:         } elsif ($trole eq 'gr') {
                   5016:         # Role of a member in a group, defined within a course/community
                   5017:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5018:             next;
                   5019:         } else {
                   5020:         # Normal role, defined in roles.tab
                   5021:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5022:         }
                   5023: 
                   5024:         my $cid = $tdomain.'_'.$trest;
                   5025:         unless ($firstaccchk{$cid}) {
                   5026:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5027:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5028:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5029:                         $coursetimerstarts{$cid}{$item}; 
                   5030:                 }
                   5031:             }
                   5032:             $firstaccchk{$cid} = 1;
                   5033:         }
                   5034:         unless ($timerintchk{$cid}) {
                   5035:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5036:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5037:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5038:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5039:                 }
1.12      www      5040:             }
1.1169    droeschl 5041:             $timerintchk{$cid} = 1;
1.191     harris41 5042:         }
1.11      www      5043:     }
1.1169    droeschl 5044: 
                   5045:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5046:         \%allroles, \%allgroups);
                   5047:     $env{'user.adv'} = $userroles{'user.adv'};
                   5048: 
1.1162    raeburn  5049:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5050: }
                   5051: 
1.567     raeburn  5052: sub set_arearole {
                   5053:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   5054: # log the associated role with the area
                   5055:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 5056:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5057: }
                   5058: 
                   5059: sub custom_roleprivs {
                   5060:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5061:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5062:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5063:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5064:         my ($rdummy,$roledef)=
                   5065:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5066:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5067:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5068:             if (defined($syspriv)) {
1.1043    raeburn  5069:                 if ($trest =~ /^$match_community$/) {
                   5070:                     $syspriv =~ s/bre\&S//; 
                   5071:                 }
1.567     raeburn  5072:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5073:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5074:             }
                   5075:             if ($tdomain ne '') {
                   5076:                 if (defined($dompriv)) {
                   5077:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5078:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5079:                 }
                   5080:                 if (($trest ne '') && (defined($coursepriv))) {
                   5081:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5082:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5083:                 }
                   5084:             }
                   5085:         }
                   5086:     }
                   5087: }
                   5088: 
1.678     raeburn  5089: sub group_roleprivs {
                   5090:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5091:     my $access = 1;
                   5092:     my $now = time;
                   5093:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5094:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5095:     if ($access) {
1.811     albertel 5096:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5097:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5098:     }
                   5099: }
1.567     raeburn  5100: 
                   5101: sub standard_roleprivs {
                   5102:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5103:     if (defined($pr{$trole.':s'})) {
                   5104:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5105:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5106:     }
                   5107:     if ($tdomain ne '') {
                   5108:         if (defined($pr{$trole.':d'})) {
                   5109:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5110:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5111:         }
                   5112:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5113:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5114:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5115:         }
                   5116:     }
                   5117: }
                   5118: 
                   5119: sub set_userprivs {
1.1064    raeburn  5120:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5121:     my $author=0;
                   5122:     my $adv=0;
1.678     raeburn  5123:     my %grouproles = ();
                   5124:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5125:         my @groupkeys; 
1.1000    raeburn  5126:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5127:             push(@groupkeys,$role);
                   5128:         }
                   5129:         if (ref($groups_roles) eq 'HASH') {
                   5130:             foreach my $key (keys(%{$groups_roles})) {
                   5131:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5132:                     push(@groupkeys,$key);
                   5133:                 }
                   5134:             }
                   5135:         }
                   5136:         if (@groupkeys > 0) {
                   5137:             foreach my $role (@groupkeys) {
                   5138:                 my ($trole,$area,$sec,$extendedarea);
                   5139:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5140:                     $trole = $1;
                   5141:                     $area = $2;
                   5142:                     $sec = $3;
                   5143:                     $extendedarea = $area.$sec;
                   5144:                     if (exists($$allgroups{$area})) {
                   5145:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5146:                             my $spec = $trole.'.'.$extendedarea;
                   5147:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5148:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5149:                         }
1.678     raeburn  5150:                     }
                   5151:                 }
                   5152:             }
                   5153:         }
                   5154:     }
1.800     albertel 5155:     foreach my $group (keys(%grouproles)) {
                   5156:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5157:     }
1.800     albertel 5158:     foreach my $role (keys(%{$allroles})) {
                   5159:         my %thesepriv;
1.941     raeburn  5160:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5161:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5162:             if ($item ne '') {
                   5163:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5164:                 if ($restrictions eq '') {
                   5165:                     $thesepriv{$privilege}='F';
                   5166:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5167:                     $thesepriv{$privilege}.=$restrictions;
                   5168:                 }
                   5169:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5170:             }
                   5171:         }
                   5172:         my $thesestr='';
1.1104    raeburn  5173:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5174: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5175: 	}
                   5176:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5177:     }
                   5178:     return ($author,$adv);
                   5179: }
                   5180: 
1.994     raeburn  5181: sub role_status {
1.1104    raeburn  5182:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5183:     my @pwhere = ();
                   5184:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5185:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5186:         unless (!defined($$role) || $$role eq '') {
                   5187:             $$where=join('.',@pwhere);
                   5188:             $$trolecode=$$role.'.'.$$where;
                   5189:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5190:             $$tstatus='is';
1.1104    raeburn  5191:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5192:                 $$tstatus='future';
1.1034    raeburn  5193:                 if ($$tstart<$now) {
                   5194:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5195:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5196:                             my (%allroles,%allgroups,$group_privs,
                   5197:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5198:                             my %userroles = (
                   5199:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5200:                             );
1.1064    raeburn  5201:                             @rolecodes = ('cm'); 
1.1002    raeburn  5202:                             my $spec=$$role.'.'.$$where;
                   5203:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5204:                             if ($$role =~ /^cr\//) {
                   5205:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5206:                                 push(@rolecodes,'cr');
1.1002    raeburn  5207:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5208:                                 push(@rolecodes,$$role);
1.1002    raeburn  5209:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5210:                                                     $env{'user.name'});
1.1064    raeburn  5211:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5212:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5213:                                 $group_privs = &unescape($group_privs);
                   5214:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5215:                                 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  5216:                                 &get_groups_roles($tdomain,$trest,
                   5217:                                                   \%course_roles,\@rolecodes,
                   5218:                                                   \%groups_roles);
1.1002    raeburn  5219:                             } else {
1.1064    raeburn  5220:                                 push(@rolecodes,$$role);
1.1002    raeburn  5221:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5222:                             }
1.1064    raeburn  5223:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5224:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5225:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5226:                         }
                   5227:                     }
1.1034    raeburn  5228:                     $$tstatus = 'is';
1.1002    raeburn  5229:                 }
1.994     raeburn  5230:             }
                   5231:             if ($$tend) {
1.1104    raeburn  5232:                 if ($$tend<$update) {
1.994     raeburn  5233:                     $$tstatus='expired';
                   5234:                 } elsif ($$tend<$now) {
                   5235:                     $$tstatus='will_not';
                   5236:                 }
                   5237:             }
                   5238:         }
                   5239:     }
                   5240: }
                   5241: 
1.1104    raeburn  5242: sub get_groups_roles {
                   5243:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5244:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5245:                   (ref($rolecodes) eq 'ARRAY') && 
                   5246:                   (ref($groups_roles) eq 'HASH')); 
                   5247:     if (keys(%{$cdom_courseroles}) > 0) {
                   5248:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5249:         if ($cdom ne '' && $cnum ne '') {
                   5250:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5251:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5252:                     my $crsrole = $1;
                   5253:                     my $crssec = $2;
                   5254:                     if ($crsrole =~ /^cr/) {
                   5255:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5256:                             push(@{$rolecodes},'cr');
                   5257:                         }
                   5258:                     } else {
                   5259:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5260:                             push(@{$rolecodes},$crsrole);
                   5261:                         }
                   5262:                     }
                   5263:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5264:                     if ($crssec ne '') {
                   5265:                         $rolekey .= "/$crssec";
                   5266:                     }
                   5267:                     $rolekey .= './';
                   5268:                     $groups_roles->{$rolekey} = $rolecodes;
                   5269:                 }
                   5270:             }
                   5271:         }
                   5272:     }
                   5273:     return;
                   5274: }
                   5275: 
                   5276: sub delete_env_groupprivs {
                   5277:     my ($where,$courseroles,$possroles) = @_;
                   5278:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5279:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5280:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5281:         %{$courseroles->{$udom}} =
                   5282:             &get_my_roles('','','userroles',['active'],
                   5283:                           $possroles,[$udom],1);
                   5284:     }
                   5285:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5286:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5287:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5288:             my $area = '/'.$cdom.'/'.$cnum;
                   5289:             my $privkey = "user.priv.$crsrole.$area";
                   5290:             if ($crssec ne '') {
                   5291:                 $privkey .= '/'.$crssec;
                   5292:             }
                   5293:             $privkey .= ".$area/$group";
                   5294:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5295:         }
                   5296:     }
                   5297:     return;
                   5298: }
                   5299: 
1.994     raeburn  5300: sub check_adhoc_privs {
1.1104    raeburn  5301:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5302:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5303:     my $setprivs;
1.994     raeburn  5304:     if ($env{$cckey}) {
                   5305:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5306:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5307:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5308:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5309:             $setprivs = 1;
1.994     raeburn  5310:         }
                   5311:     } else {
1.1088    raeburn  5312:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5313:         $setprivs = 1;
1.994     raeburn  5314:     }
1.1172.2.9  raeburn  5315:     return $setprivs;
1.994     raeburn  5316: }
                   5317: 
                   5318: sub set_adhoc_privileges {
                   5319: # role can be cc or ca
1.1088    raeburn  5320:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5321:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5322:     my $spec = $role.'.'.$area;
                   5323:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5324:                                   $env{'user.name'});
                   5325:     my %ccrole = ();
                   5326:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5327:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5328:     &appenv(\%userroles,[$role,'cm']);
                   5329:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5330:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5331:         &appenv( {'request.role'        => $spec,
                   5332:                   'request.role.domain' => $dcdom,
                   5333:                   'request.course.sec'  => ''
                   5334:                  }
                   5335:                );
                   5336:         my $tadv=0;
                   5337:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5338:         &appenv({'request.role.adv'    => $tadv});
                   5339:     }
1.994     raeburn  5340: }
                   5341: 
1.12      www      5342: # --------------------------------------------------------------- get interface
                   5343: 
                   5344: sub get {
1.131     albertel 5345:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5346:    my $items='';
1.800     albertel 5347:    foreach my $item (@$storearr) {
                   5348:        $items.=&escape($item).'&';
1.191     harris41 5349:    }
1.12      www      5350:    $items=~s/\&$//;
1.620     albertel 5351:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5352:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5353:    my $uhome=&homeserver($uname,$udomain);
                   5354: 
1.133     albertel 5355:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5356:    my @pairs=split(/\&/,$rep);
1.273     albertel 5357:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5358:      return @pairs;
                   5359:    }
1.15      www      5360:    my %returnhash=();
1.42      www      5361:    my $i=0;
1.800     albertel 5362:    foreach my $item (@$storearr) {
                   5363:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5364:       $i++;
1.191     harris41 5365:    }
1.15      www      5366:    return %returnhash;
1.27      www      5367: }
                   5368: 
                   5369: # --------------------------------------------------------------- del interface
                   5370: 
                   5371: sub del {
1.133     albertel 5372:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5373:    my $items='';
1.800     albertel 5374:    foreach my $item (@$storearr) {
                   5375:        $items.=&escape($item).'&';
1.191     harris41 5376:    }
1.984     neumanie 5377: 
1.27      www      5378:    $items=~s/\&$//;
1.620     albertel 5379:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5380:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5381:    my $uhome=&homeserver($uname,$udomain);
                   5382:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5383: }
                   5384: 
                   5385: # -------------------------------------------------------------- dump interface
                   5386: 
                   5387: sub dump {
1.1166    raeburn  5388:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5389:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5390:     if (!$uname) { $uname=$env{'user.name'}; }
                   5391:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5392: 
1.755     albertel 5393:     if ($regexp) {
                   5394: 	$regexp=&escape($regexp);
                   5395:     } else {
                   5396: 	$regexp='.';
                   5397:     }
1.1166    raeburn  5398:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5399:     my @pairs=split(/\&/,$rep);
                   5400:     my %returnhash=();
1.1098    foxr     5401:     if (!($rep =~ /^error/ )) {
                   5402: 	foreach my $item (@pairs) {
                   5403: 	    my ($key,$value)=split(/=/,$item,2);
                   5404: 	    $key = &unescape($key);
                   5405: 	    next if ($key =~ /^error: 2 /);
                   5406: 	    $returnhash{$key}=&thaw_unescape($value);
                   5407: 	}
1.755     albertel 5408:     }
                   5409:     return %returnhash;
1.407     www      5410: }
                   5411: 
1.1098    foxr     5412: 
1.717     albertel 5413: # --------------------------------------------------------- dumpstore interface
                   5414: 
                   5415: sub dumpstore {
                   5416:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5417:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5418:    if (!$uname) { $uname=$env{'user.name'}; }
                   5419:    my $uhome=&homeserver($uname,$udomain);
                   5420:    if ($regexp) {
                   5421:        $regexp=&escape($regexp);
                   5422:    } else {
                   5423:        $regexp='.';
                   5424:    }
                   5425:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5426:    my @pairs=split(/\&/,$rep);
                   5427:    my %returnhash=();
                   5428:    foreach my $item (@pairs) {
                   5429:        my ($key,$value)=split(/=/,$item,2);
                   5430:        next if ($key =~ /^error: 2 /);
                   5431:        $returnhash{$key}=&thaw_unescape($value);
                   5432:    }
                   5433:    return %returnhash;
1.717     albertel 5434: }
                   5435: 
1.407     www      5436: # -------------------------------------------------------------- keys interface
                   5437: 
                   5438: sub getkeys {
                   5439:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5440:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5441:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5442:    my $uhome=&homeserver($uname,$udomain);
                   5443:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5444:    my @keyarray=();
1.800     albertel 5445:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5446:       next if ($key =~ /^error: 2 /);
1.800     albertel 5447:       push(@keyarray,&unescape($key));
1.407     www      5448:    }
                   5449:    return @keyarray;
1.318     matthew  5450: }
                   5451: 
1.319     matthew  5452: # --------------------------------------------------------------- currentdump
                   5453: sub currentdump {
1.328     matthew  5454:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5455:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5456:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5457:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5458:    my $uhome = &homeserver($sname,$sdom);
                   5459:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5460:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5461:    #
1.318     matthew  5462:    my %returnhash=();
1.319     matthew  5463:    #
                   5464:    if ($rep eq "unknown_cmd") { 
                   5465:        # an old lond will not know currentdump
                   5466:        # Do a dump and make it look like a currentdump
1.822     albertel 5467:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5468:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5469:        my %hash = @tmp;
                   5470:        @tmp=();
1.424     matthew  5471:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5472:    } else {
                   5473:        my @pairs=split(/\&/,$rep);
1.800     albertel 5474:        foreach my $pair (@pairs) {
                   5475:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5476:            my ($symb,$param) = split(/:/,$key);
                   5477:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5478:                                                         &thaw_unescape($value);
1.319     matthew  5479:        }
1.191     harris41 5480:    }
1.12      www      5481:    return %returnhash;
1.424     matthew  5482: }
                   5483: 
                   5484: sub convert_dump_to_currentdump{
                   5485:     my %hash = %{shift()};
                   5486:     my %returnhash;
                   5487:     # Code ripped from lond, essentially.  The only difference
                   5488:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5489:     # we might run in to problems with parameter names =~ /^v\./
                   5490:     while (my ($key,$value) = each(%hash)) {
                   5491:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5492: 	$symb  = &unescape($symb);
                   5493: 	$param = &unescape($param);
1.424     matthew  5494:         next if ($v eq 'version' || $symb eq 'keys');
                   5495:         next if (exists($returnhash{$symb}) &&
                   5496:                  exists($returnhash{$symb}->{$param}) &&
                   5497:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5498:         $returnhash{$symb}->{$param}=$value;
                   5499:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5500:     }
                   5501:     #
                   5502:     # Remove all of the keys in the hashes which keep track of
                   5503:     # the version of the parameter.
                   5504:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5505:         # use a foreach because we are going to delete from the hash.
                   5506:         foreach my $key (keys(%$param_hash)) {
                   5507:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5508:         }
                   5509:     }
                   5510:     return \%returnhash;
1.12      www      5511: }
                   5512: 
1.627     albertel 5513: # ------------------------------------------------------ critical inc interface
                   5514: 
                   5515: sub cinc {
                   5516:     return &inc(@_,'critical');
                   5517: }
                   5518: 
1.449     matthew  5519: # --------------------------------------------------------------- inc interface
                   5520: 
                   5521: sub inc {
1.627     albertel 5522:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5523:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5524:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5525:     my $uhome=&homeserver($uname,$udomain);
                   5526:     my $items='';
                   5527:     if (! ref($store)) {
                   5528:         # got a single value, so use that instead
                   5529:         $items = &escape($store).'=&';
                   5530:     } elsif (ref($store) eq 'SCALAR') {
                   5531:         $items = &escape($$store).'=&';        
                   5532:     } elsif (ref($store) eq 'ARRAY') {
                   5533:         $items = join('=&',map {&escape($_);} @{$store});
                   5534:     } elsif (ref($store) eq 'HASH') {
                   5535:         while (my($key,$value) = each(%{$store})) {
                   5536:             $items.= &escape($key).'='.&escape($value).'&';
                   5537:         }
                   5538:     }
                   5539:     $items=~s/\&$//;
1.627     albertel 5540:     if ($critical) {
                   5541: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5542:     } else {
                   5543: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5544:     }
1.449     matthew  5545: }
                   5546: 
1.12      www      5547: # --------------------------------------------------------------- put interface
                   5548: 
                   5549: sub put {
1.134     albertel 5550:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5551:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5552:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5553:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5554:    my $items='';
1.800     albertel 5555:    foreach my $item (keys(%$storehash)) {
                   5556:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5557:    }
1.12      www      5558:    $items=~s/\&$//;
1.134     albertel 5559:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5560: }
                   5561: 
1.631     albertel 5562: # ------------------------------------------------------------ newput interface
                   5563: 
                   5564: sub newput {
                   5565:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5566:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5567:    if (!$uname) { $uname=$env{'user.name'}; }
                   5568:    my $uhome=&homeserver($uname,$udomain);
                   5569:    my $items='';
                   5570:    foreach my $key (keys(%$storehash)) {
                   5571:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5572:    }
                   5573:    $items=~s/\&$//;
                   5574:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5575: }
                   5576: 
                   5577: # ---------------------------------------------------------  putstore interface
                   5578: 
1.524     raeburn  5579: sub putstore {
1.715     albertel 5580:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5581:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5582:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5583:    my $uhome=&homeserver($uname,$udomain);
                   5584:    my $items='';
1.715     albertel 5585:    foreach my $key (keys(%$storehash)) {
                   5586:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5587:    }
1.715     albertel 5588:    $items=~s/\&$//;
1.716     albertel 5589:    my $esc_symb=&escape($symb);
                   5590:    my $esc_v=&escape($version);
1.715     albertel 5591:    my $reply =
1.716     albertel 5592:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5593: 	      $uhome);
                   5594:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5595:        # gfall back to way things use to be done
1.715     albertel 5596:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5597: 			    $uname);
1.524     raeburn  5598:    }
1.715     albertel 5599:    return $reply;
                   5600: }
                   5601: 
                   5602: sub old_putstore {
1.716     albertel 5603:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5604:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5605:     if (!$uname) { $uname=$env{'user.name'}; }
                   5606:     my $uhome=&homeserver($uname,$udomain);
                   5607:     my %newstorehash;
1.800     albertel 5608:     foreach my $item (keys(%$storehash)) {
                   5609: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5610: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5611:     }
                   5612:     my $items='';
                   5613:     my %allitems = ();
1.800     albertel 5614:     foreach my $item (keys(%newstorehash)) {
                   5615: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5616: 	    my $key = $1.':keys:'.$2;
                   5617: 	    $allitems{$key} .= $3.':';
                   5618: 	}
1.800     albertel 5619: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5620:     }
1.800     albertel 5621:     foreach my $item (keys(%allitems)) {
                   5622: 	$allitems{$item} =~ s/\:$//;
                   5623: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5624:     }
                   5625:     $items=~s/\&$//;
                   5626:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5627: }
                   5628: 
1.47      www      5629: # ------------------------------------------------------ critical put interface
                   5630: 
                   5631: sub cput {
1.134     albertel 5632:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5633:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5634:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5635:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5636:    my $items='';
1.800     albertel 5637:    foreach my $item (keys(%$storehash)) {
                   5638:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5639:    }
1.47      www      5640:    $items=~s/\&$//;
1.134     albertel 5641:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5642: }
                   5643: 
                   5644: # -------------------------------------------------------------- eget interface
                   5645: 
                   5646: sub eget {
1.133     albertel 5647:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5648:    my $items='';
1.800     albertel 5649:    foreach my $item (@$storearr) {
                   5650:        $items.=&escape($item).'&';
1.191     harris41 5651:    }
1.12      www      5652:    $items=~s/\&$//;
1.620     albertel 5653:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5654:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5655:    my $uhome=&homeserver($uname,$udomain);
                   5656:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5657:    my @pairs=split(/\&/,$rep);
                   5658:    my %returnhash=();
1.42      www      5659:    my $i=0;
1.800     albertel 5660:    foreach my $item (@$storearr) {
                   5661:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5662:       $i++;
1.191     harris41 5663:    }
1.12      www      5664:    return %returnhash;
                   5665: }
                   5666: 
1.667     albertel 5667: # ------------------------------------------------------------ tmpput interface
                   5668: sub tmpput {
1.802     raeburn  5669:     my ($storehash,$server,$context)=@_;
1.667     albertel 5670:     my $items='';
1.800     albertel 5671:     foreach my $item (keys(%$storehash)) {
                   5672: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5673:     }
                   5674:     $items=~s/\&$//;
1.802     raeburn  5675:     if (defined($context)) {
                   5676:         $items .= ':'.&escape($context);
                   5677:     }
1.667     albertel 5678:     return &reply("tmpput:$items",$server);
                   5679: }
                   5680: 
                   5681: # ------------------------------------------------------------ tmpget interface
                   5682: sub tmpget {
1.688     albertel 5683:     my ($token,$server)=@_;
                   5684:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5685:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5686:     my %returnhash;
                   5687:     foreach my $item (split(/\&/,$rep)) {
                   5688: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5689:         next if ($key =~ /^error: 2 /);
1.667     albertel 5690: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5691:     }
                   5692:     return %returnhash;
                   5693: }
                   5694: 
1.1113    raeburn  5695: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5696: sub tmpdel {
                   5697:     my ($token,$server)=@_;
                   5698:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5699:     return &reply("tmpdel:$token",$server);
                   5700: }
                   5701: 
1.1172.2.13  raeburn  5702: # ------------------------------------------------------------ get_timebased_id
                   5703: 
                   5704: sub get_timebased_id {
                   5705:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5706:         $maxtries) = @_;
                   5707:     my ($newid,$error,$dellock);
                   5708:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5709:         return ('','ok','invalid call to get suffix');
                   5710:     }
                   5711: 
                   5712: # set defaults for any optional args for which values were not supplied
                   5713:     if ($who eq '') {
                   5714:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5715:     }
                   5716:     if (!$locktries) {
                   5717:         $locktries = 3;
                   5718:     }
                   5719:     if (!$maxtries) {
                   5720:         $maxtries = 10;
                   5721:     }
                   5722: 
                   5723:     if (($cdom eq '') || ($cnum eq '')) {
                   5724:         if ($env{'request.course.id'}) {
                   5725:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5726:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5727:         }
                   5728:         if (($cdom eq '') || ($cnum eq '')) {
                   5729:             return ('','ok','call to get suffix not in course context');
                   5730:         }
                   5731:     }
                   5732: 
                   5733: # construct locking item
                   5734:     my $lockhash = {
                   5735:                       $prefix."\0".'locked_'.$keyid => $who,
                   5736:                    };
                   5737:     my $tries = 0;
                   5738: 
                   5739: # attempt to get lock on nohist_$namespace file
                   5740:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5741:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5742:         $tries ++;
                   5743:         sleep 1;
                   5744:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5745:     }
                   5746: 
                   5747: # attempt to get unique identifier, based on current timestamp
                   5748:     if ($gotlock eq 'ok') {
                   5749:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5750:         my $id = time;
                   5751:         $newid = $id;
                   5752:         my $idtries = 0;
                   5753:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5754:             if ($idtype eq 'concat') {
                   5755:                 $newid = $id.$idtries;
                   5756:             } else {
                   5757:                 $newid ++;
                   5758:             }
                   5759:             $idtries ++;
                   5760:         }
                   5761:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5762:             my %new_item =  (
                   5763:                               $prefix."\0".$newid => $who,
                   5764:                             );
                   5765:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5766:                                                  $cdom,$cnum);
                   5767:             if ($putresult ne 'ok') {
                   5768:                 undef($newid);
                   5769:                 $error = 'error saving new item: '.$putresult;
                   5770:             }
                   5771:         } else {
                   5772:              $error = ('error: no unique suffix available for the new item ');
                   5773:         }
                   5774: #  remove lock
                   5775:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5776:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5777:     } else {
                   5778:         $error = "error: could not obtain lockfile\n";
                   5779:         $dellock = 'ok';
                   5780:     }
                   5781:     return ($newid,$dellock,$error);
                   5782: }
                   5783: 
1.765     albertel 5784: # -------------------------------------------------- portfolio access checking
                   5785: 
                   5786: sub portfolio_access {
1.766     albertel 5787:     my ($requrl) = @_;
1.765     albertel 5788:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5789:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5790:     if ($result) {
                   5791:         my %setters;
                   5792:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5793:             my ($startblock,$endblock) =
                   5794:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5795:             if ($startblock && $endblock) {
                   5796:                 return 'B';
                   5797:             }
                   5798:         } else {
                   5799:             my ($startblock,$endblock) =
                   5800:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5801:             if ($startblock && $endblock) {
                   5802:                 return 'B';
                   5803:             }
                   5804:         }
                   5805:     }
1.765     albertel 5806:     if ($result eq 'ok') {
1.766     albertel 5807:        return 'F';
1.765     albertel 5808:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5809:        return 'A';
1.765     albertel 5810:     }
1.766     albertel 5811:     return '';
1.765     albertel 5812: }
                   5813: 
                   5814: sub get_portfolio_access {
1.767     albertel 5815:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5816: 
                   5817:     if (!ref($access_hash)) {
                   5818: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5819: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5820: 						   $file_name);
                   5821: 	$access_hash = $access_controls{$file_name};
                   5822:     }
                   5823: 
1.765     albertel 5824:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5825:     my $now = time;
                   5826:     if (ref($access_hash) eq 'HASH') {
                   5827:         foreach my $key (keys(%{$access_hash})) {
                   5828:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5829:             if ($start > $now) {
                   5830:                 next;
                   5831:             }
                   5832:             if ($end && $end<$now) {
                   5833:                 next;
                   5834:             }
                   5835:             if ($scope eq 'public') {
                   5836:                 $public = $key;
                   5837:                 last;
                   5838:             } elsif ($scope eq 'guest') {
                   5839:                 $guest = $key;
                   5840:             } elsif ($scope eq 'domains') {
                   5841:                 push(@domains,$key);
                   5842:             } elsif ($scope eq 'users') {
                   5843:                 push(@users,$key);
                   5844:             } elsif ($scope eq 'course') {
                   5845:                 push(@courses,$key);
                   5846:             } elsif ($scope eq 'group') {
                   5847:                 push(@groups,$key);
                   5848:             }
                   5849:         }
                   5850:         if ($public) {
                   5851:             return 'ok';
                   5852:         }
                   5853:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5854:             if ($guest) {
                   5855:                 return $guest;
                   5856:             }
                   5857:         } else {
                   5858:             if (@domains > 0) {
                   5859:                 foreach my $domkey (@domains) {
                   5860:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5861:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5862:                             return 'ok';
                   5863:                         }
                   5864:                     }
                   5865:                 }
                   5866:             }
                   5867:             if (@users > 0) {
                   5868:                 foreach my $userkey (@users) {
1.865     raeburn  5869:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5870:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5871:                             if (ref($item) eq 'HASH') {
                   5872:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5873:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5874:                                     return 'ok';
                   5875:                                 }
                   5876:                             }
                   5877:                         }
                   5878:                     } 
1.765     albertel 5879:                 }
                   5880:             }
                   5881:             my %roleshash;
                   5882:             my @courses_and_groups = @courses;
                   5883:             push(@courses_and_groups,@groups); 
                   5884:             if (@courses_and_groups > 0) {
                   5885:                 my (%allgroups,%allroles); 
                   5886:                 my ($start,$end,$role,$sec,$group);
                   5887:                 foreach my $envkey (%env) {
1.1060    raeburn  5888:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5889:                         my $cid = $2.'_'.$3; 
                   5890:                         if ($1 eq 'gr') {
                   5891:                             $group = $4;
                   5892:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5893:                         } else {
                   5894:                             if ($4 eq '') {
                   5895:                                 $sec = 'none';
                   5896:                             } else {
                   5897:                                 $sec = $4;
                   5898:                             }
                   5899:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5900:                         }
1.811     albertel 5901:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5902:                         my $cid = $2.'_'.$3;
                   5903:                         if ($4 eq '') {
                   5904:                             $sec = 'none';
                   5905:                         } else {
                   5906:                             $sec = $4;
                   5907:                         }
                   5908:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5909:                     }
                   5910:                 }
                   5911:                 if (keys(%allroles) == 0) {
                   5912:                     return;
                   5913:                 }
                   5914:                 foreach my $key (@courses_and_groups) {
                   5915:                     my %content = %{$$access_hash{$key}};
                   5916:                     my $cnum = $content{'number'};
                   5917:                     my $cdom = $content{'domain'};
                   5918:                     my $cid = $cdom.'_'.$cnum;
                   5919:                     if (!exists($allroles{$cid})) {
                   5920:                         next;
                   5921:                     }    
                   5922:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5923:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5924:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5925:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5926:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5927:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5928:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5929:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5930:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5931:                                         if (grep/^all$/,@sections) {
                   5932:                                             return 'ok';
                   5933:                                         } else {
                   5934:                                             if (grep/^$sec$/,@sections) {
                   5935:                                                 return 'ok';
                   5936:                                             }
                   5937:                                         }
                   5938:                                     }
                   5939:                                 }
                   5940:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5941:                                     if (grep/^none$/,@groups) {
                   5942:                                         return 'ok';
                   5943:                                     }
                   5944:                                 } else {
                   5945:                                     if (grep/^all$/,@groups) {
                   5946:                                         return 'ok';
                   5947:                                     } 
                   5948:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5949:                                         if (grep/^$group$/,@groups) {
                   5950:                                             return 'ok';
                   5951:                                         }
                   5952:                                     }
                   5953:                                 } 
                   5954:                             }
                   5955:                         }
                   5956:                     }
                   5957:                 }
                   5958:             }
                   5959:             if ($guest) {
                   5960:                 return $guest;
                   5961:             }
                   5962:         }
                   5963:     }
                   5964:     return;
                   5965: }
                   5966: 
                   5967: sub course_group_datechecker {
                   5968:     my ($dates,$now,$status) = @_;
                   5969:     my ($start,$end) = split(/\./,$dates);
                   5970:     if (!$start && !$end) {
                   5971:         return 'ok';
                   5972:     }
                   5973:     if (grep/^active$/,@{$status}) {
                   5974:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5975:             return 'ok';
                   5976:         }
                   5977:     }
                   5978:     if (grep/^previous$/,@{$status}) {
                   5979:         if ($end > $now ) {
                   5980:             return 'ok';
                   5981:         }
                   5982:     }
                   5983:     if (grep/^future$/,@{$status}) {
                   5984:         if ($start > $now) {
                   5985:             return 'ok';
                   5986:         }
                   5987:     }
                   5988:     return; 
                   5989: }
                   5990: 
                   5991: sub parse_portfolio_url {
                   5992:     my ($url) = @_;
                   5993: 
                   5994:     my ($type,$udom,$unum,$group,$file_name);
                   5995:     
1.823     albertel 5996:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5997: 	$type = 1;
                   5998:         $udom = $1;
                   5999:         $unum = $2;
                   6000:         $file_name = $3;
1.823     albertel 6001:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6002: 	$type = 2;
                   6003:         $udom = $1;
                   6004:         $unum = $2;
                   6005:         $group = $3;
                   6006:         $file_name = $3.'/'.$4;
                   6007:     }
                   6008:     if (wantarray) {
                   6009: 	return ($type,$udom,$unum,$file_name,$group);
                   6010:     }
                   6011:     return $type;
                   6012: }
                   6013: 
                   6014: sub is_portfolio_url {
                   6015:     my ($url) = @_;
                   6016:     return scalar(&parse_portfolio_url($url));
                   6017: }
                   6018: 
1.798     raeburn  6019: sub is_portfolio_file {
                   6020:     my ($file) = @_;
1.820     raeburn  6021:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6022:         return 1;
                   6023:     }
                   6024:     return;
                   6025: }
                   6026: 
1.976     raeburn  6027: sub usertools_access {
1.1084    raeburn  6028:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6029:     my ($access,%tools);
                   6030:     if ($context eq '') {
                   6031:         $context = 'tools';
                   6032:     }
                   6033:     if ($context eq 'requestcourses') {
                   6034:         %tools = (
                   6035:                       official   => 1,
                   6036:                       unofficial => 1,
1.1006    raeburn  6037:                       community  => 1,
1.985     raeburn  6038:                  );
1.1172.2.9  raeburn  6039:     } elsif ($context eq 'requestauthor') {
                   6040:         %tools = (
                   6041:                       requestauthor => 1,
                   6042:                  );
1.985     raeburn  6043:     } else {
                   6044:         %tools = (
                   6045:                       aboutme   => 1,
                   6046:                       blog      => 1,
1.1172.2.6  raeburn  6047:                       webdav    => 1,
1.985     raeburn  6048:                       portfolio => 1,
                   6049:                  );
                   6050:     }
1.976     raeburn  6051:     return if (!defined($tools{$tool}));
                   6052: 
                   6053:     if ((!defined($udom)) || (!defined($uname))) {
                   6054:         $udom = $env{'user.domain'};
                   6055:         $uname = $env{'user.name'};
                   6056:     }
                   6057: 
1.978     raeburn  6058:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6059:         if ($action ne 'reload') {
1.985     raeburn  6060:             if ($context eq 'requestcourses') {
                   6061:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6062:             } elsif ($context eq 'requestauthor') {
                   6063:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6064:             } else {
                   6065:                 return $env{'environment.availabletools.'.$tool};
                   6066:             }
                   6067:         }
1.976     raeburn  6068:     }
                   6069: 
1.1172.2.9  raeburn  6070:     my ($toolstatus,$inststatus,$envkey);
                   6071:     if ($context eq 'requestauthor') {
                   6072:         $envkey = $context;
                   6073:     } else {
                   6074:         $envkey = $context.'.'.$tool;
                   6075:     }
1.976     raeburn  6076: 
1.985     raeburn  6077:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6078:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6079:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6080:         $inststatus = $env{'environment.inststatus'};
                   6081:     } else {
1.1084    raeburn  6082:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6083:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6084:             $inststatus = $userenvref->{'inststatus'};
                   6085:         } else {
1.1172.2.9  raeburn  6086:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6087:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6088:             $inststatus = $userenv{'inststatus'};
                   6089:         }
1.976     raeburn  6090:     }
                   6091: 
                   6092:     if ($toolstatus ne '') {
                   6093:         if ($toolstatus) {
                   6094:             $access = 1;
                   6095:         } else {
                   6096:             $access = 0;
                   6097:         }
                   6098:         return $access;
                   6099:     }
                   6100: 
1.1084    raeburn  6101:     my ($is_adv,%domdef);
                   6102:     if (ref($is_advref) eq 'HASH') {
                   6103:         $is_adv = $is_advref->{'is_adv'};
                   6104:     } else {
                   6105:         $is_adv = &is_advanced_user($udom,$uname);
                   6106:     }
                   6107:     if (ref($domdefref) eq 'HASH') {
                   6108:         %domdef = %{$domdefref};
                   6109:     } else {
                   6110:         %domdef = &get_domain_defaults($udom);
                   6111:     }
1.976     raeburn  6112:     if (ref($domdef{$tool}) eq 'HASH') {
                   6113:         if ($is_adv) {
                   6114:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6115:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6116:                     $access = 1;
                   6117:                 } else {
                   6118:                     $access = 0;
                   6119:                 }
                   6120:                 return $access;
                   6121:             }
                   6122:         }
                   6123:         if ($inststatus ne '') {
                   6124:             my ($hasaccess,$hasnoaccess);
                   6125:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6126:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6127:                     if ($domdef{$tool}{$affiliation}) {
                   6128:                         $hasaccess = 1;
                   6129:                     } else {
                   6130:                         $hasnoaccess = 1;
                   6131:                     }
                   6132:                 }
                   6133:             }
                   6134:             if ($hasaccess || $hasnoaccess) {
                   6135:                 if ($hasaccess) {
                   6136:                     $access = 1;
                   6137:                 } elsif ($hasnoaccess) {
                   6138:                     $access = 0; 
                   6139:                 }
                   6140:                 return $access;
                   6141:             }
                   6142:         } else {
                   6143:             if ($domdef{$tool}{'default'} ne '') {
                   6144:                 if ($domdef{$tool}{'default'}) {
                   6145:                     $access = 1;
                   6146:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6147:                     $access = 0;
                   6148:                 }
                   6149:                 return $access;
                   6150:             }
                   6151:         }
                   6152:     } else {
1.1172.2.6  raeburn  6153:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6154:             $access = 1;
                   6155:         } else {
                   6156:             $access = 0;
                   6157:         }
1.976     raeburn  6158:         return $access;
                   6159:     }
                   6160: }
                   6161: 
1.1050    raeburn  6162: sub is_course_owner {
                   6163:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6164:     if (($udom eq '') || ($uname eq '')) {
                   6165:         $udom = $env{'user.domain'};
                   6166:         $uname = $env{'user.name'};
                   6167:     }
                   6168:     unless (($udom eq '') || ($uname eq '')) {
                   6169:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6170:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6171:                 return 1;
                   6172:             } else {
                   6173:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6174:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6175:                     return 1;
                   6176:                 }
                   6177:             }
                   6178:         }
                   6179:     }
                   6180:     return;
                   6181: }
                   6182: 
1.976     raeburn  6183: sub is_advanced_user {
                   6184:     my ($udom,$uname) = @_;
1.1085    raeburn  6185:     if ($udom ne '' && $uname ne '') {
                   6186:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6187:             if (wantarray) {
                   6188:                 return ($env{'user.adv'},$env{'user.author'});
                   6189:             } else {
                   6190:                 return $env{'user.adv'};
                   6191:             }
1.1085    raeburn  6192:         }
                   6193:     }
1.976     raeburn  6194:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6195:     my %allroles;
1.1128    raeburn  6196:     my ($is_adv,$is_author);
1.976     raeburn  6197:     foreach my $role (keys(%roleshash)) {
                   6198:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6199:         my $area = '/'.$tdomain.'/'.$trest;
                   6200:         if ($sec ne '') {
                   6201:             $area .= '/'.$sec;
                   6202:         }
                   6203:         if (($area ne '') && ($trole ne '')) {
                   6204:             my $spec=$trole.'.'.$area;
                   6205:             if ($trole =~ /^cr\//) {
                   6206:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6207:             } elsif ($trole ne 'gr') {
                   6208:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6209:             }
1.1128    raeburn  6210:             if ($trole eq 'au') {
                   6211:                 $is_author = 1;
                   6212:             }
1.976     raeburn  6213:         }
                   6214:     }
                   6215:     foreach my $role (keys(%allroles)) {
                   6216:         last if ($is_adv);
                   6217:         foreach my $item (split(/:/,$allroles{$role})) {
                   6218:             if ($item ne '') {
                   6219:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6220:                 if ($privilege eq 'adv') {
                   6221:                     $is_adv = 1;
                   6222:                     last;
                   6223:                 }
                   6224:             }
                   6225:         }
                   6226:     }
1.1128    raeburn  6227:     if (wantarray) {
                   6228:         return ($is_adv,$is_author);
                   6229:     }
1.976     raeburn  6230:     return $is_adv;
                   6231: }
1.798     raeburn  6232: 
1.1035    raeburn  6233: sub check_can_request {
1.1036    raeburn  6234:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6235:     my $canreq = 0;
                   6236:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6237:     my @options = ('approval','validate','autolimit');
                   6238:     my $optregex = join('|',@options);
                   6239:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6240:         foreach my $type (@{$types}) {
                   6241:             if (&usertools_access($env{'user.name'},
                   6242:                                   $env{'user.domain'},
                   6243:                                   $type,undef,'requestcourses')) {
                   6244:                 $canreq ++;
1.1036    raeburn  6245:                 if (ref($request_domains) eq 'HASH') {
                   6246:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6247:                 }
1.1035    raeburn  6248:                 if ($dom eq $env{'user.domain'}) {
                   6249:                     $can_request->{$type} = 1;
                   6250:                 }
                   6251:             }
                   6252:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6253:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6254:                 if (@curr > 0) {
1.1036    raeburn  6255:                     foreach my $item (@curr) {
                   6256:                         if (ref($request_domains) eq 'HASH') {
                   6257:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6258:                             if ($otherdom ne '') {
                   6259:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6260:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6261:                                         push(@{$request_domains->{$type}},$otherdom);
                   6262:                                     }
                   6263:                                 } else {
                   6264:                                     push(@{$request_domains->{$type}},$otherdom);
                   6265:                                 }
                   6266:                             }
                   6267:                         }
                   6268:                     }
                   6269:                     unless($dom eq $env{'user.domain'}) {
                   6270:                         $canreq ++;
1.1035    raeburn  6271:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6272:                             $can_request->{$type} = 1;
                   6273:                         }
                   6274:                     }
                   6275:                 }
                   6276:             }
                   6277:         }
                   6278:     }
                   6279:     return $canreq;
                   6280: }
                   6281: 
1.341     www      6282: # ---------------------------------------------- Custom access rule evaluation
                   6283: 
                   6284: sub customaccess {
                   6285:     my ($priv,$uri)=@_;
1.807     albertel 6286:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6287:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6288:     $udom = &LONCAPA::clean_domain($udom);
                   6289:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6290:     my $access=0;
1.800     albertel 6291:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6292: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6293: 	if ($type eq 'user') {
                   6294: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6295: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6296: 		if ($tdom) {
                   6297: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6298: 		}
1.896     albertel 6299: 		if ($tuname) {
                   6300: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6301: 		}
                   6302: 		$access=($effect eq 'allow');
                   6303: 		last;
                   6304: 	    }
                   6305: 	} else {
                   6306: 	    if ($role) {
                   6307: 		if ($role ne $urole) { next; }
                   6308: 	    }
                   6309: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6310: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6311: 		if ($tdom) {
                   6312: 		    if ($tdom ne $udom) { next; }
                   6313: 		}
                   6314: 		if ($tcrs) {
                   6315: 		    if ($tcrs ne $ucrs) { next; }
                   6316: 		}
                   6317: 		if ($tsec) {
                   6318: 		    if ($tsec ne $usec) { next; }
                   6319: 		}
                   6320: 		$access=($effect eq 'allow');
                   6321: 		last;
                   6322: 	    }
                   6323: 	    if ($realm eq '' && $role eq '') {
                   6324: 		$access=($effect eq 'allow');
                   6325: 	    }
1.402     bowersj2 6326: 	}
1.341     www      6327:     }
                   6328:     return $access;
                   6329: }
                   6330: 
1.103     harris41 6331: # ------------------------------------------------- Check for a user privilege
1.12      www      6332: 
                   6333: sub allowed {
1.810     raeburn  6334:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6335:     my $ver_orguri=$uri;
1.439     www      6336:     $uri=&deversion($uri);
1.152     www      6337:     my $orguri=$uri;
1.52      www      6338:     $uri=&declutter($uri);
1.809     raeburn  6339: 
1.810     raeburn  6340:     if ($priv eq 'evb') {
                   6341: # Evade communication block restrictions for specified role in a course
                   6342:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6343:             return $1;
                   6344:         } else {
                   6345:             return;
                   6346:         }
                   6347:     }
                   6348: 
1.620     albertel 6349:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6350: # Free bre access to adm and meta resources
1.775     albertel 6351:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6352: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6353: 	&& ($priv eq 'bre')) {
1.14      www      6354: 	return 'F';
1.159     www      6355:     }
                   6356: 
1.545     banghart 6357: # Free bre access to user's own portfolio contents
1.714     raeburn  6358:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6359:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6360: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6361:         my %setters;
                   6362:         my ($startblock,$endblock) = 
                   6363:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6364:         if ($startblock && $endblock) {
                   6365:             return 'B';
                   6366:         } else {
                   6367:             return 'F';
                   6368:         }
1.545     banghart 6369:     }
                   6370: 
1.762     raeburn  6371: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6372:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6373:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6374:         if (exists($env{'request.course.id'})) {
                   6375:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6376:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6377:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6378:                 my $courseprivid=$env{'request.course.id'};
                   6379:                 $courseprivid=~s/\_/\//;
                   6380:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6381:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6382:                     return $1; 
1.762     raeburn  6383:                 } else {
                   6384:                     if ($env{'request.course.sec'}) {
                   6385:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6386:                     }
                   6387:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6388:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6389:                         return $2;
                   6390:                     }
1.714     raeburn  6391:                 }
                   6392:             }
                   6393:         }
                   6394:     }
                   6395: 
1.159     www      6396: # Free bre to public access
                   6397: 
                   6398:     if ($priv eq 'bre') {
1.238     www      6399:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6400: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6401:            return 'F'; 
                   6402:         }
1.238     www      6403:         if ($copyright eq 'priv') {
                   6404:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6405: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6406: 		return '';
                   6407:             }
                   6408:         }
                   6409:         if ($copyright eq 'domain') {
                   6410:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6411: 	    unless (($env{'user.domain'} eq $1) ||
                   6412:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6413: 		return '';
                   6414:             }
1.262     matthew  6415:         }
1.620     albertel 6416:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6417:             # Library role, so allow browsing of resources in this domain.
                   6418:             return 'F';
1.238     www      6419:         }
1.341     www      6420:         if ($copyright eq 'custom') {
                   6421: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6422:         }
1.14      www      6423:     }
1.264     matthew  6424:     # Domain coordinator is trying to create a course
1.620     albertel 6425:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6426:         # uri is the requested domain in this case.
                   6427:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6428:         # a role of dc for the domain in question.
1.620     albertel 6429:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6430:     }
1.29      www      6431: 
1.52      www      6432:     my $thisallowed='';
                   6433:     my $statecond=0;
                   6434:     my $courseprivid='';
                   6435: 
1.1039    raeburn  6436:     my $ownaccess;
1.1043    raeburn  6437:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6438:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6439:         if ($uri eq '') {
                   6440:             $ownaccess = 1;
                   6441:         } else {
                   6442:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6443:                 my $udom = $env{'user.domain'};
                   6444:                 my $uname = $env{'user.name'};
                   6445:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6446:                     $ownaccess = 1;
1.1040    raeburn  6447:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6448:                     unless ($uri =~ m{\.\./}) {
                   6449:                         $ownaccess = 1;
                   6450:                     }
                   6451:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6452:                     my $now = time;
                   6453:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6454:                         my $adom = $1;
                   6455:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6456:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6457:                                 my ($start,$end) = split('.',$env{$key});
                   6458:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6459:                                     $ownaccess = 1;
                   6460:                                     last;
                   6461:                                 }
                   6462:                             }
                   6463:                         }
                   6464:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6465:                         my $adom = $1;
                   6466:                         my $aname = $2;
1.1042    raeburn  6467:                         foreach my $role ('ca','aa') { 
                   6468:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6469:                                 my ($start,$end) =
                   6470:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6471:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6472:                                     $ownaccess = 1;
                   6473:                                     last;
                   6474:                                 }
1.1039    raeburn  6475:                             }
                   6476:                         }
                   6477:                     }
                   6478:                 }
                   6479:             }
                   6480:         }
                   6481:     }
                   6482: 
1.52      www      6483: # Course
                   6484: 
1.620     albertel 6485:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6486:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6487:             $thisallowed.=$1;
                   6488:         }
1.52      www      6489:     }
1.29      www      6490: 
1.52      www      6491: # Domain
                   6492: 
1.620     albertel 6493:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6494:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6495:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6496:             $thisallowed.=$1;
                   6497:         }
1.12      www      6498:     }
1.52      www      6499: 
1.1141    raeburn  6500: # User who is not author or co-author might still be able to edit
                   6501: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6502:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6503:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6504:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6505:             $thisallowed.=$1;
                   6506:         }
                   6507:     }
                   6508: 
1.52      www      6509: # Course: uri itself is a course
1.66      www      6510:     my $courseuri=$uri;
                   6511:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6512:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6513: 
1.620     albertel 6514:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6515:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6516:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6517:             $thisallowed.=$1;
                   6518:         }
1.12      www      6519:     }
1.29      www      6520: 
1.665     albertel 6521: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6522: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6523:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6524: 	$thisallowed='';
1.671     raeburn  6525:         my ($match)=&is_on_map($uri);
                   6526:         if ($match) {
                   6527:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6528:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6529:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6530:                 if (@blockers > 0) {
                   6531:                     $thisallowed = 'B';
                   6532:                 } else {
                   6533:                     $thisallowed.=$1;
                   6534:                 }
1.671     raeburn  6535:             }
                   6536:         } else {
1.705     albertel 6537:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6538:             if ($refuri) {
                   6539:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6540:                     $thisallowed='F';
1.671     raeburn  6541:                 } else {
                   6542:                     $refuri=&declutter($refuri);
                   6543:                     my ($match) = &is_on_map($refuri);
                   6544:                     if ($match) {
1.1162    raeburn  6545:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6546:                         if (@blockers > 0) {
                   6547:                             $thisallowed = 'B';
                   6548:                         } else {
                   6549:                             $thisallowed='F';
                   6550:                         }
1.671     raeburn  6551:                     }
1.669     raeburn  6552:                 }
1.671     raeburn  6553:             }
                   6554:         }
1.314     www      6555:     }
1.492     albertel 6556: 
1.766     albertel 6557:     if ($priv eq 'bre'
                   6558: 	&& $thisallowed ne 'F' 
                   6559: 	&& $thisallowed ne '2'
                   6560: 	&& &is_portfolio_url($uri)) {
                   6561: 	$thisallowed = &portfolio_access($uri);
                   6562:     }
                   6563:     
1.52      www      6564: # Full access at system, domain or course-wide level? Exit.
1.29      www      6565:     if ($thisallowed=~/F/) {
                   6566: 	return 'F';
                   6567:     }
                   6568: 
1.52      www      6569: # If this is generating or modifying users, exit with special codes
1.29      www      6570: 
1.643     www      6571:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6572: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6573: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6574: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6575: 	    unless ($auname) { return $thisallowed; }
                   6576: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6577: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6578: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6579: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6580: 	}
1.52      www      6581: 	return $thisallowed;
                   6582:     }
                   6583: #
1.103     harris41 6584: # Gathered so far: system, domain and course wide privileges
1.52      www      6585: #
                   6586: # Course: See if uri or referer is an individual resource that is part of 
                   6587: # the course
                   6588: 
1.620     albertel 6589:     if ($env{'request.course.id'}) {
1.232     www      6590: 
1.620     albertel 6591:        $courseprivid=$env{'request.course.id'};
                   6592:        if ($env{'request.course.sec'}) {
                   6593:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6594:        }
                   6595:        $courseprivid=~s/\_/\//;
                   6596:        my $checkreferer=1;
1.232     www      6597:        my ($match,$cond)=&is_on_map($uri);
                   6598:        if ($match) {
                   6599:            $statecond=$cond;
1.620     albertel 6600:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6601:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6602:                my $value = $1;
                   6603:                if ($priv eq 'bre') {
                   6604:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6605:                    if (@blockers > 0) {
                   6606:                        $thisallowed = 'B';
                   6607:                    } else {
                   6608:                        $thisallowed.=$value;
                   6609:                    }
                   6610:                } else {
                   6611:                    $thisallowed.=$value;
                   6612:                }
1.52      www      6613:                $checkreferer=0;
                   6614:            }
1.29      www      6615:        }
1.83      www      6616:        
1.148     www      6617:        if ($checkreferer) {
1.620     albertel 6618: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6619:             unless ($refuri) {
1.800     albertel 6620:                 foreach my $key (keys(%env)) {
                   6621: 		    if ($key=~/^httpref\..*\*/) {
                   6622: 			my $pattern=$key;
1.156     www      6623:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6624:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6625:                         $pattern=~s/\//\\\//g;
1.152     www      6626:                         if ($orguri=~/$pattern/) {
1.800     albertel 6627: 			    $refuri=$env{$key};
1.148     www      6628:                         }
                   6629:                     }
1.191     harris41 6630:                 }
1.148     www      6631:             }
1.232     www      6632: 
1.148     www      6633:          if ($refuri) { 
1.152     www      6634: 	  $refuri=&declutter($refuri);
1.232     www      6635:           my ($match,$cond)=&is_on_map($refuri);
                   6636:             if ($match) {
                   6637:               my $refstatecond=$cond;
1.620     albertel 6638:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6639:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6640:                   my $value = $1;
                   6641:                   if ($priv eq 'bre') {
                   6642:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6643:                       if (@blockers > 0) {
                   6644:                           $thisallowed = 'B';
                   6645:                       } else {
                   6646:                           $thisallowed.=$value;
                   6647:                       }
                   6648:                   } else {
                   6649:                       $thisallowed.=$value;
                   6650:                   }
1.53      www      6651:                   $uri=$refuri;
                   6652:                   $statecond=$refstatecond;
1.52      www      6653:               }
                   6654:           }
1.148     www      6655:         }
1.29      www      6656:        }
1.52      www      6657:    }
1.29      www      6658: 
1.52      www      6659: #
1.103     harris41 6660: # Gathered now: all privileges that could apply, and condition number
1.52      www      6661: # 
                   6662: #
                   6663: # Full or no access?
                   6664: #
1.29      www      6665: 
1.52      www      6666:     if ($thisallowed=~/F/) {
                   6667: 	return 'F';
                   6668:     }
1.29      www      6669: 
1.52      www      6670:     unless ($thisallowed) {
                   6671:         return '';
                   6672:     }
1.29      www      6673: 
1.52      www      6674: # Restrictions exist, deal with them
                   6675: #
                   6676: #   C:according to course preferences
                   6677: #   R:according to resource settings
                   6678: #   L:unless locked
                   6679: #   X:according to user session state
                   6680: #
                   6681: 
                   6682: # Possibly locked functionality, check all courses
1.54      www      6683: # Locks might take effect only after 10 minutes cache expiration for other
                   6684: # courses, and 2 minutes for current course
1.52      www      6685: 
                   6686:     my $envkey;
                   6687:     if ($thisallowed=~/L/) {
1.1000    raeburn  6688:         foreach $envkey (keys(%env)) {
1.54      www      6689:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6690:                my $courseid=$2;
                   6691:                my $roleid=$1.'.'.$2;
1.92      www      6692:                $courseid=~s/^\///;
1.54      www      6693:                my $expiretime=600;
1.620     albertel 6694:                if ($env{'request.role'} eq $roleid) {
1.54      www      6695: 		  $expiretime=120;
                   6696:                }
                   6697: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6698:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6699:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6700: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6701:                }
1.620     albertel 6702:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6703:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6704: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6705:                        &log($env{'user.domain'},$env{'user.name'},
                   6706:                             $env{'user.home'},
1.57      www      6707:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6708:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6709:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6710: 		       return '';
                   6711:                    }
                   6712:                }
1.620     albertel 6713:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6714:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6715: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6716:                        &log($env{'user.domain'},$env{'user.name'},
                   6717:                             $env{'user.home'},
1.57      www      6718:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6719:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6720:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6721: 		       return '';
                   6722:                    }
                   6723:                }
                   6724: 	   }
1.29      www      6725:        }
1.52      www      6726:     }
                   6727:    
                   6728: #
                   6729: # Rest of the restrictions depend on selected course
                   6730: #
                   6731: 
1.620     albertel 6732:     unless ($env{'request.course.id'}) {
1.766     albertel 6733: 	if ($thisallowed eq 'A') {
                   6734: 	    return 'A';
1.814     raeburn  6735:         } elsif ($thisallowed eq 'B') {
                   6736:             return 'B';
1.766     albertel 6737: 	} else {
                   6738: 	    return '1';
                   6739: 	}
1.52      www      6740:     }
1.29      www      6741: 
1.52      www      6742: #
                   6743: # Now user is definitely in a course
                   6744: #
1.53      www      6745: 
                   6746: 
                   6747: # Course preferences
                   6748: 
                   6749:    if ($thisallowed=~/C/) {
1.620     albertel 6750:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6751:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6752:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6753: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6754: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6755: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6756: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6757: 			$env{'request.course.id'});
                   6758: 	   }
1.237     www      6759:            return '';
                   6760:        }
                   6761: 
1.620     albertel 6762:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6763: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6764: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6765: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6766: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6767: 			$env{'request.course.id'});
                   6768: 	   }
1.54      www      6769:            return '';
                   6770:        }
1.53      www      6771:    }
                   6772: 
                   6773: # Resource preferences
                   6774: 
                   6775:    if ($thisallowed=~/R/) {
1.620     albertel 6776:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6777:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6778: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6779: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6780: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6781: 	   }
                   6782: 	   return '';
1.54      www      6783:        }
1.53      www      6784:    }
1.30      www      6785: 
1.246     www      6786: # Restricted by state or randomout?
1.30      www      6787: 
1.52      www      6788:    if ($thisallowed=~/X/) {
1.620     albertel 6789:       if ($env{'acc.randomout'}) {
1.579     albertel 6790: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6791:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6792:             return ''; 
                   6793:          }
1.247     www      6794:       }
                   6795:       if (&condval($statecond)) {
1.52      www      6796: 	 return '2';
                   6797:       } else {
                   6798:          return '';
                   6799:       }
                   6800:    }
1.30      www      6801: 
1.766     albertel 6802:     if ($thisallowed eq 'A') {
                   6803: 	return 'A';
1.814     raeburn  6804:     } elsif ($thisallowed eq 'B') {
                   6805:         return 'B';
1.766     albertel 6806:     }
1.52      www      6807:    return 'F';
1.232     www      6808: }
1.1162    raeburn  6809: 
1.1172.2.13  raeburn  6810: # ------------------------------------------- Check construction space access
                   6811: 
                   6812: sub constructaccess {
                   6813:     my ($url,$setpriv)=@_;
                   6814: 
                   6815: # We do not allow editing of previous versions of files
                   6816:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6817: 
                   6818: # Get username and domain from URL
                   6819:     my ($ownername,$ownerdomain,$ownerhome);
                   6820: 
                   6821:     ($ownerdomain,$ownername) =
                   6822:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6823: 
                   6824: # The URL does not really point to any authorspace, forget it
                   6825:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6826: 
                   6827: # Now we need to see if the user has access to the authorspace of
                   6828: # $ownername at $ownerdomain
                   6829: 
                   6830:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6831: # Real author for this?
                   6832:        $ownerhome = $env{'user.home'};
                   6833:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6834:           return ($ownername,$ownerdomain,$ownerhome);
                   6835:        }
                   6836:     } else {
                   6837: # Co-author for this?
                   6838:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6839:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6840:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6841:             return ($ownername,$ownerdomain,$ownerhome);
                   6842:         }
                   6843:     }
                   6844: 
                   6845: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6846: # we might as well leave
                   6847:    unless ($setpriv) { return ''; }
                   6848: 
                   6849: # Backdoor access?
                   6850:     my $allowed=&allowed('eco',$ownerdomain);
                   6851: # Nope
                   6852:     unless ($allowed) { return ''; }
                   6853: # Looks like we may have access, but could be locked by the owner of the construction space
                   6854:     if ($allowed eq 'U') {
                   6855:         my %blocked=&get('environment',['domcoord.author'],
                   6856:                          $ownerdomain,$ownername);
                   6857: # Is blocked by owner
                   6858:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6859:     }
                   6860:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6861: # Grant temporary access
                   6862:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6863:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6864:         if (!$update) { $update = $then; }
                   6865:         my $refresh=$env{'user.refresh.time'};
                   6866:         if (!$refresh) { $refresh = $update; }
                   6867:         my $now = time;
                   6868:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6869:                            $now,'ca','constructaccess');
                   6870:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6871:         return($ownername,$ownerdomain,$ownerhome);
                   6872:     }
                   6873: # No business here
                   6874:     return '';
                   6875: }
                   6876: 
1.1162    raeburn  6877: sub get_comm_blocks {
                   6878:     my ($cdom,$cnum) = @_;
                   6879:     if ($cdom eq '' || $cnum eq '') {
                   6880:         return unless ($env{'request.course.id'});
                   6881:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6882:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6883:     }
                   6884:     my %commblocks;
                   6885:     my $hashid=$cdom.'_'.$cnum;
                   6886:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6887:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6888:         %commblocks = %{$blocksref};
                   6889:     } else {
                   6890:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6891:         my $cachetime = 600;
                   6892:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6893:     }
                   6894:     return %commblocks;
                   6895: }
                   6896: 
                   6897: sub has_comm_blocking {
                   6898:     my ($priv,$symb,$uri,$blocks) = @_;
                   6899:     return unless ($env{'request.course.id'});
                   6900:     return unless ($priv eq 'bre');
                   6901:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6902:     my %commblocks;
                   6903:     if (ref($blocks) eq 'HASH') {
                   6904:         %commblocks = %{$blocks};
                   6905:     } else {
                   6906:         %commblocks = &get_comm_blocks();
                   6907:     }
                   6908:     return unless (keys(%commblocks) > 0);
                   6909:     if (!$symb) { $symb=&symbread($uri,1); }
                   6910:     my ($map,$resid,undef)=&decode_symb($symb);
                   6911:     my %tocheck = (
                   6912:                     maps      => $map,
                   6913:                     resources => $symb,
                   6914:                   );
                   6915:     my @blockers;
                   6916:     my $now = time;
1.1163    raeburn  6917:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6918:     foreach my $block (keys(%commblocks)) {
                   6919:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6920:             my ($start,$end) = ($1,$2);
                   6921:             if ($start <= $now && $end >= $now) {
                   6922:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6923:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6924:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6925:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6926:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6927:                                     push(@blockers,$block);
                   6928:                                 }
                   6929:                             }
                   6930:                         }
                   6931:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6932:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6933:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6934:                                     push(@blockers,$block);
                   6935:                                 }
                   6936:                             }
                   6937:                         }
                   6938:                     }
                   6939:                 }
                   6940:             }
                   6941:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6942:             my $item = $1;
1.1163    raeburn  6943:             my @to_test;
1.1162    raeburn  6944:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6945:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6946:                     my $check_interval;
                   6947:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6948:                         my @interval;
                   6949:                         my $type = 'map';
                   6950:                         if ($item eq 'course') {
                   6951:                             $type = 'course';
                   6952:                             @interval=&EXT("resource.0.interval");
                   6953:                         } else {
                   6954:                             if ($item =~ /___\d+___/) {
                   6955:                                 $type = 'resource';
                   6956:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6957:                                 if (ref($navmap)) {                        
                   6958:                                     my $res = $navmap->getBySymb($item); 
                   6959:                                     push(@to_test,$res);
                   6960:                                 }
1.1162    raeburn  6961:                             } else {
                   6962:                                 my $mapsymb = &symbread($item,1);
                   6963:                                 if ($mapsymb) {
                   6964:                                     if (ref($navmap)) {
                   6965:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6966:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6967:                                         foreach my $res (@to_test) {
1.1162    raeburn  6968:                                             my $symb = $res->symb();
                   6969:                                             next if ($symb eq $mapsymb);
                   6970:                                             if ($symb ne '') {
                   6971:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6972:                                                 last;
                   6973:                                             }
                   6974:                                         }
                   6975:                                     }
                   6976:                                 }
                   6977:                             }
                   6978:                         }
                   6979:                         if ($interval[0] =~ /\d+/) {
                   6980:                             my $first_access;
                   6981:                             if ($type eq 'resource') {
                   6982:                                 $first_access=&get_first_access($interval[1],$item);
                   6983:                             } elsif ($type eq 'map') {
                   6984:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6985:                             } else {
                   6986:                                 $first_access=&get_first_access($interval[1]);
                   6987:                             }
                   6988:                             if ($first_access) {
                   6989:                                 my $timesup = $first_access+$interval[0];
                   6990:                                 if ($timesup > $now) {
1.1163    raeburn  6991:                                     foreach my $res (@to_test) {
                   6992:                                         if ($res->is_problem()) {
                   6993:                                             if ($res->completable()) {
                   6994:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6995:                                                     push(@blockers,$block);
                   6996:                                                 }
                   6997:                                                 last;
                   6998:                                             }
                   6999:                                         }
1.1162    raeburn  7000:                                     }
                   7001:                                 }
                   7002:                             }
                   7003:                         }
                   7004:                     }
                   7005:                 }
                   7006:             }
                   7007:         }
                   7008:     }
                   7009:     return @blockers;
                   7010: }
                   7011: 
                   7012: sub check_docs_block {
                   7013:     my ($docsblock,$tocheck) =@_;
                   7014:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7015:         return;
                   7016:     }
                   7017:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7018:         if ($tocheck->{'maps'}) {
                   7019:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7020:                 return 1;
                   7021:             }
                   7022:         }
                   7023:     }
                   7024:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7025:         if ($tocheck->{'resources'}) {
                   7026:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7027:                 return 1;
                   7028:             }
                   7029:         }
                   7030:     }
                   7031:     return;
                   7032: }
                   7033: 
1.1133    foxr     7034: #
                   7035: #   Removes the versino from a URI and
                   7036: #   splits it in to its filename and path to the filename.
                   7037: #   Seems like File::Basename could have done this more clearly.
                   7038: #   Parameters:
                   7039: #      $uri   - input URI
                   7040: #   Returns:
                   7041: #     Two element list consisting of 
                   7042: #     $pathname  - the URI up to and excluding the trailing /
                   7043: #     $filename  - The part of the URI following the last /
                   7044: #  NOTE:
                   7045: #    Another realization of this is simply:
                   7046: #    use File::Basename;
                   7047: #    ...
                   7048: #    $uri = shift;
                   7049: #    $filename = basename($uri);
                   7050: #    $path     = dirname($uri);
                   7051: #    return ($filename, $path);
                   7052: #
                   7053: #     The implementation below is probably faster however.
                   7054: #
1.710     albertel 7055: sub split_uri_for_cond {
                   7056:     my $uri=&deversion(&declutter(shift));
                   7057:     my @uriparts=split(/\//,$uri);
                   7058:     my $filename=pop(@uriparts);
                   7059:     my $pathname=join('/',@uriparts);
                   7060:     return ($pathname,$filename);
                   7061: }
1.232     www      7062: # --------------------------------------------------- Is a resource on the map?
                   7063: 
                   7064: sub is_on_map {
1.710     albertel 7065:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7066:     #Trying to find the conditional for the file
1.620     albertel 7067:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7068: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7069:     if ($match) {
1.289     bowersj2 7070: 	return (1,$1);
                   7071:     } else {
1.434     www      7072: 	return (0,0);
1.289     bowersj2 7073:     }
1.12      www      7074: }
                   7075: 
1.427     www      7076: # --------------------------------------------------------- Get symb from alias
                   7077: 
                   7078: sub get_symb_from_alias {
                   7079:     my $symb=shift;
                   7080:     my ($map,$resid,$url)=&decode_symb($symb);
                   7081: # Already is a symb
                   7082:     if ($url) { return $symb; }
                   7083: # Must be an alias
                   7084:     my $aliassymb='';
                   7085:     my %bighash;
1.620     albertel 7086:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7087:                             &GDBM_READER(),0640)) {
                   7088:         my $rid=$bighash{'mapalias_'.$symb};
                   7089: 	if ($rid) {
                   7090: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7091: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7092: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7093: 	}
                   7094:         untie %bighash;
                   7095:     }
                   7096:     return $aliassymb;
                   7097: }
                   7098: 
1.12      www      7099: # ----------------------------------------------------------------- Define Role
                   7100: 
                   7101: sub definerole {
                   7102:   if (allowed('mcr','/')) {
                   7103:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7104:     foreach my $role (split(':',$sysrole)) {
                   7105: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7106:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7107:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7108: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7109:                return "refused:s:$crole&$cqual"; 
                   7110:             }
                   7111:         }
1.191     harris41 7112:     }
1.800     albertel 7113:     foreach my $role (split(':',$domrole)) {
                   7114: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7115:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7116:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7117: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7118:                return "refused:d:$crole&$cqual"; 
                   7119:             }
                   7120:         }
1.191     harris41 7121:     }
1.800     albertel 7122:     foreach my $role (split(':',$courole)) {
                   7123: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7124:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7125:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7126: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7127:                return "refused:c:$crole&$cqual"; 
                   7128:             }
                   7129:         }
1.191     harris41 7130:     }
1.620     albertel 7131:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7132:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7133: 	        "rolesdef_$rolename=".
                   7134:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7135:     return reply($command,$env{'user.home'});
1.12      www      7136:   } else {
                   7137:     return 'refused';
                   7138:   }
1.105     harris41 7139: }
                   7140: 
                   7141: # ---------------- Make a metadata query against the network of library servers
                   7142: 
                   7143: sub metadata_query {
1.244     matthew  7144:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7145:     my %rhash;
1.845     albertel 7146:     my %libserv = &all_library();
1.244     matthew  7147:     my @server_list = (defined($server_array) ? @$server_array
                   7148:                                               : keys(%libserv) );
                   7149:     for my $server (@server_list) {
1.118     harris41 7150: 	unless ($custom or $customshow) {
                   7151: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7152: 	    $rhash{$server}=$reply;
                   7153: 	}
                   7154: 	else {
                   7155: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7156: 			     &escape($custom).':'.&escape($customshow),
                   7157: 			     $server);
                   7158: 	    $rhash{$server}=$reply;
                   7159: 	}
1.112     harris41 7160:     }
1.118     harris41 7161:     return \%rhash;
1.240     www      7162: }
                   7163: 
                   7164: # ----------------------------------------- Send log queries and wait for reply
                   7165: 
                   7166: sub log_query {
                   7167:     my ($uname,$udom,$query,%filters)=@_;
                   7168:     my $uhome=&homeserver($uname,$udom);
                   7169:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7170:     my $uhost=&hostname($uhome);
1.800     albertel 7171:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7172:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7173:                        $uhome);
1.479     albertel 7174:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7175:     return get_query_reply($queryid);
                   7176: }
                   7177: 
1.818     raeburn  7178: # -------------------------- Update MySQL table for portfolio file
                   7179: 
                   7180: sub update_portfolio_table {
1.821     raeburn  7181:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7182:     if ($group ne '') {
                   7183:         $file_name =~s /^\Q$group\E//;
                   7184:     }
1.818     raeburn  7185:     my $homeserver = &homeserver($uname,$udom);
                   7186:     my $queryid=
1.821     raeburn  7187:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7188:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7189:     my $reply = &get_query_reply($queryid);
                   7190:     return $reply;
                   7191: }
                   7192: 
1.899     raeburn  7193: # -------------------------- Update MySQL allusers table
                   7194: 
                   7195: sub update_allusers_table {
                   7196:     my ($uname,$udom,$names) = @_;
                   7197:     my $homeserver = &homeserver($uname,$udom);
                   7198:     my $queryid=
                   7199:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7200:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7201:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7202:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7203:                'generation='.&escape($names->{'generation'}).'%%'.
                   7204:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7205:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7206:     return;
1.899     raeburn  7207: }
                   7208: 
1.508     raeburn  7209: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7210: 
                   7211: sub fetch_enrollment_query {
1.511     raeburn  7212:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7213:     my $homeserver;
1.547     raeburn  7214:     my $maxtries = 1;
1.508     raeburn  7215:     if ($context eq 'automated') {
                   7216:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7217:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7218:     } else {
                   7219:         $homeserver = &homeserver($cnum,$dom);
                   7220:     }
1.838     albertel 7221:     my $host=&hostname($homeserver);
1.506     raeburn  7222:     my $cmd = '';
1.1000    raeburn  7223:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7224:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7225:     }
                   7226:     $cmd =~ s/%%$//;
                   7227:     $cmd = &escape($cmd);
                   7228:     my $query = 'fetchenrollment';
1.620     albertel 7229:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7230:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7231:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7232:         return 'error: '.$queryid;
                   7233:     }
1.506     raeburn  7234:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7235:     my $tries = 1;
                   7236:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7237:         $reply = &get_query_reply($queryid);
                   7238:         $tries ++;
                   7239:     }
1.526     raeburn  7240:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7241:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7242:     } else {
1.901     albertel 7243:         my @responses = split(/:/,$reply);
1.515     raeburn  7244:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7245:             foreach my $line (@responses) {
                   7246:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7247:                 $$replyref{$key} = $value;
                   7248:             }
                   7249:         } else {
1.1117    foxr     7250:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7251:             foreach my $line (@responses) {
                   7252:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7253:                 $$replyref{$key} = $value;
                   7254:                 if ($value > 0) {
1.800     albertel 7255:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7256:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7257:                         my $destname = $pathname.'/'.$filename;
                   7258:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7259:                         if ($xml_classlist =~ /^error/) {
                   7260:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7261:                         } else {
1.506     raeburn  7262:                             if ( open(FILE,">$destname") ) {
                   7263:                                 print FILE &unescape($xml_classlist);
                   7264:                                 close(FILE);
1.526     raeburn  7265:                             } else {
                   7266:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7267:                             }
                   7268:                         }
                   7269:                     }
                   7270:                 }
                   7271:             }
                   7272:         }
                   7273:         return 'ok';
                   7274:     }
                   7275:     return 'error';
                   7276: }
                   7277: 
1.242     www      7278: sub get_query_reply {
                   7279:     my $queryid=shift;
1.1117    foxr     7280:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7281:     my $reply='';
                   7282:     for (1..100) {
                   7283: 	sleep 2;
                   7284:         if (-e $replyfile.'.end') {
1.448     albertel 7285: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7286: 		$reply = join('',<$fh>);
                   7287: 		close($fh);
1.240     www      7288: 	   } else { return 'error: reply_file_error'; }
1.242     www      7289:            return &unescape($reply);
                   7290: 	}
1.240     www      7291:     }
1.242     www      7292:     return 'timeout:'.$queryid;
1.240     www      7293: }
                   7294: 
                   7295: sub courselog_query {
1.241     www      7296: #
                   7297: # possible filters:
                   7298: # url: url or symb
                   7299: # username
                   7300: # domain
                   7301: # action: view, submit, grade
                   7302: # start: timestamp
                   7303: # end: timestamp
                   7304: #
1.240     www      7305:     my (%filters)=@_;
1.620     albertel 7306:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7307:     if ($filters{'url'}) {
                   7308: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7309:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7310:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7311:     }
1.620     albertel 7312:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7313:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7314:     return &log_query($cname,$cdom,'courselog',%filters);
                   7315: }
                   7316: 
                   7317: sub userlog_query {
1.858     raeburn  7318: #
                   7319: # possible filters:
                   7320: # action: log check role
                   7321: # start: timestamp
                   7322: # end: timestamp
                   7323: #
1.240     www      7324:     my ($uname,$udom,%filters)=@_;
                   7325:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7326: }
                   7327: 
1.506     raeburn  7328: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7329: 
                   7330: sub auto_run {
1.508     raeburn  7331:     my ($cnum,$cdom) = @_;
1.876     raeburn  7332:     my $response = 0;
                   7333:     my $settings;
                   7334:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7335:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7336:         $settings = $domconfig{'autoenroll'};
                   7337:         if ($settings->{'run'} eq '1') {
                   7338:             $response = 1;
                   7339:         }
                   7340:     } else {
1.934     raeburn  7341:         my $homeserver;
                   7342:         if (&is_course($cdom,$cnum)) {
                   7343:             $homeserver = &homeserver($cnum,$cdom);
                   7344:         } else {
                   7345:             $homeserver = &domain($cdom,'primary');
                   7346:         }
                   7347:         if ($homeserver ne 'no_host') {
                   7348:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7349:         }
1.876     raeburn  7350:     }
1.506     raeburn  7351:     return $response;
                   7352: }
1.776     albertel 7353: 
1.506     raeburn  7354: sub auto_get_sections {
1.508     raeburn  7355:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7356:     my $homeserver;
                   7357:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7358:         $homeserver = &homeserver($cnum,$cdom);
                   7359:     }
                   7360:     if (!defined($homeserver)) { 
                   7361:         if ($cdom =~ /^$match_domain$/) {
                   7362:             $homeserver = &domain($cdom,'primary');
                   7363:         }
                   7364:     }
                   7365:     my @secs;
                   7366:     if (defined($homeserver)) {
                   7367:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7368:         unless ($response eq 'refused') {
                   7369:             @secs = split(/:/,$response);
                   7370:         }
1.506     raeburn  7371:     }
                   7372:     return @secs;
                   7373: }
1.776     albertel 7374: 
1.506     raeburn  7375: sub auto_new_course {
1.1099    raeburn  7376:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7377:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7378:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7379:     return $response;
                   7380: }
1.776     albertel 7381: 
1.506     raeburn  7382: sub auto_validate_courseID {
1.508     raeburn  7383:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7384:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7385:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7386:     return $response;
                   7387: }
1.776     albertel 7388: 
1.1007    raeburn  7389: sub auto_validate_instcode {
1.1020    raeburn  7390:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7391:     my ($homeserver,$response);
                   7392:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7393:         $homeserver = &homeserver($cnum,$cdom);
                   7394:     }
                   7395:     if (!defined($homeserver)) {
                   7396:         if ($cdom =~ /^$match_domain$/) {
                   7397:             $homeserver = &domain($cdom,'primary');
                   7398:         }
                   7399:     }
1.1065    raeburn  7400:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7401:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7402:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7403:     return ($outcome,$description);
1.1007    raeburn  7404: }
                   7405: 
1.506     raeburn  7406: sub auto_create_password {
1.873     raeburn  7407:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7408:     my ($homeserver,$response);
1.506     raeburn  7409:     my $create_passwd = 0;
                   7410:     my $authchk = '';
1.873     raeburn  7411:     if ($udom =~ /^$match_domain$/) {
                   7412:         $homeserver = &domain($udom,'primary');
                   7413:     }
                   7414:     if ($homeserver eq '') {
                   7415:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7416:             $homeserver = &homeserver($cnum,$cdom);
                   7417:         }
                   7418:     }
                   7419:     if ($homeserver eq '') {
                   7420:         $authchk = 'nodomain';
1.506     raeburn  7421:     } else {
1.873     raeburn  7422:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7423:         if ($response eq 'refused') {
                   7424:             $authchk = 'refused';
                   7425:         } else {
1.901     albertel 7426:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7427:         }
1.506     raeburn  7428:     }
                   7429:     return ($authparam,$create_passwd,$authchk);
                   7430: }
                   7431: 
1.706     raeburn  7432: sub auto_photo_permission {
                   7433:     my ($cnum,$cdom,$students) = @_;
                   7434:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7435:     my ($outcome,$perm_reqd,$conditions) = 
                   7436: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7437:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7438: 	return (undef,undef);
                   7439:     }
1.706     raeburn  7440:     return ($outcome,$perm_reqd,$conditions);
                   7441: }
                   7442: 
                   7443: sub auto_checkphotos {
                   7444:     my ($uname,$udom,$pid) = @_;
                   7445:     my $homeserver = &homeserver($uname,$udom);
                   7446:     my ($result,$resulttype);
                   7447:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7448: 				   &escape($uname).':'.&escape($pid),
                   7449: 				   $homeserver));
1.709     albertel 7450:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7451: 	return (undef,undef);
                   7452:     }
1.706     raeburn  7453:     if ($outcome) {
                   7454:         ($result,$resulttype) = split(/:/,$outcome);
                   7455:     } 
                   7456:     return ($result,$resulttype);
                   7457: }
                   7458: 
                   7459: sub auto_photochoice {
                   7460:     my ($cnum,$cdom) = @_;
                   7461:     my $homeserver = &homeserver($cnum,$cdom);
                   7462:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7463: 						       &escape($cdom),
                   7464: 						       $homeserver)));
1.709     albertel 7465:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7466: 	return (undef,undef);
                   7467:     }
1.706     raeburn  7468:     return ($update,$comment);
                   7469: }
                   7470: 
                   7471: sub auto_photoupdate {
                   7472:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7473:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7474:     my $host=&hostname($homeserver);
1.706     raeburn  7475:     my $cmd = '';
                   7476:     my $maxtries = 1;
1.800     albertel 7477:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7478:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7479:     }
                   7480:     $cmd =~ s/%%$//;
                   7481:     $cmd = &escape($cmd);
                   7482:     my $query = 'institutionalphotos';
                   7483:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7484:     unless ($queryid=~/^\Q$host\E\_/) {
                   7485:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7486:         return 'error: '.$queryid;
                   7487:     }
                   7488:     my $reply = &get_query_reply($queryid);
                   7489:     my $tries = 1;
                   7490:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7491:         $reply = &get_query_reply($queryid);
                   7492:         $tries ++;
                   7493:     }
                   7494:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7495:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7496:     } else {
                   7497:         my @responses = split(/:/,$reply);
                   7498:         my $outcome = shift(@responses); 
                   7499:         foreach my $item (@responses) {
                   7500:             my ($key,$value) = split(/=/,$item);
                   7501:             $$photo{$key} = $value;
                   7502:         }
                   7503:         return $outcome;
                   7504:     }
                   7505:     return 'error';
                   7506: }
                   7507: 
1.521     raeburn  7508: sub auto_instcode_format {
1.793     albertel 7509:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7510: 	$cat_order) = @_;
1.521     raeburn  7511:     my $courses = '';
1.772     raeburn  7512:     my @homeservers;
1.521     raeburn  7513:     if ($caller eq 'global') {
1.841     albertel 7514: 	my %servers = &get_servers($codedom,'library');
                   7515: 	foreach my $tryserver (keys(%servers)) {
                   7516: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7517: 		push(@homeservers,$tryserver);
                   7518: 	    }
1.584     raeburn  7519:         }
1.1022    raeburn  7520:     } elsif ($caller eq 'requests') {
                   7521:         if ($codedom =~ /^$match_domain$/) {
                   7522:             my $chome = &domain($codedom,'primary');
                   7523:             unless ($chome eq 'no_host') {
                   7524:                 push(@homeservers,$chome);
                   7525:             }
                   7526:         }
1.521     raeburn  7527:     } else {
1.772     raeburn  7528:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7529:     }
1.793     albertel 7530:     foreach my $code (keys(%{$instcodes})) {
                   7531:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7532:     }
                   7533:     chop($courses);
1.772     raeburn  7534:     my $ok_response = 0;
                   7535:     my $response;
                   7536:     while (@homeservers > 0 && $ok_response == 0) {
                   7537:         my $server = shift(@homeservers); 
                   7538:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7539:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7540:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7541: 		split(/:/,$response);
1.772     raeburn  7542:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7543:             push(@{$codetitles},&str2array($codetitles_str));
                   7544:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7545:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7546:             $ok_response = 1;
                   7547:         }
                   7548:     }
                   7549:     if ($ok_response) {
1.521     raeburn  7550:         return 'ok';
1.772     raeburn  7551:     } else {
                   7552:         return $response;
1.521     raeburn  7553:     }
                   7554: }
                   7555: 
1.792     raeburn  7556: sub auto_instcode_defaults {
                   7557:     my ($domain,$returnhash,$code_order) = @_;
                   7558:     my @homeservers;
1.841     albertel 7559: 
                   7560:     my %servers = &get_servers($domain,'library');
                   7561:     foreach my $tryserver (keys(%servers)) {
                   7562: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7563: 	    push(@homeservers,$tryserver);
                   7564: 	}
1.792     raeburn  7565:     }
1.841     albertel 7566: 
1.792     raeburn  7567:     my $response;
1.841     albertel 7568:     foreach my $server (@homeservers) {
1.792     raeburn  7569:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7570:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7571: 	
                   7572: 	foreach my $pair (split(/\&/,$response)) {
                   7573: 	    my ($name,$value)=split(/\=/,$pair);
                   7574: 	    if ($name eq 'code_order') {
                   7575: 		@{$code_order} = split(/\&/,&unescape($value));
                   7576: 	    } else {
                   7577: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7578: 	    }
                   7579: 	}
                   7580: 	return 'ok';
1.792     raeburn  7581:     }
1.841     albertel 7582: 
                   7583:     return $response;
1.1003    raeburn  7584: }
                   7585: 
                   7586: sub auto_possible_instcodes {
1.1007    raeburn  7587:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7588:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7589:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7590:         return;
                   7591:     }
1.1003    raeburn  7592:     my (@homeservers,$uhome);
                   7593:     if (defined(&domain($domain,'primary'))) {
                   7594:         $uhome=&domain($domain,'primary');
                   7595:         push(@homeservers,&domain($domain,'primary'));
                   7596:     } else {
                   7597:         my %servers = &get_servers($domain,'library');
                   7598:         foreach my $tryserver (keys(%servers)) {
                   7599:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7600:                 push(@homeservers,$tryserver);
                   7601:             }
                   7602:         }
                   7603:     }
                   7604:     my $response;
                   7605:     foreach my $server (@homeservers) {
                   7606:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7607:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7608:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7609:             split(':',$response);
                   7610:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7611:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7612:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7613:             my ($name,$value)=split('=',$item);
                   7614:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7615:         }
                   7616:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7617:             my ($name,$value)=split('=',$item);
                   7618:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7619:         }
                   7620:         return 'ok';
                   7621:     }
                   7622:     return $response;
                   7623: }
1.792     raeburn  7624: 
1.1010    raeburn  7625: sub auto_courserequest_checks {
                   7626:     my ($dom) = @_;
1.1020    raeburn  7627:     my ($homeserver,%validations);
                   7628:     if ($dom =~ /^$match_domain$/) {
                   7629:         $homeserver = &domain($dom,'primary');
                   7630:     }
                   7631:     unless ($homeserver eq 'no_host') {
                   7632:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7633:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7634:             my @items = split(/&/,$response);
                   7635:             foreach my $item (@items) {
                   7636:                 my ($key,$value) = split('=',$item);
                   7637:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7638:             }
                   7639:         }
                   7640:     }
1.1010    raeburn  7641:     return %validations; 
                   7642: }
                   7643: 
1.1020    raeburn  7644: sub auto_courserequest_validation {
                   7645:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7646:     my ($homeserver,$response);
                   7647:     if ($dom =~ /^$match_domain$/) {
                   7648:         $homeserver = &domain($dom,'primary');
                   7649:     }
                   7650:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7651:           
1.1020    raeburn  7652:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7653:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7654:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7655:                                     $homeserver));
                   7656:     }
                   7657:     return $response;
                   7658: }
                   7659: 
1.777     albertel 7660: sub auto_validate_class_sec {
1.918     raeburn  7661:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7662:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7663:     my $ownerlist;
                   7664:     if (ref($owners) eq 'ARRAY') {
                   7665:         $ownerlist = join(',',@{$owners});
                   7666:     } else {
                   7667:         $ownerlist = $owners;
                   7668:     }
1.773     raeburn  7669:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7670:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7671:     return $response;
                   7672: }
                   7673: 
1.679     raeburn  7674: # ------------------------------------------------------- Course Group routines
                   7675: 
                   7676: sub get_coursegroups {
1.809     raeburn  7677:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7678:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7679: }
                   7680: 
1.679     raeburn  7681: sub modify_coursegroup {
                   7682:     my ($cdom,$cnum,$groupsettings) = @_;
                   7683:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7684: }
                   7685: 
1.809     raeburn  7686: sub toggle_coursegroup_status {
                   7687:     my ($cdom,$cnum,$group,$action) = @_;
                   7688:     my ($from_namespace,$to_namespace);
                   7689:     if ($action eq 'delete') {
                   7690:         $from_namespace = 'coursegroups';
                   7691:         $to_namespace = 'deleted_groups';
                   7692:     } else {
                   7693:         $from_namespace = 'deleted_groups';
                   7694:         $to_namespace = 'coursegroups';
                   7695:     }
                   7696:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7697:     if (my $tmp = &error(%curr_group)) {
                   7698:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7699:         return ('read error',$tmp);
                   7700:     } else {
                   7701:         my %savedsettings = %curr_group; 
1.809     raeburn  7702:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7703:         my $deloutcome;
                   7704:         if ($result eq 'ok') {
1.809     raeburn  7705:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7706:         } else {
                   7707:             return ('write error',$result);
                   7708:         }
                   7709:         if ($deloutcome eq 'ok') {
                   7710:             return 'ok';
                   7711:         } else {
                   7712:             return ('delete error',$deloutcome);
                   7713:         }
                   7714:     }
                   7715: }
                   7716: 
1.679     raeburn  7717: sub modify_group_roles {
1.957     raeburn  7718:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7719:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7720:     my $role = 'gr/'.&escape($userprivs);
                   7721:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7722:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7723:     if ($result eq 'ok') {
                   7724:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7725:     }
1.679     raeburn  7726:     return $result;
                   7727: }
                   7728: 
                   7729: sub modify_coursegroup_membership {
                   7730:     my ($cdom,$cnum,$membership) = @_;
                   7731:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7732:     return $result;
                   7733: }
                   7734: 
1.682     raeburn  7735: sub get_active_groups {
                   7736:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7737:     my $now = time;
                   7738:     my %groups = ();
                   7739:     foreach my $key (keys(%env)) {
1.811     albertel 7740:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7741:             my ($start,$end) = split(/\./,$env{$key});
                   7742:             if (($end!=0) && ($end<$now)) { next; }
                   7743:             if (($start!=0) && ($start>$now)) { next; }
                   7744:             if ($1 eq $cdom && $2 eq $cnum) {
                   7745:                 $groups{$3} = $env{$key} ;
                   7746:             }
                   7747:         }
                   7748:     }
                   7749:     return %groups;
                   7750: }
                   7751: 
1.683     raeburn  7752: sub get_group_membership {
                   7753:     my ($cdom,$cnum,$group) = @_;
                   7754:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7755: }
                   7756: 
                   7757: sub get_users_groups {
                   7758:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7759:     my @usersgroups;
1.683     raeburn  7760:     my $cachetime=1800;
                   7761: 
                   7762:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7763:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7764:     if (defined($cached)) {
1.734     albertel 7765:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7766:     } else {  
                   7767:         $grouplist = '';
1.816     raeburn  7768:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7769:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7770:         my $access_end = $env{'course.'.$courseid.
                   7771:                               '.default_enrollment_end_date'};
                   7772:         my $now = time;
                   7773:         foreach my $key (keys(%roleshash)) {
                   7774:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7775:                 my $group = $1;
                   7776:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7777:                     my $start = $2;
                   7778:                     my $end = $1;
                   7779:                     if ($start == -1) { next; } # deleted from group
                   7780:                     if (($start!=0) && ($start>$now)) { next; }
                   7781:                     if (($end!=0) && ($end<$now)) {
                   7782:                         if ($access_end && $access_end < $now) {
                   7783:                             if ($access_end - $end < 86400) {
                   7784:                                 push(@usersgroups,$group);
1.733     raeburn  7785:                             }
                   7786:                         }
1.817     raeburn  7787:                         next;
1.733     raeburn  7788:                     }
1.817     raeburn  7789:                     push(@usersgroups,$group);
1.683     raeburn  7790:                 }
                   7791:             }
                   7792:         }
1.817     raeburn  7793:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7794:         $grouplist = join(':',@usersgroups);
                   7795:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7796:     }
1.733     raeburn  7797:     return @usersgroups;
1.683     raeburn  7798: }
                   7799: 
                   7800: sub devalidate_getgroups_cache {
                   7801:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7802:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7803: 
1.683     raeburn  7804:     my $hashid="$udom:$uname:$courseid";
                   7805:     &devalidate_cache_new('getgroups',$hashid);
                   7806: }
                   7807: 
1.12      www      7808: # ------------------------------------------------------------------ Plain Text
                   7809: 
                   7810: sub plaintext {
1.988     raeburn  7811:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7812:     if ($short =~ m{^cr/}) {
1.758     albertel 7813: 	return (split('/',$short))[-1];
                   7814:     }
1.742     raeburn  7815:     if (!defined($cid)) {
                   7816:         $cid = $env{'request.course.id'};
                   7817:     }
                   7818:     my %rolenames = (
1.1008    raeburn  7819:                       Course    => 'std',
                   7820:                       Community => 'alt1',
1.742     raeburn  7821:                     );
1.1037    raeburn  7822:     if ($cid ne '') {
                   7823:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7824:             unless ($forcedefault) {
                   7825:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7826:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7827:                 return &Apache::lonlocal::mt($roletext);
                   7828:             }
                   7829:         }
                   7830:     }
                   7831:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7832:         (defined($rolenames{$type})) && 
                   7833:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7834:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7835:     } elsif ($cid ne '') {
                   7836:         my $crstype = $env{'course.'.$cid.'.type'};
                   7837:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7838:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7839:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7840:         }
1.742     raeburn  7841:     }
1.1037    raeburn  7842:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7843: }
                   7844: 
                   7845: # ----------------------------------------------------------------- Assign Role
                   7846: 
                   7847: sub assignrole {
1.957     raeburn  7848:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7849:         $context)=@_;
1.21      www      7850:     my $mrole;
                   7851:     if ($role =~ /^cr\//) {
1.393     www      7852:         my $cwosec=$url;
1.811     albertel 7853:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7854: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7855:            my $refused = 1;
                   7856:            if ($context eq 'requestcourses') {
                   7857:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7858:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7859:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7860:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7861:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7862:                            if ($crsenv{'internal.courseowner'} eq
                   7863:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7864:                                $refused = '';
                   7865:                            }
                   7866:                        }
                   7867:                    }
                   7868:                }
                   7869:            }
                   7870:            if ($refused) {
                   7871:                &logthis('Refused custom assignrole: '.
                   7872:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7873:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7874:                return 'refused';
                   7875:            }
1.104     www      7876:         }
1.21      www      7877:         $mrole='cr';
1.678     raeburn  7878:     } elsif ($role =~ /^gr\//) {
                   7879:         my $cwogrp=$url;
1.811     albertel 7880:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7881:         unless (&allowed('mdg',$cwogrp)) {
                   7882:             &logthis('Refused group assignrole: '.
                   7883:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7884:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7885:             return 'refused';
                   7886:         }
                   7887:         $mrole='gr';
1.21      www      7888:     } else {
1.82      www      7889:         my $cwosec=$url;
1.811     albertel 7890:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7891:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7892:             my $refused;
                   7893:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7894:                 if (!(&allowed('c'.$role,$url))) {
                   7895:                     $refused = 1;
                   7896:                 }
                   7897:             } else {
                   7898:                 $refused = 1;
                   7899:             }
1.947     raeburn  7900:             if ($refused) {
1.1045    raeburn  7901:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7902:                 if (!$selfenroll && $context eq 'course') {
                   7903:                     my %crsenv;
                   7904:                     if ($role eq 'cc' || $role eq 'co') {
                   7905:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7906:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7907:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7908:                                 if ($crsenv{'internal.courseowner'} eq 
                   7909:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7910:                                     $refused = '';
                   7911:                                 }
                   7912:                             }
                   7913:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7914:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7915:                                 if ($crsenv{'internal.courseowner'} eq 
                   7916:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7917:                                     $refused = '';
                   7918:                                 }
                   7919:                             }
                   7920:                         }
                   7921:                     }
                   7922:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7923:                     $refused = '';
1.1017    raeburn  7924:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7925:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7926:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7927:                         my $wrongcc;
                   7928:                         if ($cnum =~ /^$match_community$/) {
                   7929:                             $wrongcc = 1 if ($role eq 'cc');
                   7930:                         } else {
                   7931:                             $wrongcc = 1 if ($role eq 'co');
                   7932:                         }
                   7933:                         unless ($wrongcc) {
                   7934:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7935:                             if ($crsenv{'internal.courseowner'} eq 
                   7936:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7937:                                 $refused = '';
                   7938:                             }
1.1017    raeburn  7939:                         }
                   7940:                     }
1.1172.2.9  raeburn  7941:                 } elsif ($context eq 'requestauthor') {
                   7942:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7943:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7944:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7945:                             $refused = '';
                   7946:                         } else {
                   7947:                             my %domdefaults = &get_domain_defaults($udom);
                   7948:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7949:                                 my $checkbystatus;
                   7950:                                 if ($env{'user.adv'}) {
                   7951:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7952:                                     if ($disposition eq 'automatic') {
                   7953:                                         $refused = '';
                   7954:                                     } elsif ($disposition eq '') {
                   7955:                                         $checkbystatus = 1;
                   7956:                                     }
                   7957:                                 } else {
                   7958:                                     $checkbystatus = 1;
                   7959:                                 }
                   7960:                                 if ($checkbystatus) {
                   7961:                                     if ($env{'environment.inststatus'}) {
                   7962:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7963:                                         foreach my $type (@inststatuses) {
                   7964:                                             if (($type ne '') &&
                   7965:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7966:                                                 $refused = '';
                   7967:                                             }
                   7968:                                         }
                   7969:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7970:                                         $refused = '';
                   7971:                                     }
                   7972:                                 }
                   7973:                             }
                   7974:                         }
                   7975:                     }
1.1017    raeburn  7976:                 }
                   7977:                 if ($refused) {
1.947     raeburn  7978:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7979:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7980: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7981:                     return 'refused';
                   7982:                 }
1.932     raeburn  7983:             }
1.1131    raeburn  7984:         } elsif ($role eq 'au') {
                   7985:             if ($url ne '/'.$udom.'/') {
                   7986:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7987:                          ' to assign author role for '.$uname.':'.$udom.
                   7988:                          ' in domain: '.$url.' refused (wrong domain).');
                   7989:                 return 'refused';
                   7990:             }
1.104     www      7991:         }
1.21      www      7992:         $mrole=$role;
                   7993:     }
1.620     albertel 7994:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7995:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7996:     if ($end) { $command.='_'.$end; }
1.21      www      7997:     if ($start) {
                   7998: 	if ($end) { 
1.81      www      7999:            $command.='_'.$start; 
1.21      www      8000:         } else {
1.81      www      8001:            $command.='_0_'.$start;
1.21      www      8002:         }
                   8003:     }
1.739     raeburn  8004:     my $origstart = $start;
                   8005:     my $origend = $end;
1.957     raeburn  8006:     my $delflag;
1.357     www      8007: # actually delete
                   8008:     if ($deleteflag) {
1.373     www      8009: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8010: # modify command to delete the role
1.620     albertel 8011:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8012:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8013: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8014: # set start and finish to negative values for userrolelog
                   8015:            $start=-1;
                   8016:            $end=-1;
1.957     raeburn  8017:            $delflag = 1;
1.357     www      8018:         }
                   8019:     }
                   8020: # send command
1.349     www      8021:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8022: # log new user role if status is ok
1.349     www      8023:     if ($answer eq 'ok') {
1.663     raeburn  8024: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8025:         if (($role eq 'cc') || ($role eq 'in') ||
                   8026:             ($role eq 'ep') || ($role eq 'ad') ||
                   8027:             ($role eq 'ta') || ($role eq 'st') ||
                   8028:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8029:             ($role eq 'co')) {
1.1172.2.13  raeburn  8030: # for course roles, perform group memberships changes triggered by role change.
                   8031:             unless ($role =~ /^gr/) {
                   8032:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8033:                                                  $origstart,$selfenroll,$context);
                   8034:             }
1.1172.2.9  raeburn  8035:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8036:                            $selfenroll,$context);
                   8037:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8038:                  ($role eq 'au') || ($role eq 'dc')) {
                   8039:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8040:                            $context);
                   8041:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8042:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8043:                              $context);
                   8044:         }
1.1053    raeburn  8045:         if ($role eq 'cc') {
                   8046:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8047:         }
1.349     www      8048:     }
                   8049:     return $answer;
1.169     harris41 8050: }
                   8051: 
1.1053    raeburn  8052: sub autoupdate_coowners {
                   8053:     my ($url,$end,$start,$uname,$udom) = @_;
                   8054:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8055:     if (($cdom ne '') && ($cnum ne '')) {
                   8056:         my $now = time;
                   8057:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8058:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8059:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8060:             my $instcode = $coursehash{'internal.coursecode'};
                   8061:             if ($instcode ne '') {
1.1056    raeburn  8062:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8063:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8064:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8065:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8066:                         if ($result eq 'valid') {
                   8067:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8068:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8069:                                     push(@newcoowners,$coowner);
                   8070:                                 }
                   8071:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8072:                                     push(@newcoowners,$uname.':'.$udom);
                   8073:                                 }
                   8074:                                 @newcoowners = sort(@newcoowners);
                   8075:                             } else {
                   8076:                                 push(@newcoowners,$uname.':'.$udom);
                   8077:                             }
                   8078:                         } else {
                   8079:                             if ($coursehash{'internal.co-owners'}) {
                   8080:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8081:                                     unless ($coowner eq $uname.':'.$udom) {
                   8082:                                         push(@newcoowners,$coowner);
                   8083:                                     }
                   8084:                                 }
                   8085:                                 unless (@newcoowners > 0) {
                   8086:                                     $delcoowners = 1;
                   8087:                                     $coowners = '';
                   8088:                                 }
                   8089:                             }
                   8090:                         }
                   8091:                         if (@newcoowners || $delcoowners) {
                   8092:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8093:                                             $delcoowners,@newcoowners);
                   8094:                         }
                   8095:                     }
                   8096:                 }
                   8097:             }
                   8098:         }
                   8099:     }
                   8100: }
                   8101: 
                   8102: sub store_coowners {
                   8103:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8104:     my $cid = $cdom.'_'.$cnum;
                   8105:     my ($coowners,$delresult,$putresult);
                   8106:     if (@newcoowners) {
                   8107:         $coowners = join(',',@newcoowners);
                   8108:         my %coownershash = (
                   8109:                             'internal.co-owners' => $coowners,
                   8110:                            );
                   8111:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8112:         if ($putresult eq 'ok') {
                   8113:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8114:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8115:             }
                   8116:         }
                   8117:     }
                   8118:     if ($delcoowners) {
                   8119:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8120:         if ($delresult eq 'ok') {
                   8121:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8122:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8123:             }
                   8124:         }
                   8125:     }
                   8126:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8127:         my %crsinfo =
                   8128:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8129:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8130:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8131:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8132:         }
                   8133:     }
                   8134: }
                   8135: 
1.169     harris41 8136: # -------------------------------------------------- Modify user authentication
1.197     www      8137: # Overrides without validation
                   8138: 
1.169     harris41 8139: sub modifyuserauth {
                   8140:     my ($udom,$uname,$umode,$upass)=@_;
                   8141:     my $uhome=&homeserver($uname,$udom);
1.197     www      8142:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8143:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8144:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8145:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8146:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8147: 		     &escape($upass),$uhome);
1.620     albertel 8148:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8149:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8150:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8151:     &log($udom,,$uname,$uhome,
1.620     albertel 8152:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8153:                                      $env{'user.name'}.', '.$umode.
1.197     www      8154:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8155:     unless ($reply eq 'ok') {
1.197     www      8156:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8157: 	return 'error: '.$reply;
                   8158:     }   
1.170     harris41 8159:     return 'ok';
1.80      www      8160: }
                   8161: 
1.81      www      8162: # --------------------------------------------------------------- Modify a user
1.80      www      8163: 
1.81      www      8164: sub modifyuser {
1.206     matthew  8165:     my ($udom,    $uname, $uid,
                   8166:         $umode,   $upass, $first,
                   8167:         $middle,  $last,  $gene,
1.1058    raeburn  8168:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8169:     $udom= &LONCAPA::clean_domain($udom);
                   8170:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8171:     my $showcandelete = 'none';
                   8172:     if (ref($candelete) eq 'ARRAY') {
                   8173:         if (@{$candelete} > 0) {
                   8174:             $showcandelete = join(', ',@{$candelete});
                   8175:         }
                   8176:     }
1.81      www      8177:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8178:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8179: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8180:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8181:                                      ' desiredhome not specified'). 
1.620     albertel 8182:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8183:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8184:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8185:     my $newuser;
                   8186:     if ($uhome eq 'no_host') {
                   8187:         $newuser = 1;
                   8188:     }
1.80      www      8189: # ----------------------------------------------------------------- Create User
1.406     albertel 8190:     if (($uhome eq 'no_host') && 
                   8191: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8192:         my $unhome='';
1.844     albertel 8193:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8194:             $unhome = $desiredhome;
1.620     albertel 8195: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8196: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8197:         } else { # load balancing routine for determining $unhome
1.81      www      8198:             my $loadm=10000000;
1.841     albertel 8199: 	    my %servers = &get_servers($udom,'library');
                   8200: 	    foreach my $tryserver (keys(%servers)) {
                   8201: 		my $answer=reply('load',$tryserver);
                   8202: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8203: 		    $loadm=$answer;
                   8204: 		    $unhome=$tryserver;
                   8205: 		}
1.80      www      8206: 	    }
                   8207:         }
                   8208:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8209: 	    return 'error: unable to find a home server for '.$uname.
                   8210:                    ' in domain '.$udom;
1.80      www      8211:         }
                   8212:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8213:                          &escape($upass),$unhome);
                   8214: 	unless ($reply eq 'ok') {
                   8215:             return 'error: '.$reply;
                   8216:         }   
1.230     stredwic 8217:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8218:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8219: 	    return 'error: unable verify users home machine.';
1.80      www      8220:         }
1.209     matthew  8221:     }   # End of creation of new user
1.80      www      8222: # ---------------------------------------------------------------------- Add ID
                   8223:     if ($uid) {
                   8224:        $uid=~tr/A-Z/a-z/;
                   8225:        my %uidhash=&idrget($udom,$uname);
1.196     www      8226:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8227:          && (!$forceid)) {
1.80      www      8228: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8229: 	      return 'error: user id "'.$uid.'" does not match '.
                   8230:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8231:           }
                   8232:        } else {
                   8233: 	  &idput($udom,($uname => $uid));
                   8234:        }
                   8235:     }
                   8236: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8237:     my @tmp=&get('environment',
1.899     raeburn  8238: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8239:                     'permanentemail','inststatus'],
1.134     albertel 8240: 		   $udom,$uname);
1.1075    raeburn  8241:     my (%names,%oldnames);
1.313     matthew  8242:     if ($tmp[0] =~ m/^error:.*/) { 
                   8243:         %names=(); 
                   8244:     } else {
                   8245:         %names = @tmp;
1.1075    raeburn  8246:         %oldnames = %names;
1.313     matthew  8247:     }
1.388     www      8248: #
1.1058    raeburn  8249: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8250: # of users did not contain them), do not overwrite existing values
                   8251: # unless field is in $candelete array ref.  
                   8252: #
                   8253: 
                   8254:     my @fields = ('firstname','middlename','lastname','generation',
                   8255:                   'permanentemail','id');
                   8256:     my %newvalues;
                   8257:     if (ref($candelete) eq 'ARRAY') {
                   8258:         foreach my $field (@fields) {
                   8259:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8260:                 if ($field eq 'firstname') {
                   8261:                     $names{$field} = $first;
                   8262:                 } elsif ($field eq 'middlename') {
                   8263:                     $names{$field} = $middle;
                   8264:                 } elsif ($field eq 'lastname') {
                   8265:                     $names{$field} = $last;
                   8266:                 } elsif ($field eq 'generation') { 
                   8267:                     $names{$field} = $gene;
                   8268:                 } elsif ($field eq 'permanentemail') {
                   8269:                     $names{$field} = $email;
                   8270:                 } elsif ($field eq 'id') {
                   8271:                     $names{$field}  = $uid;
                   8272:                 }
                   8273:             }
                   8274:         }
                   8275:     }
1.388     www      8276:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8277:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8278:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8279:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8280:     if ($email) {
                   8281:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8282:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8283:     }
1.899     raeburn  8284:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8285:     if (defined($inststatus)) {
                   8286:         $names{'inststatus'} = '';
                   8287:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8288:         if (ref($usertypes) eq 'HASH') {
                   8289:             my @okstatuses; 
                   8290:             foreach my $item (split(/:/,$inststatus)) {
                   8291:                 if (defined($usertypes->{$item})) {
                   8292:                     push(@okstatuses,$item);  
                   8293:                 }
                   8294:             }
                   8295:             if (@okstatuses) {
                   8296:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8297:             }
                   8298:         }
                   8299:     }
1.1075    raeburn  8300:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8301:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8302:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8303:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8304:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8305:     } else {
                   8306:         $logmsg .= ' during self creation';
                   8307:     }
1.1075    raeburn  8308:     my $changed;
                   8309:     if ($newuser) {
                   8310:         $changed = 1;
                   8311:     } else {
                   8312:         foreach my $field (@fields) {
                   8313:             if ($names{$field} ne $oldnames{$field}) {
                   8314:                 $changed = 1;
                   8315:                 last;
                   8316:             }
                   8317:         }
                   8318:     }
                   8319:     unless ($changed) {
                   8320:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8321:         &logthis($logmsg);
                   8322:         return 'ok';
                   8323:     }
                   8324:     my $reply = &put('environment', \%names, $udom,$uname);
                   8325:     if ($reply ne 'ok') { 
                   8326:         return 'error: '.$reply;
                   8327:     }
1.1087    raeburn  8328:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8329:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8330:     }
1.1075    raeburn  8331:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8332:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8333:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8334:     &logthis($logmsg);
1.134     albertel 8335:     return 'ok';
1.80      www      8336: }
                   8337: 
1.81      www      8338: # -------------------------------------------------------------- Modify student
1.80      www      8339: 
1.81      www      8340: sub modifystudent {
                   8341:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8342:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8343:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8344:     if (!$cid) {
1.620     albertel 8345: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8346: 	    return 'not_in_class';
                   8347: 	}
1.80      www      8348:     }
                   8349: # --------------------------------------------------------------- Make the user
1.81      www      8350:     my $reply=&modifyuser
1.209     matthew  8351: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8352:          $desiredhome,$email,$inststatus);
1.80      www      8353:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8354:     # This will cause &modify_student_enrollment to get the uid from the
                   8355:     # students environment
                   8356:     $uid = undef if (!$forceid);
1.455     albertel 8357:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8358: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8359:     return $reply;
                   8360: }
                   8361: 
                   8362: sub modify_student_enrollment {
1.957     raeburn  8363:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8364:     my ($cdom,$cnum,$chome);
                   8365:     if (!$cid) {
1.620     albertel 8366: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8367: 	    return 'not_in_class';
                   8368: 	}
1.620     albertel 8369: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8370: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8371:     } else {
                   8372: 	($cdom,$cnum)=split(/_/,$cid);
                   8373:     }
1.620     albertel 8374:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8375:     if (!$chome) {
1.457     raeburn  8376: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8377:     }
1.455     albertel 8378:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8379:     # Make sure the user exists
1.81      www      8380:     my $uhome=&homeserver($uname,$udom);
                   8381:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8382: 	return 'error: no such user';
                   8383:     }
1.297     matthew  8384:     # Get student data if we were not given enough information
                   8385:     if (!defined($first)  || $first  eq '' || 
                   8386:         !defined($last)   || $last   eq '' || 
                   8387:         !defined($uid)    || $uid    eq '' || 
                   8388:         !defined($middle) || $middle eq '' || 
                   8389:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8390:         # They did not supply us with enough data to enroll the student, so
                   8391:         # we need to pick up more information.
1.297     matthew  8392:         my %tmp = &get('environment',
1.294     matthew  8393:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8394:                        ,$udom,$uname);
                   8395: 
1.800     albertel 8396:         #foreach my $key (keys(%tmp)) {
                   8397:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8398:         #}
1.294     matthew  8399:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8400:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8401:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8402:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8403:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8404:     }
1.556     albertel 8405:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8406:     my $user = "$uname:$udom";
                   8407:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8408:     my $reply=cput('classlist',
1.1148    raeburn  8409: 		   {$user => 
1.515     raeburn  8410: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8411: 		   $cdom,$cnum);
1.1148    raeburn  8412:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8413:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8414:     } else { 
1.81      www      8415: 	return 'error: '.$reply;
                   8416:     }
1.297     matthew  8417:     # Add student role to user
1.83      www      8418:     my $uurl='/'.$cid;
1.81      www      8419:     $uurl=~s/\_/\//g;
                   8420:     if ($usec) {
                   8421: 	$uurl.='/'.$usec;
                   8422:     }
1.1148    raeburn  8423:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8424:                              $selfenroll,$context);
                   8425:     if ($result ne 'ok') {
                   8426:         if ($old_entry{$user} ne '') {
                   8427:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8428:         } else {
                   8429:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8430:         }
                   8431:     }
                   8432:     return $result; 
1.21      www      8433: }
                   8434: 
1.556     albertel 8435: sub format_name {
                   8436:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8437:     my $name;
                   8438:     if ($first ne 'lastname') {
                   8439: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8440:     } else {
                   8441: 	if ($lastname=~/\S/) {
                   8442: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8443: 	    $name=~s/\s+,/,/;
                   8444: 	} else {
                   8445: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8446: 	}
                   8447:     }
                   8448:     $name=~s/^\s+//;
                   8449:     $name=~s/\s+$//;
                   8450:     $name=~s/\s+/ /g;
                   8451:     return $name;
                   8452: }
                   8453: 
1.84      www      8454: # ------------------------------------------------- Write to course preferences
                   8455: 
                   8456: sub writecoursepref {
                   8457:     my ($courseid,%prefs)=@_;
                   8458:     $courseid=~s/^\///;
                   8459:     $courseid=~s/\_/\//g;
                   8460:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8461:     my $chome=homeserver($cnum,$cdomain);
                   8462:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8463: 	return 'error: no such course';
                   8464:     }
                   8465:     my $cstring='';
1.800     albertel 8466:     foreach my $pref (keys(%prefs)) {
                   8467: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8468:     }
1.84      www      8469:     $cstring=~s/\&$//;
                   8470:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8471: }
                   8472: 
                   8473: # ---------------------------------------------------------- Make/modify course
                   8474: 
                   8475: sub createcourse {
1.741     raeburn  8476:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8477:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8478:     $url=&declutter($url);
                   8479:     my $cid='';
1.1028    raeburn  8480:     if ($context eq 'requestcourses') {
                   8481:         my $can_create = 0;
                   8482:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8483:         if ($udom eq $ownerdom) {
                   8484:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8485:                                   $context)) {
                   8486:                 $can_create = 1;
                   8487:             }
                   8488:         } else {
                   8489:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8490:                                            $category);
                   8491:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8492:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8493:                 if (@curr > 0) {
                   8494:                     my @options = qw(approval validate autolimit);
                   8495:                     my $optregex = join('|',@options);
                   8496:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8497:                         $can_create = 1;
                   8498:                     }
                   8499:                 }
                   8500:             }
                   8501:         }
                   8502:         if ($can_create) {
                   8503:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8504:                 unless (&allowed('ccc',$udom)) {
                   8505:                     return 'refused'; 
                   8506:                 }
1.1017    raeburn  8507:             }
                   8508:         } else {
                   8509:             return 'refused';
                   8510:         }
1.1028    raeburn  8511:     } elsif (!&allowed('ccc',$udom)) {
                   8512:         return 'refused';
1.84      www      8513:     }
1.1011    raeburn  8514: # --------------------------------------------------------------- Get Unique ID
                   8515:     my $uname;
                   8516:     if ($cnum =~ /^$match_courseid$/) {
                   8517:         my $chome=&homeserver($cnum,$udom,'true');
                   8518:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8519:             $uname = $cnum;
                   8520:         } else {
1.1038    raeburn  8521:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8522:         }
                   8523:     } else {
1.1038    raeburn  8524:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8525:     }
                   8526:     return $uname if ($uname =~ /^error/);
                   8527: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8528:     if (!defined($course_server)) {
                   8529:         if (defined(&domain($udom,'primary'))) {
                   8530:             $course_server = &domain($udom,'primary');
                   8531:         } else {
                   8532:             $course_server = $env{'user.home'}; 
                   8533:         }
                   8534:     }
                   8535:     my %host_servers =
                   8536:         &Apache::lonnet::get_servers($udom,'library');
                   8537:     unless ($host_servers{$course_server}) {
                   8538:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8539:     }
1.84      www      8540: # ------------------------------------------------------------- Make the course
                   8541:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8542:                       $course_server);
1.84      www      8543:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8544:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8545:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8546: 	return 'error: no such course';
                   8547:     }
1.271     www      8548: # ----------------------------------------------------------------- Course made
1.516     raeburn  8549: # log existence
1.1029    raeburn  8550:     my $now = time;
1.918     raeburn  8551:     my $newcourse = {
                   8552:                     $udom.'_'.$uname => {
1.921     raeburn  8553:                                      description => $description,
                   8554:                                      inst_code   => $inst_code,
                   8555:                                      owner       => $course_owner,
                   8556:                                      type        => $crstype,
1.1029    raeburn  8557:                                      creator     => $env{'user.name'}.':'.
                   8558:                                                     $env{'user.domain'},
                   8559:                                      created     => $now,
                   8560:                                      context     => $context,
1.918     raeburn  8561:                                                 },
                   8562:                     };
1.921     raeburn  8563:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8564: # set toplevel url
1.271     www      8565:     my $topurl=$url;
                   8566:     unless ($nonstandard) {
                   8567: # ------------------------------------------ For standard courses, make top url
                   8568:         my $mapurl=&clutter($url);
1.278     www      8569:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8570:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8571: <map>
                   8572: <resource id="1" type="start"></resource>
                   8573: <resource id="2" src="$mapurl"></resource>
                   8574: <resource id="3" type="finish"></resource>
                   8575: <link index="1" from="1" to="2"></link>
                   8576: <link index="2" from="2" to="3"></link>
                   8577: </map>
                   8578: ENDINITMAP
                   8579:         $topurl=&declutter(
1.638     albertel 8580:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8581:                           );
                   8582:     }
                   8583: # ----------------------------------------------------------- Write preferences
1.84      www      8584:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8585:                      ('description'              => $description,
                   8586:                       'url'                      => $topurl,
                   8587:                       'internal.creator'         => $env{'user.name'}.':'.
                   8588:                                                     $env{'user.domain'},
                   8589:                       'internal.created'         => $now,
                   8590:                       'internal.creationcontext' => $context)
                   8591:                     );
1.84      www      8592:     return '/'.$udom.'/'.$uname;
                   8593: }
                   8594: 
1.1011    raeburn  8595: # ------------------------------------------------------------------- Create ID
                   8596: sub generate_coursenum {
1.1038    raeburn  8597:     my ($udom,$crstype) = @_;
1.1011    raeburn  8598:     my $domdesc = &domain($udom);
                   8599:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8600:     my $first;
                   8601:     if ($crstype eq 'Community') {
                   8602:         $first = '0';
                   8603:     } else {
                   8604:         $first = int(1+rand(9)); 
                   8605:     } 
                   8606:     my $uname=$first.
1.1011    raeburn  8607:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8608:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8609:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8610: # ----------------------------------------------- Make sure that does not exist
                   8611:     my $uhome=&homeserver($uname,$udom,'true');
                   8612:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8613:         if ($crstype eq 'Community') {
                   8614:             $first = '0';
                   8615:         } else {
                   8616:             $first = int(1+rand(9));
                   8617:         }
                   8618:         $uname=$first.
1.1011    raeburn  8619:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8620:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8621:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8622:         $uhome=&homeserver($uname,$udom,'true');
                   8623:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8624:             return 'error: unable to generate unique course-ID';
                   8625:         }
                   8626:     }
                   8627:     return $uname;
                   8628: }
                   8629: 
1.813     albertel 8630: sub is_course {
1.1167    droeschl 8631:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8632:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8633: 
                   8634:     return unless $cdom and $cnum;
                   8635: 
                   8636:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8637:         '.');
                   8638: 
                   8639:     return unless exists($courses{$cdom.'_'.$cnum});
                   8640:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8641: }
                   8642: 
1.1015    raeburn  8643: sub store_userdata {
                   8644:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8645:     my $result;
1.1016    raeburn  8646:     if ($datakey ne '') {
1.1013    raeburn  8647:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8648:             if ($udom eq '' || $uname eq '') {
                   8649:                 $udom = $env{'user.domain'};
                   8650:                 $uname = $env{'user.name'};
                   8651:             }
                   8652:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8653:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8654:                 $result = 'error: no_host';
                   8655:             } else {
                   8656:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8657:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8658: 
                   8659:                 my $namevalue='';
                   8660:                 foreach my $key (keys(%{$storehash})) {
                   8661:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8662:                 }
                   8663:                 $namevalue=~s/\&$//;
1.1105    raeburn  8664:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8665:                                   $namevalue,$uhome);
1.1013    raeburn  8666:             }
                   8667:         } else {
                   8668:             $result = 'error: data to store was not a hash reference'; 
                   8669:         }
                   8670:     } else {
                   8671:         $result= 'error: invalid requestkey'; 
                   8672:     }
                   8673:     return $result;
                   8674: }
                   8675: 
1.21      www      8676: # ---------------------------------------------------------- Assign Custom Role
                   8677: 
                   8678: sub assigncustomrole {
1.957     raeburn  8679:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8680:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8681:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8682: }
                   8683: 
                   8684: # ----------------------------------------------------------------- Revoke Role
                   8685: 
                   8686: sub revokerole {
1.957     raeburn  8687:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8688:     my $now=time;
1.965     raeburn  8689:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8690: }
                   8691: 
                   8692: # ---------------------------------------------------------- Revoke Custom Role
                   8693: 
                   8694: sub revokecustomrole {
1.957     raeburn  8695:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8696:     my $now=time;
1.357     www      8697:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8698:            $deleteflag,$selfenroll,$context);
1.17      www      8699: }
                   8700: 
1.533     banghart 8701: # ------------------------------------------------------------ Disk usage
1.535     albertel 8702: sub diskusage {
1.955     raeburn  8703:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8704:     $directorypath =~ s/\/$//;
                   8705:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8706:                        .&escape($getpropath).':'.&escape($uname).':'
                   8707:                        .&escape($udom),homeserver($uname,$udom));
                   8708:     if ($listing eq 'unknown_cmd') {
                   8709:         if ($getpropath) {
                   8710:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8711:         }
                   8712:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8713:     }
1.514     albertel 8714:     return $listing;
1.512     banghart 8715: }
                   8716: 
1.566     banghart 8717: sub is_locked {
1.1096    raeburn  8718:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8719:     my @check;
                   8720:     my $is_locked;
1.1093    raeburn  8721:     push (@check,$file_name);
1.613     albertel 8722:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8723: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8724:     my ($tmp)=keys(%locked);
                   8725:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8726:     
1.566     banghart 8727:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8728:         $is_locked = 'false';
                   8729:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8730:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8731:                $is_locked = 'true';
1.1096    raeburn  8732:                if (ref($which) eq 'ARRAY') {
                   8733:                    push(@{$which},$entry);
                   8734:                } else {
                   8735:                    last;
                   8736:                }
1.745     raeburn  8737:            }
                   8738:        }
1.566     banghart 8739:     } else {
                   8740:         $is_locked = 'false';
                   8741:     }
1.1093    raeburn  8742:     return $is_locked;
1.566     banghart 8743: }
                   8744: 
1.759     albertel 8745: sub declutter_portfile {
                   8746:     my ($file) = @_;
1.833     albertel 8747:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8748:     return $file;
                   8749: }
                   8750: 
1.559     banghart 8751: # ------------------------------------------------------------- Mark as Read Only
                   8752: 
                   8753: sub mark_as_readonly {
                   8754:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8755:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8756:     my ($tmp)=keys(%current_permissions);
                   8757:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8758:     foreach my $file (@{$files}) {
1.759     albertel 8759: 	$file = &declutter_portfile($file);
1.561     banghart 8760:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8761:     }
1.613     albertel 8762:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8763:     return;
                   8764: }
                   8765: 
1.572     banghart 8766: # ------------------------------------------------------------Save Selected Files
                   8767: 
                   8768: sub save_selected_files {
                   8769:     my ($user, $path, @files) = @_;
                   8770:     my $filename = $user."savedfiles";
1.573     banghart 8771:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8772:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8773:     foreach my $file (@files) {
1.620     albertel 8774:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8775:     }
                   8776:     foreach my $file (@other_files) {
1.574     banghart 8777:         print (OUT $file."\n");
1.572     banghart 8778:     }
1.574     banghart 8779:     close (OUT);
1.572     banghart 8780:     return 'ok';
                   8781: }
                   8782: 
1.574     banghart 8783: sub clear_selected_files {
                   8784:     my ($user) = @_;
                   8785:     my $filename = $user."savedfiles";
1.1117    foxr     8786:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8787:     print (OUT undef);
                   8788:     close (OUT);
                   8789:     return ("ok");    
                   8790: }
                   8791: 
1.572     banghart 8792: sub files_in_path {
                   8793:     my ($user, $path) = @_;
                   8794:     my $filename = $user."savedfiles";
                   8795:     my %return_files;
1.1117    foxr     8796:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8797:     while (my $line_in = <IN>) {
1.574     banghart 8798:         chomp ($line_in);
                   8799:         my @paths_and_file = split (m!/!, $line_in);
                   8800:         my $file_part = pop (@paths_and_file);
                   8801:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8802:         $path_part.='/';
                   8803:         my $path_and_file = $path_part.$file_part;
                   8804:         if ($path_part eq $path) {
                   8805:             $return_files{$file_part}= 'selected';
                   8806:         }
                   8807:     }
1.574     banghart 8808:     close (IN);
                   8809:     return (\%return_files);
1.572     banghart 8810: }
                   8811: 
                   8812: # called in portfolio select mode, to show files selected NOT in current directory
                   8813: sub files_not_in_path {
                   8814:     my ($user, $path) = @_;
                   8815:     my $filename = $user."savedfiles";
                   8816:     my @return_files;
                   8817:     my $path_part;
1.1117    foxr     8818:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8819:     while (my $line = <IN>) {
1.572     banghart 8820:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8821:         my @paths_and_file = split(m|/|, $line);
                   8822:         my $file_part = pop(@paths_and_file);
                   8823:         chomp($file_part);
                   8824:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8825:         $path_part .= '/';
                   8826:         my $path_and_file = $path_part.$file_part;
                   8827:         if ($path_part ne $path) {
1.800     albertel 8828:             push(@return_files, ($path_and_file));
1.572     banghart 8829:         }
                   8830:     }
1.800     albertel 8831:     close(OUT);
1.574     banghart 8832:     return (@return_files);
1.572     banghart 8833: }
                   8834: 
1.745     raeburn  8835: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8836: 
1.745     raeburn  8837: sub get_portfile_permissions {
                   8838:     my ($domain,$user) = @_;
1.613     albertel 8839:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8840:     my ($tmp)=keys(%current_permissions);
                   8841:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8842:     return \%current_permissions;
                   8843: }
                   8844: 
                   8845: #---------------------------------------------Get portfolio file access controls
                   8846: 
1.749     raeburn  8847: sub get_access_controls {
1.745     raeburn  8848:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8849:     my %access;
                   8850:     my $real_file = $file;
                   8851:     $file =~ s/\.meta$//;
1.745     raeburn  8852:     if (defined($file)) {
1.749     raeburn  8853:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8854:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8855:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8856:             }
                   8857:         }
1.745     raeburn  8858:     } else {
1.749     raeburn  8859:         foreach my $key (keys(%{$current_permissions})) {
                   8860:             if ($key =~ /\0accesscontrol$/) {
                   8861:                 if (defined($group)) {
                   8862:                     if ($key !~ m-^\Q$group\E/-) {
                   8863:                         next;
                   8864:                     }
                   8865:                 }
                   8866:                 my ($fullpath) = split(/\0/,$key);
                   8867:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8868:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8869:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8870:                     }
                   8871:                 }
                   8872:             }
                   8873:         }
                   8874:     }
                   8875:     return %access;
                   8876: }
                   8877: 
                   8878: sub modify_access_controls {
                   8879:     my ($file_name,$changes,$domain,$user)=@_;
                   8880:     my ($outcome,$deloutcome);
                   8881:     my %store_permissions;
                   8882:     my %new_values;
                   8883:     my %new_control;
                   8884:     my %translation;
                   8885:     my @deletions = ();
                   8886:     my $now = time;
                   8887:     if (exists($$changes{'activate'})) {
                   8888:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8889:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8890:             my $numnew = scalar(@newitems);
                   8891:             for (my $i=0; $i<$numnew; $i++) {
                   8892:                 my $newkey = $newitems[$i];
                   8893:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8894:                 if ($newkey =~ /^\d+:/) { 
                   8895:                     $newkey =~ s/^(\d+)/$newid/;
                   8896:                     $translation{$1} = $newid;
                   8897:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8898:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8899:                     $translation{$1} = $newid;
                   8900:                 }
1.749     raeburn  8901:                 $new_values{$file_name."\0".$newkey} = 
                   8902:                                           $$changes{'activate'}{$newitems[$i]};
                   8903:                 $new_control{$newkey} = $now;
                   8904:             }
                   8905:         }
                   8906:     }
                   8907:     my %todelete;
                   8908:     my %changed_items;
                   8909:     foreach my $action ('delete','update') {
                   8910:         if (exists($$changes{$action})) {
                   8911:             if (ref($$changes{$action}) eq 'HASH') {
                   8912:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8913:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8914:                     if ($action eq 'delete') { 
                   8915:                         $todelete{$itemnum} = 1;
                   8916:                     } else {
                   8917:                         $changed_items{$itemnum} = $key;
                   8918:                     }
                   8919:                 }
1.745     raeburn  8920:             }
                   8921:         }
1.749     raeburn  8922:     }
                   8923:     # get lock on access controls for file.
                   8924:     my $lockhash = {
                   8925:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8926:                                                        ':'.$env{'user.domain'},
                   8927:                    }; 
                   8928:     my $tries = 0;
                   8929:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8930:    
                   8931:     while (($gotlock ne 'ok') && $tries <3) {
                   8932:         $tries ++;
                   8933:         sleep 1;
                   8934:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8935:     }
                   8936:     if ($gotlock eq 'ok') {
                   8937:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8938:         my ($tmp)=keys(%curr_permissions);
                   8939:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8940:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8941:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8942:             if (ref($curr_controls) eq 'HASH') {
                   8943:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8944:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8945:                     if (defined($todelete{$itemnum})) {
                   8946:                         push(@deletions,$file_name."\0".$control_item);
                   8947:                     } else {
                   8948:                         if (defined($changed_items{$itemnum})) {
                   8949:                             $new_control{$changed_items{$itemnum}} = $now;
                   8950:                             push(@deletions,$file_name."\0".$control_item);
                   8951:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8952:                         } else {
                   8953:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8954:                         }
                   8955:                     }
1.745     raeburn  8956:                 }
                   8957:             }
                   8958:         }
1.970     raeburn  8959:         my ($group);
                   8960:         if (&is_course($domain,$user)) {
                   8961:             ($group,my $file) = split(/\//,$file_name,2);
                   8962:         }
1.749     raeburn  8963:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8964:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8965:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8966:         #  remove lock
                   8967:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8968:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8969:         my $sqlresult =
1.970     raeburn  8970:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8971:                                     $group);
1.749     raeburn  8972:     } else {
                   8973:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8974:     }
1.749     raeburn  8975:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8976: }
                   8977: 
1.827     raeburn  8978: sub make_public_indefinitely {
                   8979:     my ($requrl) = @_;
                   8980:     my $now = time;
                   8981:     my $action = 'activate';
                   8982:     my $aclnum = 0;
                   8983:     if (&is_portfolio_url($requrl)) {
                   8984:         my (undef,$udom,$unum,$file_name,$group) =
                   8985:             &parse_portfolio_url($requrl);
                   8986:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8987:         my %access_controls = &get_access_controls($current_perms,
                   8988:                                                    $group,$file_name);
                   8989:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8990:             my ($num,$scope,$end,$start) = 
                   8991:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8992:             if ($scope eq 'public') {
                   8993:                 if ($start <= $now && $end == 0) {
                   8994:                     $action = 'none';
                   8995:                 } else {
                   8996:                     $action = 'update';
                   8997:                     $aclnum = $num;
                   8998:                 }
                   8999:                 last;
                   9000:             }
                   9001:         }
                   9002:         if ($action eq 'none') {
                   9003:              return 'ok';
                   9004:         } else {
                   9005:             my %changes;
                   9006:             my $newend = 0;
                   9007:             my $newstart = $now;
                   9008:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9009:             $changes{$action}{$newkey} = {
                   9010:                 type => 'public',
                   9011:                 time => {
                   9012:                     start => $newstart,
                   9013:                     end   => $newend,
                   9014:                 },
                   9015:             };
                   9016:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9017:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9018:             return $outcome;
                   9019:         }
                   9020:     } else {
                   9021:         return 'invalid';
                   9022:     }
                   9023: }
                   9024: 
1.745     raeburn  9025: #------------------------------------------------------Get Marked as Read Only
                   9026: 
                   9027: sub get_marked_as_readonly {
                   9028:     my ($domain,$user,$what,$group) = @_;
                   9029:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9030:     my @readonly_files;
1.629     banghart 9031:     my $cmp1=$what;
                   9032:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9033:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9034:         if (defined($group)) {
                   9035:             if ($file_name !~ m-^\Q$group\E/-) {
                   9036:                 next;
                   9037:             }
                   9038:         }
1.561     banghart 9039:         if (ref($value) eq "ARRAY"){
                   9040:             foreach my $stored_what (@{$value}) {
1.629     banghart 9041:                 my $cmp2=$stored_what;
1.759     albertel 9042:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9043:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9044:                 }
1.629     banghart 9045:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9046:                     push(@readonly_files, $file_name);
1.745     raeburn  9047:                     last;
1.563     banghart 9048:                 } elsif (!defined($what)) {
                   9049:                     push(@readonly_files, $file_name);
1.745     raeburn  9050:                     last;
1.561     banghart 9051:                 }
                   9052:             }
1.745     raeburn  9053:         }
1.561     banghart 9054:     }
                   9055:     return @readonly_files;
                   9056: }
1.577     banghart 9057: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9058: 
1.577     banghart 9059: sub get_marked_as_readonly_hash {
1.745     raeburn  9060:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9061:     my %readonly_files;
1.745     raeburn  9062:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9063:         if (defined($group)) {
                   9064:             if ($file_name !~ m-^\Q$group\E/-) {
                   9065:                 next;
                   9066:             }
                   9067:         }
1.577     banghart 9068:         if (ref($value) eq "ARRAY"){
                   9069:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9070:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9071:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9072:                         if ($lock_descriptor eq 'graded') {
                   9073:                             $readonly_files{$file_name} = 'graded';
                   9074:                         } elsif ($lock_descriptor eq 'handback') {
                   9075:                             $readonly_files{$file_name} = 'handback';
                   9076:                         } else {
                   9077:                             if (!exists($readonly_files{$file_name})) {
                   9078:                                 $readonly_files{$file_name} = 'locked';
                   9079:                             }
                   9080:                         }
1.745     raeburn  9081:                     }
1.750     banghart 9082:                 } 
1.577     banghart 9083:             }
                   9084:         } 
                   9085:     }
                   9086:     return %readonly_files;
                   9087: }
1.559     banghart 9088: # ------------------------------------------------------------ Unmark as Read Only
                   9089: 
                   9090: sub unmark_as_readonly {
1.629     banghart 9091:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9092:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9093:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9094:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9095:     my $symb_crs = $what;
                   9096:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9097:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9098:     my ($tmp)=keys(%current_permissions);
                   9099:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9100:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9101:     foreach my $file (@readonly_files) {
1.759     albertel 9102: 	my $clean_file = &declutter_portfile($file);
                   9103: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9104: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9105:         my @new_locks;
                   9106:         my @del_keys;
                   9107:         if (ref($current_locks) eq "ARRAY"){
                   9108:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9109:                 my $compare=$locker;
1.749     raeburn  9110:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9111:                     $compare=join('',@{$locker});
1.746     raeburn  9112:                     if ($compare ne $symb_crs) {
                   9113:                         push(@new_locks, $locker);
                   9114:                     }
1.563     banghart 9115:                 }
                   9116:             }
1.650     albertel 9117:             if (scalar(@new_locks) > 0) {
1.563     banghart 9118:                 $current_permissions{$file} = \@new_locks;
                   9119:             } else {
                   9120:                 push(@del_keys, $file);
1.613     albertel 9121:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9122:                 delete($current_permissions{$file});
1.563     banghart 9123:             }
                   9124:         }
1.561     banghart 9125:     }
1.613     albertel 9126:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9127:     return;
                   9128: }
1.512     banghart 9129: 
1.17      www      9130: # ------------------------------------------------------------ Directory lister
                   9131: 
                   9132: sub dirlist {
1.955     raeburn  9133:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9134:     $uri=~s/^\///;
                   9135:     $uri=~s/\/$//;
1.253     stredwic 9136:     my ($udom, $uname);
1.955     raeburn  9137:     if ($getuserdir) {
1.253     stredwic 9138:         $udom = $userdomain;
                   9139:         $uname = $username;
1.955     raeburn  9140:     } else {
                   9141:         (undef,$udom,$uname)=split(/\//,$uri);
                   9142:         if(defined($userdomain)) {
                   9143:             $udom = $userdomain;
                   9144:         }
                   9145:         if(defined($username)) {
                   9146:             $uname = $username;
                   9147:         }
1.253     stredwic 9148:     }
1.955     raeburn  9149:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9150: 
1.955     raeburn  9151:     $dirRoot = $perlvar{'lonDocRoot'};
                   9152:     if (defined($getpropath)) {
                   9153:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9154:         $dirRoot =~ s/\/$//;
1.955     raeburn  9155:     } elsif (defined($getuserdir)) {
                   9156:         my $subdir=$uname.'__';
                   9157:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9158:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9159:                    ."/$udom/$subdir/$uname";
                   9160:     } elsif (defined($alternateRoot)) {
                   9161:         $dirRoot = $alternateRoot;
1.751     banghart 9162:     }
1.253     stredwic 9163: 
                   9164:     if($udom) {
                   9165:         if($uname) {
1.1135    raeburn  9166:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9167:             if ($uhome eq 'no_host') {
                   9168:                 return ([],'no_host');
                   9169:             }
1.955     raeburn  9170:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9171:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9172:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9173:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9174:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9175:             } else {
                   9176:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9177:             }
1.605     matthew  9178:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9179:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9180:                 @listing_results = split(/:/,$listing);
                   9181:             } else {
                   9182:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9183:             }
1.1135    raeburn  9184:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9185:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9186:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9187:                 return ([],$listing);
                   9188:             } else {
                   9189:                 return (\@listing_results);
1.1135    raeburn  9190:             }
1.955     raeburn  9191:         } elsif(!$alternateRoot) {
1.1136    raeburn  9192:             my (%allusers,%listerror);
1.841     albertel 9193: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9194:  	    foreach my $tryserver (keys(%servers)) {
                   9195:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9196:                                   &escape($udom),$tryserver);
                   9197:                 if ($listing eq 'unknown_cmd') {
                   9198: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9199: 				      $udom, $tryserver);
                   9200:                 } else {
                   9201:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9202:                 }
1.841     albertel 9203: 		if ($listing eq 'unknown_cmd') {
                   9204: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9205: 				      $udom, $tryserver);
                   9206: 		    @listing_results = split(/:/,$listing);
                   9207: 		} else {
                   9208: 		    @listing_results =
                   9209: 			map { &unescape($_); } split(/:/,$listing);
                   9210: 		}
1.1136    raeburn  9211:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9212:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9213:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9214:                     $listerror{$tryserver} = $listing;
                   9215:                 } else {
1.841     albertel 9216: 		    foreach my $line (@listing_results) {
                   9217: 			my ($entry) = split(/&/,$line,2);
                   9218: 			$allusers{$entry} = 1;
                   9219: 		    }
                   9220: 		}
1.253     stredwic 9221:             }
1.1136    raeburn  9222:             my @alluserslist=();
1.800     albertel 9223:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9224:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9225:             }
1.1136    raeburn  9226:             return (\@alluserslist);
1.253     stredwic 9227:         } else {
1.1136    raeburn  9228:             return ([],'missing username');
1.253     stredwic 9229:         }
1.955     raeburn  9230:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9231:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9232:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9233:         return (\@all_domains);
1.955     raeburn  9234:     } else {
1.1136    raeburn  9235:         return ([],'missing domain');
1.275     stredwic 9236:     }
                   9237: }
                   9238: 
                   9239: # --------------------------------------------- GetFileTimestamp
                   9240: # This function utilizes dirlist and returns the date stamp for
                   9241: # when it was last modified.  It will also return an error of -1
                   9242: # if an error occurs
                   9243: 
                   9244: sub GetFileTimestamp {
1.955     raeburn  9245:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9246:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9247:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9248:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9249:                                     undef,$getuserdir);
                   9250:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9251:         return -1;
                   9252:     }
                   9253:     if (ref($fileref) eq 'ARRAY') {
                   9254:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9255:         # @stats contains first the filename, then the stat output
                   9256:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9257:     } else {
                   9258:         return -1;
1.253     stredwic 9259:     }
1.26      www      9260: }
                   9261: 
1.712     albertel 9262: sub stat_file {
                   9263:     my ($uri) = @_;
1.787     albertel 9264:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9265: 
1.955     raeburn  9266:     my ($udom,$uname,$file);
1.712     albertel 9267:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9268: 	($udom,$uname,$file) =
1.811     albertel 9269: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9270: 	$file = 'userfiles/'.$file;
                   9271:     }
                   9272:     if ($uri =~ m-^/res/-) {
                   9273: 	($udom,$uname) = 
1.807     albertel 9274: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9275: 	$file = $uri;
                   9276:     }
                   9277: 
                   9278:     if (!$udom || !$uname || !$file) {
                   9279: 	# unable to handle the uri
                   9280: 	return ();
                   9281:     }
1.956     raeburn  9282:     my $getpropath;
                   9283:     if ($file =~ /^userfiles\//) {
                   9284:         $getpropath = 1;
                   9285:     }
1.1136    raeburn  9286:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9287:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9288:         return ();
                   9289:     } else {
                   9290:         if (ref($listref) eq 'ARRAY') {
                   9291:             my @stats = split('&',$listref->[0]);
                   9292: 	    shift(@stats); #filename is first
                   9293: 	    return @stats;
                   9294:         }
1.712     albertel 9295:     }
                   9296:     return ();
                   9297: }
                   9298: 
1.26      www      9299: # -------------------------------------------------------- Value of a Condition
                   9300: 
1.713     albertel 9301: # gets the value of a specific preevaluated condition
                   9302: #    stored in the string  $env{user.state.<cid>}
                   9303: # or looks up a condition reference in the bighash and if if hasn't
                   9304: # already been evaluated recurses into docondval to get the value of
                   9305: # the condition, then memoizing it to 
                   9306: #   $env{user.state.<cid>.<condition>}
1.40      www      9307: sub directcondval {
                   9308:     my $number=shift;
1.620     albertel 9309:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9310: 	&Apache::lonuserstate::evalstate();
                   9311:     }
1.713     albertel 9312:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9313: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9314:     } elsif ($number =~ /^_/) {
                   9315: 	my $sub_condition;
                   9316: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9317: 		&GDBM_READER(),0640)) {
                   9318: 	    $sub_condition=$bighash{'conditions'.$number};
                   9319: 	    untie(%bighash);
                   9320: 	}
                   9321: 	my $value = &docondval($sub_condition);
1.949     raeburn  9322: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9323: 	return $value;
                   9324:     }
1.620     albertel 9325:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9326:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9327:     } else {
                   9328:        return 2;
                   9329:     }
                   9330: }
                   9331: 
1.713     albertel 9332: # get the collection of conditions for this resource
1.26      www      9333: sub condval {
                   9334:     my $condidx=shift;
1.54      www      9335:     my $allpathcond='';
1.713     albertel 9336:     foreach my $cond (split(/\|/,$condidx)) {
                   9337: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9338: 	    $allpathcond.=
                   9339: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9340: 	}
1.191     harris41 9341:     }
1.54      www      9342:     $allpathcond=~s/\|$//;
1.713     albertel 9343:     return &docondval($allpathcond);
                   9344: }
                   9345: 
                   9346: #evaluates an expression of conditions
                   9347: sub docondval {
                   9348:     my ($allpathcond) = @_;
                   9349:     my $result=0;
                   9350:     if ($env{'request.course.id'}
                   9351: 	&& defined($allpathcond)) {
                   9352: 	my $operand='|';
                   9353: 	my @stack;
                   9354: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9355: 	    if ($chunk eq '(') {
                   9356: 		push @stack,($operand,$result);
                   9357: 	    } elsif ($chunk eq ')') {
                   9358: 		my $before=pop @stack;
                   9359: 		if (pop @stack eq '&') {
                   9360: 		    $result=$result>$before?$before:$result;
                   9361: 		} else {
                   9362: 		    $result=$result>$before?$result:$before;
                   9363: 		}
                   9364: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9365: 		$operand=$chunk;
                   9366: 	    } else {
                   9367: 		my $new=directcondval($chunk);
                   9368: 		if ($operand eq '&') {
                   9369: 		    $result=$result>$new?$new:$result;
                   9370: 		} else {
                   9371: 		    $result=$result>$new?$result:$new;
                   9372: 		}
                   9373: 	    }
                   9374: 	}
1.26      www      9375:     }
                   9376:     return $result;
1.421     albertel 9377: }
                   9378: 
                   9379: # ---------------------------------------------------- Devalidate courseresdata
                   9380: 
                   9381: sub devalidatecourseresdata {
                   9382:     my ($coursenum,$coursedomain)=@_;
                   9383:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9384:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9385: }
                   9386: 
1.763     www      9387: 
1.200     www      9388: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9389: #
                   9390: #  Parameters:
                   9391: #      $coursenum    - Number of the course.
                   9392: #      $coursedomain - Domain at which the course was created.
                   9393: #  Returns:
                   9394: #     A hash of the course parameters along (I think) with timestamps
                   9395: #     and version info.
1.877     foxr     9396: 
1.624     albertel 9397: sub get_courseresdata {
                   9398:     my ($coursenum,$coursedomain)=@_;
1.200     www      9399:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9400:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9401:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9402:     my %dumpreply;
1.417     albertel 9403:     unless (defined($cached)) {
1.624     albertel 9404: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9405: 	$result=\%dumpreply;
1.251     albertel 9406: 	my ($tmp) = keys(%dumpreply);
                   9407: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9408: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9409: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9410: 	    return $tmp;
1.416     albertel 9411: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9412: 	    $result=undef;
1.599     albertel 9413: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9414: 	}
                   9415:     }
1.624     albertel 9416:     return $result;
                   9417: }
                   9418: 
1.633     albertel 9419: sub devalidateuserresdata {
                   9420:     my ($uname,$udom)=@_;
                   9421:     my $hashid="$udom:$uname";
                   9422:     &devalidate_cache_new('userres',$hashid);
                   9423: }
                   9424: 
1.624     albertel 9425: sub get_userresdata {
                   9426:     my ($uname,$udom)=@_;
                   9427:     #most student don\'t have any data set, check if there is some data
                   9428:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9429: 
                   9430:     my $hashid="$udom:$uname";
                   9431:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9432:     if (!defined($cached)) {
                   9433: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9434: 	$result=\%resourcedata;
                   9435: 	&do_cache_new('userres',$hashid,$result,600);
                   9436:     }
                   9437:     my ($tmp)=keys(%$result);
                   9438:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9439: 	return $result;
                   9440:     }
                   9441:     #error 2 occurs when the .db doesn't exist
                   9442:     if ($tmp!~/error: 2 /) {
1.672     albertel 9443: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9444: 		 " Trying to get resource data for ".
                   9445: 		 $uname." at ".$udom.": ".
                   9446: 		 $tmp."</font>");
                   9447:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9448: 	#&EXT_cache_set($udom,$uname);
                   9449: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9450: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9451:     }
                   9452:     return $tmp;
                   9453: }
1.879     foxr     9454: #----------------------------------------------- resdata - return resource data
                   9455: #  Purpose:
                   9456: #    Return resource data for either users or for a course.
                   9457: #  Parameters:
                   9458: #     $name      - Course/user name.
                   9459: #     $domain    - Name of the domain the user/course is registered on.
                   9460: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9461: #     @which     - Array of names of resources desired.
                   9462: #  Returns:
                   9463: #     The value of the first reasource in @which that is found in the
                   9464: #     resource hash.
                   9465: #  Exceptional Conditions:
                   9466: #     If the $type passed in is not valid (not the string 'course' or 
                   9467: #     'user', an undefined  reference is returned.
                   9468: #     If none of the resources are found, an undef is returned
1.624     albertel 9469: sub resdata {
                   9470:     my ($name,$domain,$type,@which)=@_;
                   9471:     my $result;
                   9472:     if ($type eq 'course') {
                   9473: 	$result=&get_courseresdata($name,$domain);
                   9474:     } elsif ($type eq 'user') {
                   9475: 	$result=&get_userresdata($name,$domain);
                   9476:     }
                   9477:     if (!ref($result)) { return $result; }    
1.251     albertel 9478:     foreach my $item (@which) {
1.927     albertel 9479: 	if (defined($result->{$item->[0]})) {
                   9480: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9481: 	}
1.250     albertel 9482:     }
1.291     albertel 9483:     return undef;
1.200     www      9484: }
                   9485: 
1.379     matthew  9486: #
                   9487: # EXT resource caching routines
                   9488: #
                   9489: 
                   9490: sub clear_EXT_cache_status {
1.383     albertel 9491:     &delenv('cache.EXT.');
1.379     matthew  9492: }
                   9493: 
                   9494: sub EXT_cache_status {
                   9495:     my ($target_domain,$target_user) = @_;
1.383     albertel 9496:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9497:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9498:         # We know already the user has no data
                   9499:         return 1;
                   9500:     } else {
                   9501:         return 0;
                   9502:     }
                   9503: }
                   9504: 
                   9505: sub EXT_cache_set {
                   9506:     my ($target_domain,$target_user) = @_;
1.383     albertel 9507:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9508:     #&appenv({$cachename => time});
1.379     matthew  9509: }
                   9510: 
1.28      www      9511: # --------------------------------------------------------- Value of a Variable
1.58      www      9512: sub EXT {
1.715     albertel 9513: 
1.395     albertel 9514:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9515:     unless ($varname) { return ''; }
1.218     albertel 9516:     #get real user name/domain, courseid and symb
                   9517:     my $courseid;
1.359     albertel 9518:     my $publicuser;
1.427     www      9519:     if ($symbparm) {
                   9520: 	$symbparm=&get_symb_from_alias($symbparm);
                   9521:     }
1.218     albertel 9522:     if (!($uname && $udom)) {
1.790     albertel 9523:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9524:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9525:     } else {
1.620     albertel 9526: 	$courseid=$env{'request.course.id'};
1.218     albertel 9527:     }
1.48      www      9528:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9529:     my $rest;
1.320     albertel 9530:     if (defined($therest[0])) {
1.48      www      9531:        $rest=join('.',@therest);
                   9532:     } else {
                   9533:        $rest='';
                   9534:     }
1.320     albertel 9535: 
1.57      www      9536:     my $qualifierrest=$qualifier;
                   9537:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9538:     my $spacequalifierrest=$space;
                   9539:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9540:     if ($realm eq 'user') {
1.48      www      9541: # --------------------------------------------------------------- user.resource
                   9542: 	if ($space eq 'resource') {
1.651     albertel 9543: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9544: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9545: 		 &&
1.744     albertel 9546: 		 ($symbparm eq &symbread()) ) {	
                   9547: 		# if we are in the middle of processing the resource the
                   9548: 		# get the value we are planning on committing
                   9549:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9550:                     return $Apache::lonhomework::results{$qualifierrest};
                   9551:                 } else {
                   9552:                     return $Apache::lonhomework::history{$qualifierrest};
                   9553:                 }
1.335     albertel 9554: 	    } else {
1.359     albertel 9555: 		my %restored;
1.620     albertel 9556: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9557: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9558: 		} else {
                   9559: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9560: 		}
1.335     albertel 9561: 		return $restored{$qualifierrest};
                   9562: 	    }
1.48      www      9563: # ----------------------------------------------------------------- user.access
                   9564:         } elsif ($space eq 'access') {
1.218     albertel 9565: 	    # FIXME - not supporting calls for a specific user
1.48      www      9566:             return &allowed($qualifier,$rest);
                   9567: # ------------------------------------------ user.preferences, user.environment
                   9568:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9569: 	    if (($uname eq $env{'user.name'}) &&
                   9570: 		($udom eq $env{'user.domain'})) {
                   9571: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9572: 	    } else {
1.359     albertel 9573: 		my %returnhash;
                   9574: 		if (!$publicuser) {
                   9575: 		    %returnhash=&userenvironment($udom,$uname,
                   9576: 						 $qualifierrest);
                   9577: 		}
1.218     albertel 9578: 		return $returnhash{$qualifierrest};
                   9579: 	    }
1.48      www      9580: # ----------------------------------------------------------------- user.course
                   9581:         } elsif ($space eq 'course') {
1.218     albertel 9582: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9583:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9584: # ------------------------------------------------------------------- user.role
                   9585:         } elsif ($space eq 'role') {
1.218     albertel 9586: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9587:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9588:             if ($qualifier eq 'value') {
                   9589: 		return $role;
                   9590:             } elsif ($qualifier eq 'extent') {
                   9591:                 return $where;
                   9592:             }
                   9593: # ----------------------------------------------------------------- user.domain
                   9594:         } elsif ($space eq 'domain') {
1.218     albertel 9595:             return $udom;
1.48      www      9596: # ------------------------------------------------------------------- user.name
                   9597:         } elsif ($space eq 'name') {
1.218     albertel 9598:             return $uname;
1.48      www      9599: # ---------------------------------------------------- Any other user namespace
1.29      www      9600:         } else {
1.359     albertel 9601: 	    my %reply;
                   9602: 	    if (!$publicuser) {
                   9603: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9604: 	    }
                   9605: 	    return $reply{$qualifierrest};
1.48      www      9606:         }
1.236     www      9607:     } elsif ($realm eq 'query') {
                   9608: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9609:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9610: 						[$spacequalifierrest]);
1.620     albertel 9611: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9612:    } elsif ($realm eq 'request') {
1.48      www      9613: # ------------------------------------------------------------- request.browser
                   9614:         if ($space eq 'browser') {
1.1145    bisitz   9615:             return $env{'browser.'.$qualifier};
1.57      www      9616: # ------------------------------------------------------------ request.filename
                   9617:         } else {
1.620     albertel 9618:             return $env{'request.'.$spacequalifierrest};
1.29      www      9619:         }
1.28      www      9620:     } elsif ($realm eq 'course') {
1.48      www      9621: # ---------------------------------------------------------- course.description
1.620     albertel 9622:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9623:     } elsif ($realm eq 'resource') {
1.165     www      9624: 
1.620     albertel 9625: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9626: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9627: 	}
1.693     albertel 9628: 
                   9629: 	if ($space eq 'title') {
                   9630: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9631: 	    return &gettitle($symbparm);
                   9632: 	}
                   9633: 	
                   9634: 	if ($space eq 'map') {
                   9635: 	    my ($map) = &decode_symb($symbparm);
                   9636: 	    return &symbread($map);
                   9637: 	}
1.905     albertel 9638: 	if ($space eq 'filename') {
                   9639: 	    if ($symbparm) {
                   9640: 		return &clutter((&decode_symb($symbparm))[2]);
                   9641: 	    }
                   9642: 	    return &hreflocation('',$env{'request.filename'});
                   9643: 	}
1.693     albertel 9644: 
                   9645: 	my ($section, $group, @groups);
1.593     albertel 9646: 	my ($courselevelm,$courselevel);
1.539     albertel 9647: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9648: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9649: 
1.218     albertel 9650: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9651: 
1.60      www      9652: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9653: 	    my $symbp=$symbparm;
1.735     albertel 9654: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9655: 
                   9656: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9657: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9658: 
1.620     albertel 9659: 	    if (($env{'user.name'} eq $uname) &&
                   9660: 		($env{'user.domain'} eq $udom)) {
                   9661: 		$section=$env{'request.course.sec'};
1.733     raeburn  9662:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9663:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9664: 	    } else {
1.539     albertel 9665: 		if (! defined($usection)) {
1.551     albertel 9666: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9667: 		} else {
                   9668: 		    $section = $usection;
                   9669: 		}
1.733     raeburn  9670:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9671: 	    }
                   9672: 
                   9673: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9674: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9675: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9676: 
1.593     albertel 9677: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9678: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9679: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9680: 
1.60      www      9681: # ----------------------------------------------------------- first, check user
1.624     albertel 9682: 
                   9683: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9684: 				       ([$courselevelr,'resource'],
                   9685: 					[$courselevelm,'map'     ],
                   9686: 					[$courselevel, 'course'  ]));
1.931     albertel 9687: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9688: 
1.594     albertel 9689: # ------------------------------------------------ second, check some of course
1.684     raeburn  9690:             my $coursereply;
1.691     raeburn  9691:             if (@groups > 0) {
                   9692:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9693:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9694:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9695:             }
1.96      www      9696: 
1.684     raeburn  9697: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9698: 				  $env{'course.'.$courseid.'.domain'},
                   9699: 				  'course',
                   9700: 				  ([$seclevelr,   'resource'],
                   9701: 				   [$seclevelm,   'map'     ],
                   9702: 				   [$seclevel,    'course'  ],
                   9703: 				   [$courselevelr,'resource']));
                   9704: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9705: 
1.60      www      9706: # ------------------------------------------------------ third, check map parms
1.218     albertel 9707: 	    my %parmhash=();
                   9708: 	    my $thisparm='';
                   9709: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9710: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9711: 		    &GDBM_READER(),0640)) {
1.218     albertel 9712: 		$thisparm=$parmhash{$symbparm};
                   9713: 		untie(%parmhash);
                   9714: 	    }
1.927     albertel 9715: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9716: 	}
1.594     albertel 9717: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9718: 
1.218     albertel 9719: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9720: 	my $filename;
                   9721: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9722: 	if ($symbparm) {
1.409     www      9723: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9724: 	} else {
1.620     albertel 9725: 	    $filename=$env{'request.filename'};
1.282     albertel 9726: 	}
                   9727: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9728: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9729: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9730: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9731: 
1.927     albertel 9732: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9733: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9734: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9735: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9736: 				     $env{'course.'.$courseid.'.domain'},
                   9737: 				     'course',
1.927     albertel 9738: 				     ([$courselevelm,'map'   ],
                   9739: 				      [$courselevel, 'course']));
                   9740: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9741: 	}
1.145     www      9742: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9743: 	unless ($space eq '0') {
1.336     albertel 9744: 	    my @parts=split(/_/,$space);
                   9745: 	    my $id=pop(@parts);
                   9746: 	    my $part=join('_',@parts);
                   9747: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9748: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9749: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9750: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9751: 	}
1.395     albertel 9752: 	if ($recurse) { return undef; }
                   9753: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9754: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9755: # ---------------------------------------------------- Any other user namespace
                   9756:     } elsif ($realm eq 'environment') {
                   9757: # ----------------------------------------------------------------- environment
1.620     albertel 9758: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9759: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9760: 	} else {
1.770     albertel 9761: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9762: 		return '';
                   9763: 	    }
1.219     albertel 9764: 	    my %returnhash=&userenvironment($udom,$uname,
                   9765: 					    $spacequalifierrest);
                   9766: 	    return $returnhash{$spacequalifierrest};
                   9767: 	}
1.28      www      9768:     } elsif ($realm eq 'system') {
1.48      www      9769: # ----------------------------------------------------------------- system.time
                   9770: 	if ($space eq 'time') {
                   9771: 	    return time;
                   9772:         }
1.696     albertel 9773:     } elsif ($realm eq 'server') {
                   9774: # ----------------------------------------------------------------- system.time
                   9775: 	if ($space eq 'name') {
                   9776: 	    return $ENV{'SERVER_NAME'};
                   9777:         }
1.28      www      9778:     }
1.48      www      9779:     return '';
1.61      www      9780: }
                   9781: 
1.927     albertel 9782: sub get_reply {
                   9783:     my ($reply_value) = @_;
1.940     raeburn  9784:     if (ref($reply_value) eq 'ARRAY') {
                   9785:         if (wantarray) {
                   9786: 	    return @$reply_value;
                   9787:         }
                   9788:         return $reply_value->[0];
                   9789:     } else {
                   9790:         return $reply_value;
1.927     albertel 9791:     }
                   9792: }
                   9793: 
1.691     raeburn  9794: sub check_group_parms {
                   9795:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9796:     my @groupitems = ();
                   9797:     my $resultitem;
1.927     albertel 9798:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9799:     foreach my $group (@{$groups}) {
                   9800:         foreach my $level (@levels) {
1.927     albertel 9801:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9802:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9803:         }
                   9804:     }
                   9805:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9806:                             $env{'course.'.$courseid.'.domain'},
                   9807:                                      'course',@groupitems);
                   9808:     return $coursereply;
                   9809: }
                   9810: 
                   9811: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9812:     my ($courseid,@groups) = @_;
                   9813:     @groups = sort(@groups);
1.691     raeburn  9814:     return @groups;
                   9815: }
                   9816: 
1.395     albertel 9817: sub packages_tab_default {
                   9818:     my ($uri,$varname)=@_;
                   9819:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9820: 
                   9821:     my (@extension,@specifics,$do_default);
                   9822:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9823: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9824: 	if ($pack_type eq 'default') {
                   9825: 	    $do_default=1;
                   9826: 	} elsif ($pack_type eq 'extension') {
                   9827: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9828: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9829: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9830: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9831: 	}
                   9832:     }
                   9833:     # first look for a package that matches the requested part id
                   9834:     foreach my $package (@specifics) {
                   9835: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9836: 	next if ($pack_part ne $part);
                   9837: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9838: 	    return $packagetab{"$pack_type&$name&default"};
                   9839: 	}
                   9840:     }
                   9841:     # look for any possible matching non extension_ package
                   9842:     foreach my $package (@specifics) {
                   9843: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9844: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9845: 	    return $packagetab{"$pack_type&$name&default"};
                   9846: 	}
1.585     albertel 9847: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9848: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9849: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9850: 	}
                   9851:     }
1.738     albertel 9852:     # look for any posible extension_ match
                   9853:     foreach my $package (@extension) {
                   9854: 	my ($package,$pack_type)=@{$package};
                   9855: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9856: 	    return $packagetab{"$pack_type&$name&default"};
                   9857: 	}
                   9858: 	if (defined($packagetab{$package."&$name&default"})) {
                   9859: 	    return $packagetab{$package."&$name&default"};
                   9860: 	}
                   9861:     }
                   9862:     # look for a global default setting
                   9863:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9864: 	return $packagetab{"default&$name&default"};
                   9865:     }
1.395     albertel 9866:     return undef;
                   9867: }
                   9868: 
1.334     albertel 9869: sub add_prefix_and_part {
                   9870:     my ($prefix,$part)=@_;
                   9871:     my $keyroot;
                   9872:     if (defined($prefix) && $prefix !~ /^__/) {
                   9873: 	# prefix that has a part already
                   9874: 	$keyroot=$prefix;
                   9875:     } elsif (defined($prefix)) {
                   9876: 	# prefix that is missing a part
                   9877: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9878:     } else {
                   9879: 	# no prefix at all
                   9880: 	if (defined($part)) { $keyroot='_'.$part; }
                   9881:     }
                   9882:     return $keyroot;
                   9883: }
                   9884: 
1.71      www      9885: # ---------------------------------------------------------------- Get metadata
                   9886: 
1.599     albertel 9887: my %metaentry;
1.1070    www      9888: my %importedpartids;
1.71      www      9889: sub metadata {
1.176     www      9890:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9891:     $uri=&declutter($uri);
1.288     albertel 9892:     # if it is a non metadata possible uri return quickly
1.529     albertel 9893:     if (($uri eq '') || 
                   9894: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9895: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9896:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9897: 	return undef;
                   9898:     }
1.1140    www      9899:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9900: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9901: 	return undef;
1.288     albertel 9902:     }
1.73      www      9903:     my $filename=$uri;
                   9904:     $uri=~s/\.meta$//;
1.172     www      9905: #
                   9906: # Is the metadata already cached?
1.177     www      9907: # Look at timestamp of caching
1.172     www      9908: # Everything is cached by the main uri, libraries are never directly cached
                   9909: #
1.428     albertel 9910:     if (!defined($liburi)) {
1.599     albertel 9911: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9912: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9913:     }
                   9914:     {
1.1069    www      9915: # Imported parts would go here
1.1070    www      9916:         my %importedids=();
                   9917:         my @origfileimportpartids=();
1.1069    www      9918:         my $importedparts=0;
1.172     www      9919: #
                   9920: # Is this a recursive call for a library?
                   9921: #
1.599     albertel 9922: #	if (! exists($metacache{$uri})) {
                   9923: #	    $metacache{$uri}={};
                   9924: #	}
1.924     albertel 9925: 	my $cachetime = 60*60;
1.171     www      9926:         if ($liburi) {
                   9927: 	    $liburi=&declutter($liburi);
                   9928:             $filename=$liburi;
1.401     bowersj2 9929:         } else {
1.599     albertel 9930: 	    &devalidate_cache_new('meta',$uri);
                   9931: 	    undef(%metaentry);
1.401     bowersj2 9932: 	}
1.140     www      9933:         my %metathesekeys=();
1.73      www      9934:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9935: 	my $metastring;
1.1140    www      9936: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9937: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9938: 	    $metastring = 
1.929     albertel 9939: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9940: 					  ('grade_target' => 'meta'));
                   9941: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9942: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9943:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9944: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9945: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9946: 	    $metastring=&getfile($file);
1.489     albertel 9947: 	}
1.208     albertel 9948:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9949:         my $token;
1.140     www      9950:         undef %metathesekeys;
1.71      www      9951:         while ($token=$parser->get_token) {
1.339     albertel 9952: 	    if ($token->[0] eq 'S') {
                   9953: 		if (defined($token->[2]->{'package'})) {
1.172     www      9954: #
                   9955: # This is a package - get package info
                   9956: #
1.339     albertel 9957: 		    my $package=$token->[2]->{'package'};
                   9958: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9959: 		    if (defined($token->[2]->{'id'})) { 
                   9960: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9961: 		    }
1.599     albertel 9962: 		    if ($metaentry{':packages'}) {
                   9963: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9964: 		    } else {
1.599     albertel 9965: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9966: 		    }
1.736     albertel 9967: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9968: 			my $part=$keyroot;
                   9969: 			$part=~s/^\_//;
1.736     albertel 9970: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9971: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9972: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9973: 			    # ignore package.tab specified default values
                   9974:                             # here &package_tab_default() will fetch those
                   9975: 			    if ($subp eq 'default') { next; }
1.736     albertel 9976: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9977: 			    my $unikey;
                   9978: 			    if ($pack =~ /_0$/) {
                   9979: 				$unikey='parameter_0_'.$name;
                   9980: 				$part=0;
                   9981: 			    } else {
                   9982: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9983: 			    }
1.339     albertel 9984: 			    if ($subp eq 'display') {
                   9985: 				$value.=' [Part: '.$part.']';
                   9986: 			    }
1.599     albertel 9987: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9988: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9989: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9990: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9991: 			    }
1.599     albertel 9992: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9993: 				$metaentry{':'.$unikey}=
                   9994: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9995: 			    }
1.339     albertel 9996: 			}
                   9997: 		    }
                   9998: 		} else {
1.172     www      9999: #
                   10000: # This is not a package - some other kind of start tag
1.339     albertel 10001: #
                   10002: 		    my $entry=$token->[1];
1.1068    www      10003: 		    my $unikey='';
1.175     www      10004: 
1.339     albertel 10005: 		    if ($entry eq 'import') {
1.175     www      10006: #
                   10007: # Importing a library here
1.339     albertel 10008: #
1.1067    www      10009:                         my $location=$parser->get_text('/import');
                   10010:                         my $dir=$filename;
                   10011:                         $dir=~s|[^/]*$||;
                   10012:                         $location=&filelocation($dir,$location);
1.1069    www      10013:                        
1.1068    www      10014:                         my $importmode=$token->[2]->{'importmode'};
                   10015:                         if ($importmode eq 'problem') {
1.1069    www      10016: # Import as problem/response
1.1068    www      10017:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10018:                         } elsif ($importmode eq 'part') {
                   10019: # Import as part(s)
1.1069    www      10020:                            $importedparts=1;
                   10021: # We need to get the original file and the imported file to get the part order correct
                   10022: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10023: # Load and inspect original file
1.1070    www      10024:                            if ($#origfileimportpartids<0) {
                   10025:                               undef(%importedpartids);
                   10026:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10027:                               my $origfile=&getfile($origfilelocation);
                   10028:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10029:                            }
                   10030: 
1.1069    www      10031: # Load and inspect imported file
                   10032:                            my $impfile=&getfile($location);
                   10033:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10034:                            if ($#impfilepartids>=0) {
                   10035: # This problem had parts
1.1070    www      10036:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10037:                            } else {
                   10038: # Importing by turning a single problem into a problem part
                   10039: # It gets the import-tags ID as part-ID
                   10040:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10041:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10042:                            }
1.1068    www      10043:                         } else {
                   10044: # Normal import
                   10045:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10046:                            if (defined($token->[2]->{'id'})) {
                   10047:                               $unikey.='_'.$token->[2]->{'id'};
                   10048:                            }
1.1067    www      10049:                         }
                   10050: 
1.339     albertel 10051: 			if ($depthcount<20) {
1.736     albertel 10052: 			    my $metadata = 
                   10053: 				&metadata($uri,'keys', $location,$unikey,
                   10054: 					  $depthcount+1);
                   10055: 			    foreach my $meta (split(',',$metadata)) {
                   10056: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10057: 				$metathesekeys{$meta}=1;
1.339     albertel 10058: 			    }
1.1068    www      10059: 			
                   10060:                         }
1.1067    www      10061: 		    } else {
                   10062: #
                   10063: # Not importing, some other kind of non-package, non-library start tag
                   10064: # 
                   10065:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10066:                         if (defined($token->[2]->{'id'})) {
                   10067:                             $unikey.='_'.$token->[2]->{'id'};
                   10068:                         }
1.339     albertel 10069: 			if (defined($token->[2]->{'name'})) { 
                   10070: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10071: 			}
                   10072: 			$metathesekeys{$unikey}=1;
1.736     albertel 10073: 			foreach my $param (@{$token->[3]}) {
                   10074: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10075: 				$token->[2]->{$param};
1.339     albertel 10076: 			}
                   10077: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10078: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10079: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10080: 		 # only ws inside the tag, and not in default, so use default
                   10081: 		 # as value
1.599     albertel 10082: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10083: 			} elsif ( $internaltext =~ /\S/ ) {
                   10084: 		  # something interesting inside the tag
                   10085: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10086: 			} else {
1.908     albertel 10087: 		  # no interesting values, don't set a default
1.339     albertel 10088: 			}
1.172     www      10089: # end of not-a-package not-a-library import
1.339     albertel 10090: 		    }
1.172     www      10091: # end of not-a-package start tag
1.339     albertel 10092: 		}
1.172     www      10093: # the next is the end of "start tag"
1.339     albertel 10094: 	    }
                   10095: 	}
1.483     albertel 10096: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10097: 	$extension = lc($extension);
                   10098: 	if ($extension eq 'htm') { $extension='html'; }
                   10099: 
1.737     albertel 10100: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10101: 	    #no specific packages #how's our extension
                   10102: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10103: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10104: 					 \%metathesekeys);
                   10105: 	}
1.883     albertel 10106: 
                   10107: 	if (!exists($metaentry{':packages'})
                   10108: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10109: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10110: 		#no specific packages well let's get default then
                   10111: 		if ($key!~/^default&/) { next; }
1.488     albertel 10112: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10113: 					     \%metathesekeys);
                   10114: 	    }
                   10115: 	}
1.338     www      10116: # are there custom rights to evaluate
1.599     albertel 10117: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10118: 
1.338     www      10119:     #
                   10120:     # Importing a rights file here
1.339     albertel 10121:     #
                   10122: 	    unless ($depthcount) {
1.599     albertel 10123: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10124: 		my $dir=$filename;
                   10125: 		$dir=~s|[^/]*$||;
                   10126: 		$location=&filelocation($dir,$location);
1.736     albertel 10127: 		my $rights_metadata =
                   10128: 		    &metadata($uri,'keys',$location,'_rights',
                   10129: 			      $depthcount+1);
                   10130: 		foreach my $rights (split(',',$rights_metadata)) {
                   10131: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10132: 		    $metathesekeys{$rights}=1;
1.339     albertel 10133: 		}
                   10134: 	    }
                   10135: 	}
1.737     albertel 10136: 	# uniqifiy package listing
                   10137: 	my %seen;
                   10138: 	my @uniq_packages =
                   10139: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10140: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10141: 
1.1070    www      10142:         if ($importedparts) {
                   10143: # We had imported parts and need to rebuild partorder
                   10144:            $metaentry{':partorder'}='';
                   10145:            $metathesekeys{'partorder'}=1;
                   10146:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10147:                if ($origfileimportpartids[$index] eq 'part') {
                   10148: # original part, part of the problem
                   10149:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10150:                } else {
                   10151: # we have imported parts at this position
                   10152:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10153:                }
                   10154:            }
                   10155:            $metaentry{':partorder'}=~s/^\,//;
                   10156:         }
                   10157: 
1.737     albertel 10158: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10159: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10160: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10161: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10162: # this is the end of "was not already recently cached
1.71      www      10163:     }
1.599     albertel 10164:     return $metaentry{':'.$what};
1.261     albertel 10165: }
                   10166: 
1.488     albertel 10167: sub metadata_create_package_def {
1.483     albertel 10168:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10169:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10170:     if ($subp eq 'default') { next; }
                   10171:     
1.599     albertel 10172:     if (defined($metaentry{':packages'})) {
                   10173: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10174:     } else {
1.599     albertel 10175: 	$metaentry{':packages'}=$package;
1.483     albertel 10176:     }
                   10177:     my $value=$packagetab{$key};
                   10178:     my $unikey;
                   10179:     $unikey='parameter_0_'.$name;
1.599     albertel 10180:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10181:     $$metathesekeys{$unikey}=1;
1.599     albertel 10182:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10183: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10184:     }
1.599     albertel 10185:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10186: 	$metaentry{':'.$unikey}=
                   10187: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10188:     }
                   10189: }
                   10190: 
1.261     albertel 10191: sub metadata_generate_part0 {
                   10192:     my ($metadata,$metacache,$uri) = @_;
                   10193:     my %allnames;
1.737     albertel 10194:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10195: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10196: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10197: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10198: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10199: 	    $allnames{$name}=$part;
                   10200: 	  }
                   10201: 	}
                   10202:     }
                   10203:     foreach my $name (keys(%allnames)) {
                   10204:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10205:       my $key=":parameter_0_$name";
1.261     albertel 10206:       $$metacache{"$key.part"}='0';
                   10207:       $$metacache{"$key.name"}=$name;
1.428     albertel 10208:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10209: 					   $allnames{$name}.'_'.$name.
                   10210: 					   '.type'};
1.428     albertel 10211:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10212: 			     '.display'};
1.644     www      10213:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10214:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10215:       $$metacache{"$key.display"}=$olddis;
                   10216:     }
1.71      www      10217: }
                   10218: 
1.764     albertel 10219: # ------------------------------------------------------ Devalidate title cache
                   10220: 
                   10221: sub devalidate_title_cache {
                   10222:     my ($url)=@_;
                   10223:     if (!$env{'request.course.id'}) { return; }
                   10224:     my $symb=&symbread($url);
                   10225:     if (!$symb) { return; }
                   10226:     my $key=$env{'request.course.id'}."\0".$symb;
                   10227:     &devalidate_cache_new('title',$key);
                   10228: }
                   10229: 
1.1014    droeschl 10230: # ------------------------------------------------- Get the title of a course
                   10231: 
                   10232: sub current_course_title {
                   10233:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10234: }
1.301     www      10235: # ------------------------------------------------- Get the title of a resource
                   10236: 
                   10237: sub gettitle {
                   10238:     my $urlsymb=shift;
                   10239:     my $symb=&symbread($urlsymb);
1.534     albertel 10240:     if ($symb) {
1.620     albertel 10241: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10242: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10243: 	if (defined($cached)) { 
                   10244: 	    return $result;
                   10245: 	}
1.534     albertel 10246: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10247: 	my $title='';
1.907     albertel 10248: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10249: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10250: 	} else {
                   10251: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10252: 		    &GDBM_READER(),0640)) {
                   10253: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10254: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10255: 		untie(%bighash);
                   10256: 	    }
1.534     albertel 10257: 	}
                   10258: 	$title=~s/\&colon\;/\:/gs;
                   10259: 	if ($title) {
1.1159    www      10260: # Remember both $symb and $title for dynamic metadata
                   10261:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10262:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10263: # Cache this title and then return it
1.599     albertel 10264: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10265: 	}
                   10266: 	$urlsymb=$url;
                   10267:     }
                   10268:     my $title=&metadata($urlsymb,'title');
                   10269:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10270:     return $title;
1.301     www      10271: }
1.613     albertel 10272: 
1.1172.2.13  raeburn  10273: sub getdocspath {
                   10274:     my ($symb) = @_;
                   10275:     my $path;
                   10276:     if ($symb) {
                   10277:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10278:         if ($resurl=~/\.(sequence|page)$/) {
                   10279:             $mapurl=$resurl;
                   10280:         } elsif ($resurl eq 'adm/navmaps') {
                   10281:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10282:         }
                   10283:         my $mapresobj;
                   10284:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10285:         if (ref($navmap)) {
                   10286:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10287:         }
                   10288:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10289:         my $type=$2;
                   10290:         if (ref($mapresobj)) {
                   10291:             my $pcslist = $mapresobj->map_hierarchy();
                   10292:             if ($pcslist ne '') {
                   10293:                 foreach my $pc (split(/,/,$pcslist)) {
                   10294:                     next if ($pc <= 1);
                   10295:                     my $res = $navmap->getByMapPc($pc);
                   10296:                     if (ref($res)) {
                   10297:                         my $thisurl = $res->src();
                   10298:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10299:                         my $thistitle = $res->title();
                   10300:                         $path .= '&'.
                   10301:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10302:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10303:                                  ':'.$res->randompick().
                   10304:                                  ':'.$res->randomout().
                   10305:                                  ':'.$res->encrypted().
                   10306:                                  ':'.$res->randomorder().
                   10307:                                  ':'.$res->is_page();
                   10308:                     }
                   10309:                 }
                   10310:             }
                   10311:             $path =~ s/^\&//;
                   10312:             my $maptitle = $mapresobj->title();
                   10313:             if ($mapurl eq 'default') {
                   10314:                 $maptitle = 'Main Course Documents';
                   10315:             }
                   10316:             $path .= ($path ne '')? '&' : ''.
                   10317:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10318:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10319:                     ':'.$mapresobj->randompick().
                   10320:                     ':'.$mapresobj->randomout().
                   10321:                     ':'.$mapresobj->encrypted().
                   10322:                     ':'.$mapresobj->randomorder().
                   10323:                     ':'.$mapresobj->is_page();
                   10324:         } else {
                   10325:             my $maptitle = &gettitle($mapurl);
                   10326:             my $ispage;
                   10327:             if ($mapurl =~ /\.page$/) {
                   10328:                 $ispage = 1;
                   10329:             }
                   10330:             if ($mapurl eq 'default') {
                   10331:                 $maptitle = 'Main Course Documents';
                   10332:             }
                   10333:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10334:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10335:         }
                   10336:         unless ($mapurl eq 'default') {
                   10337:             $path = 'default&'.
                   10338:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10339:                     ':::::&'.$path;
                   10340:         }
                   10341:     }
                   10342:     return $path;
                   10343: }
                   10344: 
1.614     albertel 10345: sub get_slot {
                   10346:     my ($which,$cnum,$cdom)=@_;
                   10347:     if (!$cnum || !$cdom) {
1.790     albertel 10348: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10349: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10350: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10351:     }
1.703     albertel 10352:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10353:     my %slotinfo;
                   10354:     if (exists($remembered{$key})) {
                   10355: 	$slotinfo{$which} = $remembered{$key};
                   10356:     } else {
                   10357: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10358: 	&Apache::lonhomework::showhash(%slotinfo);
                   10359: 	my ($tmp)=keys(%slotinfo);
                   10360: 	if ($tmp=~/^error:/) { return (); }
                   10361: 	$remembered{$key} = $slotinfo{$which};
                   10362:     }
1.616     albertel 10363:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10364: 	return %{$slotinfo{$which}};
                   10365:     }
                   10366:     return $slotinfo{$which};
1.614     albertel 10367: }
1.1150    raeburn  10368: 
                   10369: sub get_reservable_slots {
                   10370:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10371:     my $now = time;
                   10372:     my $reservable_info;
                   10373:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10374:     if (exists($remembered{$key})) {
                   10375:         $reservable_info = $remembered{$key};
                   10376:     } else {
                   10377:         my %resv;
                   10378:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10379:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10380:         $reservable_info = \%resv;
                   10381:         $remembered{$key} = $reservable_info;
                   10382:     }
                   10383:     return $reservable_info;
                   10384: }
                   10385: 
                   10386: sub get_course_slots {
                   10387:     my ($cnum,$cdom) = @_;
                   10388:     my $hashid=$cnum.':'.$cdom;
                   10389:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10390:     if (defined($cached)) {
                   10391:         if (ref($result) eq 'HASH') {
                   10392:             return %{$result};
                   10393:         }
                   10394:     } else {
                   10395:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10396:         my ($tmp) = keys(%slots);
                   10397:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10398:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10399:             return %slots;
                   10400:         }
                   10401:     }
                   10402:     return;
                   10403: }
                   10404: 
                   10405: sub devalidate_slots_cache {
                   10406:     my ($cnum,$cdom)=@_;
                   10407:     my $hashid=$cnum.':'.$cdom;
                   10408:     &devalidate_cache_new('allslots',$hashid);
                   10409: }
                   10410: 
1.1172.2.8  raeburn  10411: sub get_coursechange {
                   10412:     my ($cdom,$cnum) = @_;
                   10413:     if ($cdom eq '' || $cnum eq '') {
                   10414:         return unless ($env{'request.course.id'});
                   10415:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10416:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10417:     }
                   10418:     my $hashid=$cdom.'_'.$cnum;
                   10419:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10420:     if ((defined($cached)) && ($change ne '')) {
                   10421:         return $change;
                   10422:     } else {
                   10423:         my %crshash;
                   10424:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10425:         if ($crshash{'internal.contentchange'} eq '') {
                   10426:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10427:             if ($change eq '') {
                   10428:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10429:                 $change = $crshash{'internal.created'};
                   10430:             }
                   10431:         } else {
                   10432:             $change = $crshash{'internal.contentchange'};
                   10433:         }
                   10434:         my $cachetime = 600;
                   10435:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10436:     }
                   10437:     return $change;
                   10438: }
                   10439: 
                   10440: sub devalidate_coursechange_cache {
                   10441:     my ($cnum,$cdom)=@_;
                   10442:     my $hashid=$cnum.':'.$cdom;
                   10443:     &devalidate_cache_new('crschange',$hashid);
                   10444: }
                   10445: 
1.31      www      10446: # ------------------------------------------------- Update symbolic store links
                   10447: 
                   10448: sub symblist {
                   10449:     my ($mapname,%newhash)=@_;
1.438     www      10450:     $mapname=&deversion(&declutter($mapname));
1.31      www      10451:     my %hash;
1.620     albertel 10452:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10453:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10454:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10455: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10456: 		next if ($url eq 'last_known'
                   10457: 			 && $env{'form.no_update_last_known'});
                   10458: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10459: 						    $newhash{$url}->[1],
                   10460: 						    $newhash{$url}->[0]);
1.191     harris41 10461:             }
1.31      www      10462:             if (untie(%hash)) {
                   10463: 		return 'ok';
                   10464:             }
                   10465:         }
                   10466:     }
                   10467:     return 'error';
1.212     www      10468: }
                   10469: 
                   10470: # --------------------------------------------------------------- Verify a symb
                   10471: 
                   10472: sub symbverify {
1.1172.2.11  raeburn  10473:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10474:     my $thisfn=$thisurl;
1.439     www      10475:     $thisfn=&declutter($thisfn);
1.215     www      10476: # direct jump to resource in page or to a sequence - will construct own symbs
                   10477:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10478: # check URL part
1.409     www      10479:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10480: 
1.431     www      10481:     unless ($url eq $thisfn) { return 0; }
1.213     www      10482: 
1.216     www      10483:     $symb=&symbclean($symb);
1.510     www      10484:     $thisurl=&deversion($thisurl);
1.439     www      10485:     $thisfn=&deversion($thisfn);
1.213     www      10486: 
                   10487:     my %bighash;
                   10488:     my $okay=0;
1.431     www      10489: 
1.620     albertel 10490:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10491:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10492:         my $noclutter;
1.1032    raeburn  10493:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10494:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10495:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10496:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10497:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10498:                 $noclutter = 1;
                   10499:             }
                   10500:         }
                   10501:         my $ids;
                   10502:         if ($noclutter) {
                   10503:             $ids=$bighash{'ids_'.$thisurl};
                   10504:         } else {
                   10505:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10506:         }
1.1102    raeburn  10507:         unless ($ids) {
1.1172.2.13  raeburn  10508:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10509:             $ids=$bighash{$idkey};
1.216     www      10510:         }
                   10511:         if ($ids) {
                   10512: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10513:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10514:                 $symb =~ s/\?.+$//;
                   10515:             }
1.800     albertel 10516: 	    foreach my $id (split(/\,/,$ids)) {
                   10517: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10518:                if (
                   10519:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10520:    eq $symb) {
1.1172.2.11  raeburn  10521:                    if (ref($encstate)) {
                   10522:                        $$encstate = $bighash{'encrypted_'.$id};
                   10523:                    }
1.1172.2.13  raeburn  10524:                    if (($env{'request.role.adv'}) ||
                   10525:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10526:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10527:                        $okay=1;
                   10528:                        last;
                   10529:                    }
                   10530:                }
                   10531:            }
1.216     www      10532:         }
1.213     www      10533: 	untie(%bighash);
                   10534:     }
                   10535:     return $okay;
1.31      www      10536: }
                   10537: 
1.210     www      10538: # --------------------------------------------------------------- Clean-up symb
                   10539: 
                   10540: sub symbclean {
                   10541:     my $symb=shift;
1.568     albertel 10542:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10543: # remove version from map
                   10544:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10545: 
1.210     www      10546: # remove version from URL
                   10547:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10548: 
1.507     www      10549: # remove wrapper
                   10550: 
1.510     www      10551:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10552:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10553:     return $symb;
1.409     www      10554: }
                   10555: 
                   10556: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10557: 
                   10558: sub encode_symb {
                   10559:     my ($map,$resid,$url)=@_;
                   10560:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10561: }
1.409     www      10562: 
                   10563: sub decode_symb {
1.568     albertel 10564:     my $symb=shift;
                   10565:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10566:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10567:     return (&fixversion($map),$resid,&fixversion($url));
                   10568: }
                   10569: 
                   10570: sub fixversion {
                   10571:     my $fn=shift;
1.609     banghart 10572:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10573:     my %bighash;
                   10574:     my $uri=&clutter($fn);
1.620     albertel 10575:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10576: # is this cached?
1.599     albertel 10577:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10578:     if (defined($cached)) { return $result; }
                   10579: # unfortunately not cached, or expired
1.620     albertel 10580:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10581: 	    &GDBM_READER(),0640)) {
                   10582:  	if ($bighash{'version_'.$uri}) {
                   10583:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10584:  	    unless (($version eq 'mostrecent') || 
                   10585: 		    ($version==&getversion($uri))) {
1.440     www      10586:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10587:  	    }
                   10588:  	}
                   10589:  	untie %bighash;
1.413     www      10590:     }
1.599     albertel 10591:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10592: }
                   10593: 
                   10594: sub deversion {
                   10595:     my $url=shift;
                   10596:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10597:     return $url;
1.210     www      10598: }
                   10599: 
1.31      www      10600: # ------------------------------------------------------ Return symb list entry
                   10601: 
                   10602: sub symbread {
1.249     www      10603:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10604:     my $cache_str;
                   10605:     if ($thisfn ne '') {
                   10606:         $cache_str='request.symbread.cached.'.$thisfn;
                   10607:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10608:             return $env{$cache_str};
                   10609:         }
1.1172.2.13  raeburn  10610:    } else {
1.242     www      10611: # no filename provided? try from environment
1.620     albertel 10612:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10613:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10614:         }
                   10615:         $thisfn=$env{'request.filename'};
1.44      www      10616:     }
1.569     albertel 10617:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10618: # is that filename actually a symb? Verify, clean, and return
                   10619:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10620: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10621: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10622: 	}
1.242     www      10623:     }
1.44      www      10624:     $thisfn=declutter($thisfn);
1.31      www      10625:     my %hash;
1.37      www      10626:     my %bighash;
                   10627:     my $syval='';
1.620     albertel 10628:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10629:         my $targetfn = $thisfn;
1.609     banghart 10630:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10631:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10632:         }
1.687     albertel 10633: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10634: 	    $targetfn=$1;
                   10635: 	}
1.620     albertel 10636:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10637:                       &GDBM_READER(),0640)) {
1.481     raeburn  10638: 	    $syval=$hash{$targetfn};
1.37      www      10639:             untie(%hash);
                   10640:         }
                   10641: # ---------------------------------------------------------- There was an entry
                   10642:         if ($syval) {
1.601     albertel 10643: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10644: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10645: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10646: 		    #return $env{$cache_str}='';
1.601     albertel 10647: 		#}    
                   10648: 		#$syval.=$1;
                   10649: 	    #}
1.37      www      10650:         } else {
                   10651: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10652:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10653:                             &GDBM_READER(),0640)) {
1.37      www      10654: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10655:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10656:               unless ($ids) { 
                   10657:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10658:               }
                   10659:               unless ($ids) {
                   10660: # alias?
                   10661: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10662:               }
1.37      www      10663:               if ($ids) {
                   10664: # ------------------------------------------------------------------- Has ID(s)
                   10665:                  my @possibilities=split(/\,/,$ids);
1.39      www      10666:                  if ($#possibilities==0) {
                   10667: # ----------------------------------------------- There is only one possibility
1.37      www      10668: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10669: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10670: 						    $resid,$thisfn);
1.249     www      10671:                  } elsif (!$donotrecurse) {
1.39      www      10672: # ------------------------------------------ There is more than one possibility
                   10673:                      my $realpossible=0;
1.800     albertel 10674:                      foreach my $id (@possibilities) {
                   10675: 			 my $file=$bighash{'src_'.$id};
1.39      www      10676:                          if (&allowed('bre',$file)) {
1.800     albertel 10677:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10678:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10679: 				$realpossible++;
1.626     albertel 10680:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10681: 						    $resid,$thisfn);
1.39      www      10682:                             }
                   10683: 			 }
1.191     harris41 10684:                      }
1.39      www      10685: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10686:                  } else {
                   10687:                      $syval='';
1.37      www      10688:                  }
                   10689: 	      }
                   10690:               untie(%bighash)
1.481     raeburn  10691:            }
1.31      www      10692:         }
1.62      www      10693:         if ($syval) {
1.620     albertel 10694: 	    return $env{$cache_str}=$syval;
1.62      www      10695:         }
1.31      www      10696:     }
1.949     raeburn  10697:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10698:     return $env{$cache_str}='';
1.31      www      10699: }
                   10700: 
                   10701: # ---------------------------------------------------------- Return random seed
                   10702: 
1.32      www      10703: sub numval {
                   10704:     my $txt=shift;
                   10705:     $txt=~tr/A-J/0-9/;
                   10706:     $txt=~tr/a-j/0-9/;
                   10707:     $txt=~tr/K-T/0-9/;
                   10708:     $txt=~tr/k-t/0-9/;
                   10709:     $txt=~tr/U-Z/0-5/;
                   10710:     $txt=~tr/u-z/0-5/;
                   10711:     $txt=~s/\D//g;
1.564     albertel 10712:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10713:     return int($txt);
1.368     albertel 10714: }
                   10715: 
1.484     albertel 10716: sub numval2 {
                   10717:     my $txt=shift;
                   10718:     $txt=~tr/A-J/0-9/;
                   10719:     $txt=~tr/a-j/0-9/;
                   10720:     $txt=~tr/K-T/0-9/;
                   10721:     $txt=~tr/k-t/0-9/;
                   10722:     $txt=~tr/U-Z/0-5/;
                   10723:     $txt=~tr/u-z/0-5/;
                   10724:     $txt=~s/\D//g;
                   10725:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10726:     my $total;
                   10727:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10728:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10729:     return int($total);
                   10730: }
                   10731: 
1.575     albertel 10732: sub numval3 {
                   10733:     use integer;
                   10734:     my $txt=shift;
                   10735:     $txt=~tr/A-J/0-9/;
                   10736:     $txt=~tr/a-j/0-9/;
                   10737:     $txt=~tr/K-T/0-9/;
                   10738:     $txt=~tr/k-t/0-9/;
                   10739:     $txt=~tr/U-Z/0-5/;
                   10740:     $txt=~tr/u-z/0-5/;
                   10741:     $txt=~s/\D//g;
                   10742:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10743:     my $total;
                   10744:     foreach my $val (@txts) { $total+=$val; }
                   10745:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10746:     return $total;
                   10747: }
                   10748: 
1.675     albertel 10749: sub digest {
                   10750:     my ($data)=@_;
                   10751:     my $digest=&Digest::MD5::md5($data);
                   10752:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10753:     my ($e,$f);
                   10754:     {
                   10755:         use integer;
                   10756:         $e=($a+$b);
                   10757:         $f=($c+$d);
                   10758:         if ($_64bit) {
                   10759:             $e=(($e<<32)>>32);
                   10760:             $f=(($f<<32)>>32);
                   10761:         }
                   10762:     }
                   10763:     if (wantarray) {
                   10764: 	return ($e,$f);
                   10765:     } else {
                   10766: 	my $g;
                   10767: 	{
                   10768: 	    use integer;
                   10769: 	    $g=($e+$f);
                   10770: 	    if ($_64bit) {
                   10771: 		$g=(($g<<32)>>32);
                   10772: 	    }
                   10773: 	}
                   10774: 	return $g;
                   10775:     }
                   10776: }
                   10777: 
1.368     albertel 10778: sub latest_rnd_algorithm_id {
1.675     albertel 10779:     return '64bit5';
1.366     albertel 10780: }
1.32      www      10781: 
1.503     albertel 10782: sub get_rand_alg {
                   10783:     my ($courseid)=@_;
1.790     albertel 10784:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10785:     if ($courseid) {
1.620     albertel 10786: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10787:     }
                   10788:     return &latest_rnd_algorithm_id();
                   10789: }
                   10790: 
1.562     albertel 10791: sub validCODE {
                   10792:     my ($CODE)=@_;
                   10793:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10794:     return 0;
                   10795: }
                   10796: 
1.491     albertel 10797: sub getCODE {
1.620     albertel 10798:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10799:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10800: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10801: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10802: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10803:     }
                   10804:     return undef;
                   10805: }
1.1133    foxr     10806: #
                   10807: #  Determines the random seed for a specific context:
                   10808: #
                   10809: # parameters:
                   10810: #   symb      - in course context the symb for the seed.
                   10811: #   course_id - The course id of the form domain_coursenum.
                   10812: #   domain    - Domain for the user.
                   10813: #   course    - Course for the user.
                   10814: #   cenv      - environment of the course.
                   10815: #
                   10816: # NOTE:
                   10817: #   All parameters are picked out of the environment if missing
                   10818: #   or not defined.
                   10819: #   If a symb cannot be determined the current time is used instead.
                   10820: #
                   10821: #  For a given well defined symb, courside, domain, username,
                   10822: #  and course environment, the seed is reproducible.
                   10823: #
1.31      www      10824: sub rndseed {
1.1133    foxr     10825:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10826:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10827:     if (!defined($symb)) {
1.366     albertel 10828: 	unless ($symb=$wsymb) { return time; }
                   10829:     }
1.1146    foxr     10830:     if (!defined $courseid) { 
                   10831: 	$courseid=$wcourseid; 
                   10832:     }
                   10833:     if (!defined $domain) { $domain=$wdomain; }
                   10834:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10835: 
                   10836:     my $which;
                   10837:     if (defined($cenv->{'rndseed'})) {
                   10838: 	$which = $cenv->{'rndseed'};
                   10839:     } else {
                   10840: 	$which =&get_rand_alg($courseid);
                   10841:     }
1.491     albertel 10842:     if (defined(&getCODE())) {
1.675     albertel 10843: 	if ($which eq '64bit5') {
                   10844: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10845: 	} elsif ($which eq '64bit4') {
1.575     albertel 10846: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10847: 	} else {
                   10848: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10849: 	}
1.675     albertel 10850:     } elsif ($which eq '64bit5') {
                   10851: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10852:     } elsif ($which eq '64bit4') {
                   10853: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10854:     } elsif ($which eq '64bit3') {
                   10855: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10856:     } elsif ($which eq '64bit2') {
                   10857: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10858:     } elsif ($which eq '64bit') {
                   10859: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10860:     }
                   10861:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10862: }
                   10863: 
                   10864: sub rndseed_32bit {
                   10865:     my ($symb,$courseid,$domain,$username)=@_;
                   10866:     {
                   10867: 	use integer;
                   10868: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10869: 	my $symbseed=numval($symb) << 22;
                   10870: 	my $namechck=unpack("%32C*",$username) << 17;
                   10871: 	my $nameseed=numval($username) << 12;
                   10872: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10873: 	my $courseseed=unpack("%32C*",$courseid);
                   10874: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10875: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10876: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10877: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10878: 	return $num;
                   10879:     }
                   10880: }
                   10881: 
                   10882: sub rndseed_64bit {
                   10883:     my ($symb,$courseid,$domain,$username)=@_;
                   10884:     {
                   10885: 	use integer;
                   10886: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10887: 	my $symbseed=numval($symb) << 10;
                   10888: 	my $namechck=unpack("%32S*",$username);
                   10889: 	
                   10890: 	my $nameseed=numval($username) << 21;
                   10891: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10892: 	my $courseseed=unpack("%32S*",$courseid);
                   10893: 	
                   10894: 	my $num1=$symbchck+$symbseed+$namechck;
                   10895: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10896: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10897: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10898: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10899: 	return "$num1,$num2";
1.155     albertel 10900:     }
1.366     albertel 10901: }
                   10902: 
1.443     albertel 10903: sub rndseed_64bit2 {
                   10904:     my ($symb,$courseid,$domain,$username)=@_;
                   10905:     {
                   10906: 	use integer;
                   10907: 	# strings need to be an even # of cahracters long, it it is odd the
                   10908:         # last characters gets thrown away
                   10909: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10910: 	my $symbseed=numval($symb) << 10;
                   10911: 	my $namechck=unpack("%32S*",$username.' ');
                   10912: 	
                   10913: 	my $nameseed=numval($username) << 21;
1.501     albertel 10914: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10915: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10916: 	
                   10917: 	my $num1=$symbchck+$symbseed+$namechck;
                   10918: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10919: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10920: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10921: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10922: 	return "$num1,$num2";
                   10923:     }
                   10924: }
                   10925: 
                   10926: sub rndseed_64bit3 {
                   10927:     my ($symb,$courseid,$domain,$username)=@_;
                   10928:     {
                   10929: 	use integer;
                   10930: 	# strings need to be an even # of cahracters long, it it is odd the
                   10931:         # last characters gets thrown away
                   10932: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10933: 	my $symbseed=numval2($symb) << 10;
                   10934: 	my $namechck=unpack("%32S*",$username.' ');
                   10935: 	
                   10936: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10937: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10938: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10939: 	
                   10940: 	my $num1=$symbchck+$symbseed+$namechck;
                   10941: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10942: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10943: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10944: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10945: 	
1.503     albertel 10946: 	return "$num1:$num2";
1.443     albertel 10947:     }
                   10948: }
                   10949: 
1.575     albertel 10950: sub rndseed_64bit4 {
                   10951:     my ($symb,$courseid,$domain,$username)=@_;
                   10952:     {
                   10953: 	use integer;
                   10954: 	# strings need to be an even # of cahracters long, it it is odd the
                   10955:         # last characters gets thrown away
                   10956: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10957: 	my $symbseed=numval3($symb) << 10;
                   10958: 	my $namechck=unpack("%32S*",$username.' ');
                   10959: 	
                   10960: 	my $nameseed=numval3($username) << 21;
                   10961: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10962: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10963: 	
                   10964: 	my $num1=$symbchck+$symbseed+$namechck;
                   10965: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10967: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10968: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10969: 	
1.575     albertel 10970: 	return "$num1:$num2";
                   10971:     }
                   10972: }
                   10973: 
1.675     albertel 10974: sub rndseed_64bit5 {
                   10975:     my ($symb,$courseid,$domain,$username)=@_;
                   10976:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10977:     return "$num1:$num2";
                   10978: }
                   10979: 
1.366     albertel 10980: sub rndseed_CODE_64bit {
                   10981:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10982:     {
1.366     albertel 10983: 	use integer;
1.443     albertel 10984: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10985: 	my $symbseed=numval2($symb);
1.491     albertel 10986: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10987: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10988: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10989: 	my $num1=$symbseed+$CODEchck;
                   10990: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10991: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10992: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10993: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10994: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10995: 	return "$num1:$num2";
1.366     albertel 10996:     }
                   10997: }
                   10998: 
1.575     albertel 10999: sub rndseed_CODE_64bit4 {
                   11000:     my ($symb,$courseid,$domain,$username)=@_;
                   11001:     {
                   11002: 	use integer;
                   11003: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11004: 	my $symbseed=numval3($symb);
                   11005: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11006: 	my $CODEseed=numval3(&getCODE());
                   11007: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11008: 	my $num1=$symbseed+$CODEchck;
                   11009: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11010: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11011: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11012: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11013: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11014: 	return "$num1:$num2";
                   11015:     }
                   11016: }
                   11017: 
1.675     albertel 11018: sub rndseed_CODE_64bit5 {
                   11019:     my ($symb,$courseid,$domain,$username)=@_;
                   11020:     my $code = &getCODE();
                   11021:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11022:     return "$num1:$num2";
                   11023: }
                   11024: 
1.366     albertel 11025: sub setup_random_from_rndseed {
                   11026:     my ($rndseed)=@_;
1.503     albertel 11027:     if ($rndseed =~/([,:])/) {
                   11028: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11029: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11030:     } else {
                   11031: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11032:     }
1.36      albertel 11033: }
                   11034: 
1.474     albertel 11035: sub latest_receipt_algorithm_id {
1.835     albertel 11036:     return 'receipt3';
1.474     albertel 11037: }
                   11038: 
1.480     www      11039: sub recunique {
                   11040:     my $fucourseid=shift;
                   11041:     my $unique;
1.835     albertel 11042:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11043: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11044: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11045:     } else {
                   11046: 	$unique=$perlvar{'lonReceipt'};
                   11047:     }
                   11048:     return unpack("%32C*",$unique);
                   11049: }
                   11050: 
                   11051: sub recprefix {
                   11052:     my $fucourseid=shift;
                   11053:     my $prefix;
1.835     albertel 11054:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11055: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11056: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11057:     } else {
                   11058: 	$prefix=$perlvar{'lonHostID'};
                   11059:     }
                   11060:     return unpack("%32C*",$prefix);
                   11061: }
                   11062: 
1.76      www      11063: sub ireceipt {
1.474     albertel 11064:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11065: 
                   11066:     my $return =&recprefix($fucourseid).'-';
                   11067: 
                   11068:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11069: 	$env{'request.state'} eq 'construct') {
                   11070: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11071: 	return $return;
                   11072:     }
                   11073: 
1.76      www      11074:     my $cuname=unpack("%32C*",$funame);
                   11075:     my $cudom=unpack("%32C*",$fudom);
                   11076:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11077:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11078:     my $cunique=&recunique($fucourseid);
1.474     albertel 11079:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11080:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11081: 
1.790     albertel 11082: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11083: 			       
                   11084: 	$return.= ($cunique%$cuname+
                   11085: 		   $cunique%$cudom+
                   11086: 		   $cusymb%$cuname+
                   11087: 		   $cusymb%$cudom+
                   11088: 		   $cucourseid%$cuname+
                   11089: 		   $cucourseid%$cudom+
                   11090: 		   $cpart%$cuname+
                   11091: 		   $cpart%$cudom);
                   11092:     } else {
                   11093: 	$return.= ($cunique%$cuname+
                   11094: 		   $cunique%$cudom+
                   11095: 		   $cusymb%$cuname+
                   11096: 		   $cusymb%$cudom+
                   11097: 		   $cucourseid%$cuname+
                   11098: 		   $cucourseid%$cudom);
                   11099:     }
                   11100:     return $return;
1.76      www      11101: }
                   11102: 
                   11103: sub receipt {
1.474     albertel 11104:     my ($part)=@_;
1.790     albertel 11105:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11106:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11107: }
1.260     ng       11108: 
1.790     albertel 11109: sub whichuser {
                   11110:     my ($passedsymb)=@_;
                   11111:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11112:     if (defined($env{'form.grade_symb'})) {
                   11113: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11114: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11115: 	if (!$allowed &&
                   11116: 	    exists($env{'request.course.sec'}) &&
                   11117: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11118: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11119: 			      '/'.$env{'request.course.sec'});
                   11120: 	}
                   11121: 	if ($allowed) {
                   11122: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11123: 	    $courseid=$tmp_courseid;
                   11124: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11125: 	    ($name)=&get_env_multiple('form.grade_username');
                   11126: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11127: 	}
                   11128:     }
                   11129:     if (!$passedsymb) {
                   11130: 	$symb=&symbread();
                   11131:     } else {
                   11132: 	$symb=$passedsymb;
                   11133:     }
                   11134:     $courseid=$env{'request.course.id'};
                   11135:     $domain=$env{'user.domain'};
                   11136:     $name=$env{'user.name'};
                   11137:     if ($name eq 'public' && $domain eq 'public') {
                   11138: 	if (!defined($env{'form.username'})) {
                   11139: 	    $env{'form.username'}.=time.rand(10000000);
                   11140: 	}
                   11141: 	$name.=$env{'form.username'};
                   11142:     }
                   11143:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11144: 
                   11145: }
                   11146: 
1.36      albertel 11147: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11148: # returns either the contents of the file or 
                   11149: # -1 if the file doesn't exist
1.481     raeburn  11150: #
                   11151: # if the target is a file that was uploaded via DOCS, 
                   11152: # a check will be made to see if a current copy exists on the local server,
                   11153: # if it does this will be served, otherwise a copy will be retrieved from
                   11154: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11155: # the local server.   
1.472     albertel 11156: 
1.36      albertel 11157: sub getfile {
1.538     albertel 11158:     my ($file) = @_;
1.609     banghart 11159:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11160:     &repcopy($file);
                   11161:     return &readfile($file);
                   11162: }
                   11163: 
                   11164: sub repcopy_userfile {
                   11165:     my ($file)=@_;
1.1142    raeburn  11166:     my $londocroot = $perlvar{'lonDocRoot'};
                   11167:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11168:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11169:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11170: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11171:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11172:     if (-e "$file") {
1.828     www      11173: # we already have a local copy, check it out
1.538     albertel 11174: 	my @fileinfo = stat($file);
1.828     www      11175: 	my $rtncode;
                   11176: 	my $info;
1.538     albertel 11177: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11178: 	if ($lwpresp ne 'ok') {
1.828     www      11179: # there is no such file anymore, even though we had a local copy
1.482     albertel 11180: 	    if ($rtncode eq '404') {
1.538     albertel 11181: 		unlink($file);
1.482     albertel 11182: 	    }
                   11183: 	    return -1;
                   11184: 	}
                   11185: 	if ($info < $fileinfo[9]) {
1.828     www      11186: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11187: 	    return 'ok';
1.828     www      11188: 	} else {
                   11189: # the file is outdated, get rid of it
                   11190: 	    unlink($file);
1.482     albertel 11191: 	}
1.828     www      11192:     }
                   11193: # one way or the other, at this point, we don't have the file
                   11194: # construct the correct path for the file
                   11195:     my @parts = ($cdom,$cnum); 
                   11196:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11197: 	push @parts, split(/\//,$1);
                   11198:     }
                   11199:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11200:     foreach my $part (@parts) {
                   11201: 	$path .= '/'.$part;
                   11202: 	if (!-e $path) {
                   11203: 	    mkdir($path,0770);
1.482     albertel 11204: 	}
                   11205:     }
1.828     www      11206: # now the path exists for sure
                   11207: # get a user agent
                   11208:     my $ua=new LWP::UserAgent;
                   11209:     my $transferfile=$file.'.in.transfer';
                   11210: # FIXME: this should flock
                   11211:     if (-e $transferfile) { return 'ok'; }
                   11212:     my $request;
                   11213:     $uri=~s/^\///;
1.980     raeburn  11214:     my $homeserver = &homeserver($cnum,$cdom);
                   11215:     my $protocol = $protocol{$homeserver};
                   11216:     $protocol = 'http' if ($protocol ne 'https');
                   11217:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11218:     my $response=$ua->request($request,$transferfile);
                   11219: # did it work?
                   11220:     if ($response->is_error()) {
                   11221: 	unlink($transferfile);
                   11222: 	&logthis("Userfile repcopy failed for $uri");
                   11223: 	return -1;
                   11224:     }
                   11225: # worked, rename the transfer file
                   11226:     rename($transferfile,$file);
1.607     raeburn  11227:     return 'ok';
1.481     raeburn  11228: }
                   11229: 
1.517     albertel 11230: sub tokenwrapper {
                   11231:     my $uri=shift;
1.980     raeburn  11232:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11233:     $uri=~s|^/||;
1.620     albertel 11234:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11235:     my $token=$1;
1.552     albertel 11236:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11237:     if ($udom && $uname && $file) {
                   11238: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11239:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11240:         my $homeserver = &homeserver($uname,$udom);
                   11241:         my $protocol = $protocol{$homeserver};
                   11242:         $protocol = 'http' if ($protocol ne 'https');
                   11243:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11244:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11245:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11246:     } else {
                   11247:         return '/adm/notfound.html';
                   11248:     }
                   11249: }
                   11250: 
1.828     www      11251: # call with reqtype HEAD: get last modification time
                   11252: # call with reqtype GET: get the file contents
                   11253: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11254: #
1.481     raeburn  11255: sub getuploaded {
                   11256:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11257:     $uri=~s/^\///;
1.980     raeburn  11258:     my $homeserver = &homeserver($cnum,$cdom);
                   11259:     my $protocol = $protocol{$homeserver};
                   11260:     $protocol = 'http' if ($protocol ne 'https');
                   11261:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11262:     my $ua=new LWP::UserAgent;
                   11263:     my $request=new HTTP::Request($reqtype,$uri);
                   11264:     my $response=$ua->request($request);
                   11265:     $$rtncode = $response->code;
1.482     albertel 11266:     if (! $response->is_success()) {
                   11267: 	return 'failed';
                   11268:     }      
                   11269:     if ($reqtype eq 'HEAD') {
1.486     www      11270: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11271:     } elsif ($reqtype eq 'GET') {
                   11272: 	$$info = $response->content;
1.472     albertel 11273:     }
1.482     albertel 11274:     return 'ok';
1.36      albertel 11275: }
                   11276: 
1.481     raeburn  11277: sub readfile {
                   11278:     my $file = shift;
                   11279:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11280:     my $fh;
                   11281:     open($fh,"<$file");
                   11282:     my $a='';
1.800     albertel 11283:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11284:     return $a;
                   11285: }
                   11286: 
1.36      albertel 11287: sub filelocation {
1.590     banghart 11288:     my ($dir,$file) = @_;
                   11289:     my $location;
                   11290:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11291: 
                   11292:     if ($file =~ m-^/adm/-) {
                   11293: 	$file=~s-^/adm/wrapper/-/-;
                   11294: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11295:     }
1.882     albertel 11296: 
1.1139    www      11297:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11298:         $location = $file;
1.609     banghart 11299:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11300:         my ($udom,$uname,$filename)=
1.811     albertel 11301:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11302:         my $home=&homeserver($uname,$udom);
                   11303:         my $is_me=0;
                   11304:         my @ids=&current_machine_ids();
                   11305:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11306:         if ($is_me) {
1.1117    foxr     11307:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11308:         } else {
                   11309:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11310:   	      $udom.'/'.$uname.'/'.$filename;
                   11311:         }
1.882     albertel 11312:     } elsif ($file =~ m-^/adm/-) {
                   11313: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11314:     } else {
                   11315:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11316:         $file=~s:^/(res|priv)/:/:;
                   11317:         my $space=$1;
1.590     banghart 11318:         if ( !( $file =~ m:^/:) ) {
                   11319:             $location = $dir. '/'.$file;
                   11320:         } else {
1.1142    raeburn  11321:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11322:         }
1.59      albertel 11323:     }
1.590     banghart 11324:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11325:     while ($location=~m{/\.\./}) {
                   11326: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11327: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11328: 	} else {
                   11329: 	    $location=~ s{/\.\./}{/}g;
                   11330: 	}
                   11331:     } #remove dir/..
1.590     banghart 11332:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11333:     return $location;
1.46      www      11334: }
1.36      albertel 11335: 
1.46      www      11336: sub hreflocation {
                   11337:     my ($dir,$file)=@_;
1.980     raeburn  11338:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11339: 	$file=filelocation($dir,$file);
1.700     albertel 11340:     } elsif ($file=~m-^/adm/-) {
                   11341: 	$file=~s-^/adm/wrapper/-/-;
                   11342: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11343:     }
                   11344:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11345: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11346:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11347: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11348: 	        {/uploaded/$1/$2/}x;
1.46      www      11349:     }
1.913     albertel 11350:     if ($file=~ m{^/userfiles/}) {
                   11351: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11352:     }
1.462     albertel 11353:     return $file;
1.465     albertel 11354: }
                   11355: 
1.1139    www      11356: 
                   11357: 
                   11358: 
                   11359: 
1.465     albertel 11360: sub current_machine_domains {
1.853     albertel 11361:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11362: }
                   11363: 
                   11364: sub machine_domains {
                   11365:     my ($hostname) = @_;
1.465     albertel 11366:     my @domains;
1.838     albertel 11367:     my %hostname = &all_hostnames();
1.465     albertel 11368:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11369: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11370: 	if ($hostname eq $name) {
1.844     albertel 11371: 	    push(@domains,&host_domain($id));
1.465     albertel 11372: 	}
                   11373:     }
                   11374:     return @domains;
                   11375: }
                   11376: 
                   11377: sub current_machine_ids {
1.853     albertel 11378:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11379: }
                   11380: 
                   11381: sub machine_ids {
                   11382:     my ($hostname) = @_;
                   11383:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11384:     my @ids;
1.888     albertel 11385:     my %name_to_host = &all_names();
1.889     albertel 11386:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11387: 	return @{ $name_to_host{$hostname} };
                   11388:     }
                   11389:     return;
1.31      www      11390: }
                   11391: 
1.824     raeburn  11392: sub additional_machine_domains {
                   11393:     my @domains;
                   11394:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11395:     while( my $line = <$fh>) {
                   11396:         $line =~ s/\s//g;
                   11397:         push(@domains,$line);
                   11398:     }
                   11399:     return @domains;
                   11400: }
                   11401: 
                   11402: sub default_login_domain {
                   11403:     my $domain = $perlvar{'lonDefDomain'};
                   11404:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11405:     foreach my $posdom (&current_machine_domains(),
                   11406:                         &additional_machine_domains()) {
                   11407:         if (lc($posdom) eq lc($testdomain)) {
                   11408:             $domain=$posdom;
                   11409:             last;
                   11410:         }
                   11411:     }
                   11412:     return $domain;
                   11413: }
                   11414: 
1.31      www      11415: # ------------------------------------------------------------- Declutters URLs
                   11416: 
                   11417: sub declutter {
                   11418:     my $thisfn=shift;
1.569     albertel 11419:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11420:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11421:     $thisfn=~s/^\///;
1.697     albertel 11422:     $thisfn=~s|^adm/wrapper/||;
                   11423:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11424:     $thisfn=~s/^res\///;
1.1172    bisitz   11425:     $thisfn=~s/^priv\///;
1.1032    raeburn  11426:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11427:         $thisfn=~s/\?.+$//;
                   11428:     }
1.268     www      11429:     return $thisfn;
                   11430: }
                   11431: 
                   11432: # ------------------------------------------------------------- Clutter up URLs
                   11433: 
                   11434: sub clutter {
                   11435:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11436:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11437: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11438:        $thisfn='/res'.$thisfn; 
                   11439:     }
1.1031    raeburn  11440:     if ($thisfn !~m|^/adm|) {
                   11441: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11442: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11443: 	} else {
                   11444: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11445: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11446: 	    if ($embstyle eq 'ssi'
                   11447: 		|| ($embstyle eq 'hdn')
                   11448: 		|| ($embstyle eq 'rat')
                   11449: 		|| ($embstyle eq 'prv')
                   11450: 		|| ($embstyle eq 'ign')) {
                   11451: 		#do nothing with these
                   11452: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11453: 		|| ($embstyle eq 'emb')
                   11454: 		|| ($embstyle eq 'wrp')) {
                   11455: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11456: 	    } elsif ($embstyle eq 'unk'
                   11457: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11458: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11459: 	    } else {
1.718     www      11460: #		&logthis("Got a blank emb style");
1.695     albertel 11461: 	    }
1.694     albertel 11462: 	}
                   11463:     }
1.31      www      11464:     return $thisfn;
1.12      www      11465: }
                   11466: 
1.787     albertel 11467: sub clutter_with_no_wrapper {
                   11468:     my $uri = &clutter(shift);
                   11469:     if ($uri =~ m-^/adm/-) {
                   11470: 	$uri =~ s-^/adm/wrapper/-/-;
                   11471: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11472:     }
                   11473:     return $uri;
                   11474: }
                   11475: 
1.557     albertel 11476: sub freeze_escape {
                   11477:     my ($value)=@_;
                   11478:     if (ref($value)) {
                   11479: 	$value=&nfreeze($value);
                   11480: 	return '__FROZEN__'.&escape($value);
                   11481:     }
                   11482:     return &escape($value);
                   11483: }
                   11484: 
1.11      www      11485: 
1.557     albertel 11486: sub thaw_unescape {
                   11487:     my ($value)=@_;
                   11488:     if ($value =~ /^__FROZEN__/) {
                   11489: 	substr($value,0,10,undef);
                   11490: 	$value=&unescape($value);
                   11491: 	return &thaw($value);
                   11492:     }
                   11493:     return &unescape($value);
                   11494: }
                   11495: 
1.436     albertel 11496: sub correct_line_ends {
                   11497:     my ($result)=@_;
                   11498:     $$result =~s/\r\n/\n/mg;
                   11499:     $$result =~s/\r/\n/mg;
1.415     albertel 11500: }
1.1       albertel 11501: # ================================================================ Main Program
                   11502: 
1.184     www      11503: sub goodbye {
1.204     albertel 11504:    &logthis("Starting Shut down");
1.443     albertel 11505: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11506:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11507: #converted
1.599     albertel 11508: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11509:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11510: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11511: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11512: #1.1 only
1.870     albertel 11513: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11514: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11515: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11516: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11517:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11518:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11519:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11520:    &flushcourselogs();
                   11521:    &logthis("Shutting down");
                   11522: }
                   11523: 
1.852     albertel 11524: sub get_dns {
1.1172.2.17  raeburn  11525:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11526:     if (!$ignore_cache) {
                   11527: 	my ($content,$cached)=
                   11528: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11529: 	if ($cached) {
1.1172.2.17  raeburn  11530: 	    &$func($content,$hashref);
1.869     albertel 11531: 	    return;
                   11532: 	}
                   11533:     }
                   11534: 
                   11535:     my %alldns;
1.852     albertel 11536:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11537:     foreach my $dns (<$config>) {
                   11538: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11539:         my $line = $1;
                   11540:         my ($host,$protocol) = split(/:/,$line);
                   11541:         if ($protocol ne 'https') {
                   11542:             $protocol = 'http';
                   11543:         }
                   11544: 	$alldns{$host} = $protocol;
1.869     albertel 11545:     }
                   11546:     while (%alldns) {
                   11547: 	my ($dns) = keys(%alldns);
1.852     albertel 11548: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11549:         $ua->timeout(30);
1.979     raeburn  11550: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11551: 	my $response=$ua->request($request);
1.979     raeburn  11552:         delete($alldns{$dns});
1.852     albertel 11553: 	next if ($response->is_error());
                   11554: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11555:         unless ($nocache) {
                   11556: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
                   11557:         }
                   11558: 	&$func(\@content,$hashref);
1.869     albertel 11559: 	return;
1.852     albertel 11560:     }
                   11561:     close($config);
1.871     albertel 11562:     my $which = (split('/',$url))[3];
                   11563:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11564:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11565:     my @content = <$config>;
1.1172.2.17  raeburn  11566:     &$func(\@content,$hashref);
                   11567:     return;
                   11568: }
                   11569: 
                   11570: # ------------------------------------------------------Get DNS checksums file
                   11571: sub parse_dns_checksums_tab {
                   11572:     my ($lines,$hashref) = @_;
                   11573:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11574:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11575:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11576:     my (%chksum,%revnum);
                   11577:     if (ref($lines) eq 'ARRAY') {
                   11578:         chomp(@{$lines});
                   11579:         my $versions = shift(@{$lines});
                   11580:         my %supported;
                   11581:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11582:             my $releaseslist = $1;
                   11583:             if ($releaseslist =~ /,/) {
                   11584:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11585:             } elsif ($releaseslist) {
                   11586:                 $supported{$releaseslist} = 1;
                   11587:             }
                   11588:         }
                   11589:         if ($supported{$release}) {
                   11590:             my $matchthis = 0;
                   11591:             foreach my $line (@{$lines}) {
                   11592:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11593:                     if ($matchthis) {
                   11594:                         last;
                   11595:                     } elsif ($1 eq $release) {
                   11596:                         $matchthis = 1;
                   11597:                     }
                   11598:                 } elsif ($matchthis) {
                   11599:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11600:                     $chksum{$file} = $shasum;
                   11601:                     $revnum{$file} = $version;
                   11602:                 }
                   11603:             }
                   11604:             if (ref($hashref) eq 'HASH') {
                   11605:                 %{$hashref} = (
                   11606:                                 sums     => \%chksum,
                   11607:                                 versions => \%revnum,
                   11608:                               );
                   11609:             }
                   11610:         }
                   11611:     }
1.869     albertel 11612:     return;
1.852     albertel 11613: }
1.1172.2.17  raeburn  11614: 
                   11615: sub fetch_dns_checksums {
                   11616:     my %checksums;
                   11617:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11618:              \%checksums);
                   11619:     return \%checksums;
                   11620: }
                   11621: 
1.327     albertel 11622: # ------------------------------------------------------------ Read domain file
                   11623: {
1.852     albertel 11624:     my $loaded;
1.846     albertel 11625:     my %domain;
                   11626: 
1.852     albertel 11627:     sub parse_domain_tab {
                   11628: 	my ($lines) = @_;
                   11629: 	foreach my $line (@$lines) {
                   11630: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11631: 
1.846     albertel 11632: 	    chomp($line);
1.852     albertel 11633: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11634: 	    my %this_domain;
                   11635: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11636: 			       'lang_def', 'city', 'longi', 'lati',
                   11637: 			       'primary') {
                   11638: 		$this_domain{$field} = shift(@elements);
                   11639: 	    }
                   11640: 	    $domain{$name} = \%this_domain;
1.852     albertel 11641: 	}
                   11642:     }
1.864     albertel 11643: 
                   11644:     sub reset_domain_info {
                   11645: 	undef($loaded);
                   11646: 	undef(%domain);
                   11647:     }
                   11648: 
1.852     albertel 11649:     sub load_domain_tab {
1.869     albertel 11650: 	my ($ignore_cache) = @_;
                   11651: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11652: 	my $fh;
                   11653: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11654: 	    my @lines = <$fh>;
                   11655: 	    &parse_domain_tab(\@lines);
1.448     albertel 11656: 	}
1.852     albertel 11657: 	close($fh);
                   11658: 	$loaded = 1;
1.327     albertel 11659:     }
1.846     albertel 11660: 
                   11661:     sub domain {
1.852     albertel 11662: 	&load_domain_tab() if (!$loaded);
                   11663: 
1.846     albertel 11664: 	my ($name,$what) = @_;
                   11665: 	return if ( !exists($domain{$name}) );
                   11666: 
                   11667: 	if (!$what) {
                   11668: 	    return $domain{$name}{'description'};
                   11669: 	}
                   11670: 	return $domain{$name}{$what};
                   11671:     }
1.974     raeburn  11672: 
                   11673:     sub domain_info {
                   11674:         &load_domain_tab() if (!$loaded);
                   11675:         return %domain;
                   11676:     }
                   11677: 
1.327     albertel 11678: }
                   11679: 
                   11680: 
1.1       albertel 11681: # ------------------------------------------------------------- Read hosts file
                   11682: {
1.838     albertel 11683:     my %hostname;
1.844     albertel 11684:     my %hostdom;
1.845     albertel 11685:     my %libserv;
1.852     albertel 11686:     my $loaded;
1.888     albertel 11687:     my %name_to_host;
1.1074    raeburn  11688:     my %internetdom;
1.1107    raeburn  11689:     my %LC_dns_serv;
1.852     albertel 11690: 
                   11691:     sub parse_hosts_tab {
                   11692: 	my ($file) = @_;
                   11693: 	foreach my $configline (@$file) {
                   11694: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11695:             chomp($configline);
                   11696: 	    if ($configline =~ /^\^/) {
                   11697:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11698:                     $LC_dns_serv{$1} = 1;
                   11699:                 }
                   11700:                 next;
                   11701:             }
1.1074    raeburn  11702: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11703: 	    $name=~s/\s//g;
                   11704: 	    if ($id && $domain && $role && $name) {
                   11705: 		$hostname{$id}=$name;
1.888     albertel 11706: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11707: 		$hostdom{$id}=$domain;
                   11708: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11709:                 if (defined($protocol)) {
                   11710:                     if ($protocol eq 'https') {
                   11711:                         $protocol{$id} = $protocol;
                   11712:                     } else {
                   11713:                         $protocol{$id} = 'http'; 
                   11714:                     }
1.968     raeburn  11715:                 } else {
1.969     raeburn  11716:                     $protocol{$id} = 'http';
1.968     raeburn  11717:                 }
1.1074    raeburn  11718:                 if (defined($intdom)) {
                   11719:                     $internetdom{$id} = $intdom;
                   11720:                 }
1.852     albertel 11721: 	    }
                   11722: 	}
                   11723:     }
1.864     albertel 11724:     
                   11725:     sub reset_hosts_info {
1.897     albertel 11726: 	&purge_remembered();
1.864     albertel 11727: 	&reset_domain_info();
                   11728: 	&reset_hosts_ip_info();
1.892     albertel 11729: 	undef(%name_to_host);
1.864     albertel 11730: 	undef(%hostname);
                   11731: 	undef(%hostdom);
                   11732: 	undef(%libserv);
                   11733: 	undef($loaded);
                   11734:     }
1.1       albertel 11735: 
1.852     albertel 11736:     sub load_hosts_tab {
1.869     albertel 11737: 	my ($ignore_cache) = @_;
                   11738: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11739: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11740: 	my @config = <$config>;
                   11741: 	&parse_hosts_tab(\@config);
                   11742: 	close($config);
                   11743: 	$loaded=1;
1.1       albertel 11744:     }
1.852     albertel 11745: 
1.838     albertel 11746:     sub hostname {
1.852     albertel 11747: 	&load_hosts_tab() if (!$loaded);
                   11748: 
1.838     albertel 11749: 	my ($lonid) = @_;
                   11750: 	return $hostname{$lonid};
                   11751:     }
1.845     albertel 11752: 
1.838     albertel 11753:     sub all_hostnames {
1.852     albertel 11754: 	&load_hosts_tab() if (!$loaded);
                   11755: 
1.838     albertel 11756: 	return %hostname;
                   11757:     }
1.845     albertel 11758: 
1.888     albertel 11759:     sub all_names {
                   11760: 	&load_hosts_tab() if (!$loaded);
                   11761: 
                   11762: 	return %name_to_host;
                   11763:     }
                   11764: 
1.974     raeburn  11765:     sub all_host_domain {
                   11766:         &load_hosts_tab() if (!$loaded);
                   11767:         return %hostdom;
                   11768:     }
                   11769: 
1.845     albertel 11770:     sub is_library {
1.852     albertel 11771: 	&load_hosts_tab() if (!$loaded);
                   11772: 
1.845     albertel 11773: 	return exists($libserv{$_[0]});
                   11774:     }
                   11775: 
                   11776:     sub all_library {
1.852     albertel 11777: 	&load_hosts_tab() if (!$loaded);
                   11778: 
1.845     albertel 11779: 	return %libserv;
                   11780:     }
                   11781: 
1.1062    droeschl 11782:     sub unique_library {
                   11783: 	#2x reverse removes all hostnames that appear more than once
                   11784:         my %unique = reverse &all_library();
                   11785:         return reverse %unique;
                   11786:     }
                   11787: 
1.841     albertel 11788:     sub get_servers {
1.852     albertel 11789: 	&load_hosts_tab() if (!$loaded);
                   11790: 
1.841     albertel 11791: 	my ($domain,$type) = @_;
                   11792: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11793: 	                                          : %hostname;
                   11794: 	my %result;
1.842     albertel 11795: 	if (ref($domain) eq 'ARRAY') {
                   11796: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11797: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11798: 		    $result{$host} = $hostname;
                   11799: 		}
                   11800: 	    }
                   11801: 	} else {
                   11802: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11803: 		if ($hostdom{$host} eq $domain) {
                   11804: 		    $result{$host} = $hostname;
                   11805: 		}
1.841     albertel 11806: 	    }
                   11807: 	}
                   11808: 	return %result;
                   11809:     }
1.845     albertel 11810: 
1.1062    droeschl 11811:     sub get_unique_servers {
                   11812:         my %unique = reverse &get_servers(@_);
                   11813: 	return reverse %unique;
                   11814:     }
                   11815: 
1.844     albertel 11816:     sub host_domain {
1.852     albertel 11817: 	&load_hosts_tab() if (!$loaded);
                   11818: 
1.844     albertel 11819: 	my ($lonid) = @_;
                   11820: 	return $hostdom{$lonid};
                   11821:     }
                   11822: 
1.841     albertel 11823:     sub all_domains {
1.852     albertel 11824: 	&load_hosts_tab() if (!$loaded);
                   11825: 
1.841     albertel 11826: 	my %seen;
                   11827: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11828: 	return @uniq;
                   11829:     }
1.1074    raeburn  11830: 
                   11831:     sub internet_dom {
                   11832:         &load_hosts_tab() if (!$loaded);
                   11833: 
                   11834:         my ($lonid) = @_;
                   11835:         return $internetdom{$lonid};
                   11836:     }
1.1107    raeburn  11837: 
                   11838:     sub is_LC_dns {
                   11839:         &load_hosts_tab() if (!$loaded);
                   11840: 
                   11841:         my ($hostname) = @_;
                   11842:         return exists($LC_dns_serv{$hostname});
                   11843:     }
                   11844: 
1.1       albertel 11845: }
                   11846: 
1.847     albertel 11847: { 
                   11848:     my %iphost;
1.856     albertel 11849:     my %name_to_ip;
                   11850:     my %lonid_to_ip;
1.869     albertel 11851: 
1.847     albertel 11852:     sub get_hosts_from_ip {
                   11853: 	my ($ip) = @_;
                   11854: 	my %iphosts = &get_iphost();
                   11855: 	if (ref($iphosts{$ip})) {
                   11856: 	    return @{$iphosts{$ip}};
                   11857: 	}
                   11858: 	return;
1.839     albertel 11859:     }
1.864     albertel 11860:     
                   11861:     sub reset_hosts_ip_info {
                   11862: 	undef(%iphost);
                   11863: 	undef(%name_to_ip);
                   11864: 	undef(%lonid_to_ip);
                   11865:     }
1.856     albertel 11866: 
                   11867:     sub get_host_ip {
                   11868: 	my ($lonid) = @_;
                   11869: 	if (exists($lonid_to_ip{$lonid})) {
                   11870: 	    return $lonid_to_ip{$lonid};
                   11871: 	}
                   11872: 	my $name=&hostname($lonid);
                   11873:    	my $ip = gethostbyname($name);
                   11874: 	return if (!$ip || length($ip) ne 4);
                   11875: 	$ip=inet_ntoa($ip);
                   11876: 	$name_to_ip{$name}   = $ip;
                   11877: 	$lonid_to_ip{$lonid} = $ip;
                   11878: 	return $ip;
                   11879:     }
1.847     albertel 11880:     
                   11881:     sub get_iphost {
1.869     albertel 11882: 	my ($ignore_cache) = @_;
1.894     albertel 11883: 
1.869     albertel 11884: 	if (!$ignore_cache) {
                   11885: 	    if (%iphost) {
                   11886: 		return %iphost;
                   11887: 	    }
                   11888: 	    my ($ip_info,$cached)=
                   11889: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11890: 	    if ($cached) {
                   11891: 		%iphost      = %{$ip_info->[0]};
                   11892: 		%name_to_ip  = %{$ip_info->[1]};
                   11893: 		%lonid_to_ip = %{$ip_info->[2]};
                   11894: 		return %iphost;
                   11895: 	    }
                   11896: 	}
1.894     albertel 11897: 
                   11898: 	# get yesterday's info for fallback
                   11899: 	my %old_name_to_ip;
                   11900: 	my ($ip_info,$cached)=
                   11901: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11902: 	if ($cached) {
                   11903: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11904: 	}
                   11905: 
1.888     albertel 11906: 	my %name_to_host = &all_names();
                   11907: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11908: 	    my $ip;
                   11909: 	    if (!exists($name_to_ip{$name})) {
                   11910: 		$ip = gethostbyname($name);
                   11911: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11912: 		    if (defined($old_name_to_ip{$name})) {
                   11913: 			$ip = $old_name_to_ip{$name};
                   11914: 			&logthis("Can't find $name defaulting to old $ip");
                   11915: 		    } else {
                   11916: 			&logthis("Name $name no IP found");
                   11917: 			next;
                   11918: 		    }
                   11919: 		} else {
                   11920: 		    $ip=inet_ntoa($ip);
1.847     albertel 11921: 		}
                   11922: 		$name_to_ip{$name} = $ip;
                   11923: 	    } else {
                   11924: 		$ip = $name_to_ip{$name};
1.653     albertel 11925: 	    }
1.888     albertel 11926: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11927: 		$lonid_to_ip{$id} = $ip;
                   11928: 	    }
                   11929: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11930: 	}
1.869     albertel 11931: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11932: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11933: 				      48*60*60);
1.869     albertel 11934: 
1.847     albertel 11935: 	return %iphost;
1.598     albertel 11936:     }
                   11937: 
1.992     raeburn  11938:     #
                   11939:     #  Given a DNS returns the loncapa host name for that DNS 
                   11940:     # 
                   11941:     sub host_from_dns {
                   11942:         my ($dns) = @_;
                   11943:         my @hosts;
                   11944:         my $ip;
                   11945: 
1.993     raeburn  11946:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11947:             $ip = $name_to_ip{$dns};
                   11948:         }
                   11949:         if (!$ip) {
                   11950:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11951:             if (length($ip) == 4) { 
                   11952: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11953:             }
                   11954:         }
                   11955:         if ($ip) {
                   11956: 	    @hosts = get_hosts_from_ip($ip);
                   11957: 	    return $hosts[0];
                   11958:         }
                   11959:         return undef;
1.986     foxr     11960:     }
1.992     raeburn  11961: 
1.1074    raeburn  11962:     sub get_internet_names {
                   11963:         my ($lonid) = @_;
                   11964:         return if ($lonid eq '');
                   11965:         my ($idnref,$cached)=
                   11966:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11967:         if ($cached) {
                   11968:             return $idnref;
                   11969:         }
                   11970:         my $ip = &get_host_ip($lonid);
                   11971:         my @hosts = &get_hosts_from_ip($ip);
                   11972:         my %iphost = &get_iphost();
                   11973:         my (@idns,%seen);
                   11974:         foreach my $id (@hosts) {
                   11975:             my $dom = &host_domain($id);
                   11976:             my $prim_id = &domain($dom,'primary');
                   11977:             my $prim_ip = &get_host_ip($prim_id);
                   11978:             next if ($seen{$prim_ip});
                   11979:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11980:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11981:                     my $intdom = &internet_dom($id);
                   11982:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11983:                         push(@idns,$intdom);
                   11984:                     }
                   11985:                 }
                   11986:             }
                   11987:             $seen{$prim_ip} = 1;
                   11988:         }
                   11989:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11990:     }
                   11991: 
1.986     foxr     11992: }
                   11993: 
1.1079    raeburn  11994: sub all_loncaparevs {
                   11995:     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);
                   11996: }
                   11997: 
1.862     albertel 11998: BEGIN {
                   11999: 
                   12000: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12001:     unless ($readit) {
                   12002: {
                   12003:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12004:     %perlvar = (%perlvar,%{$configvars});
                   12005: }
                   12006: 
                   12007: 
1.1       albertel 12008: # ------------------------------------------------------ Read spare server file
                   12009: {
1.448     albertel 12010:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12011: 
                   12012:     while (my $configline=<$config>) {
                   12013:        chomp($configline);
1.284     matthew  12014:        if ($configline) {
1.784     albertel 12015: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12016: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12017: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12018:        }
                   12019:     }
1.448     albertel 12020:     close($config);
1.1       albertel 12021: }
1.11      www      12022: # ------------------------------------------------------------ Read permissions
                   12023: {
1.448     albertel 12024:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12025: 
                   12026:     while (my $configline=<$config>) {
1.448     albertel 12027: 	chomp($configline);
                   12028: 	if ($configline) {
                   12029: 	    my ($role,$perm)=split(/ /,$configline);
                   12030: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12031: 	}
1.11      www      12032:     }
1.448     albertel 12033:     close($config);
1.11      www      12034: }
                   12035: 
                   12036: # -------------------------------------------- Read plain texts for permissions
                   12037: {
1.448     albertel 12038:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12039: 
                   12040:     while (my $configline=<$config>) {
1.448     albertel 12041: 	chomp($configline);
                   12042: 	if ($configline) {
1.742     raeburn  12043: 	    my ($short,@plain)=split(/:/,$configline);
                   12044:             %{$prp{$short}} = ();
                   12045: 	    if (@plain > 0) {
                   12046:                 $prp{$short}{'std'} = $plain[0];
                   12047:                 for (my $i=1; $i<@plain; $i++) {
                   12048:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12049:                 }
                   12050:             }
1.448     albertel 12051: 	}
1.135     www      12052:     }
1.448     albertel 12053:     close($config);
1.135     www      12054: }
                   12055: 
                   12056: # ---------------------------------------------------------- Read package table
                   12057: {
1.448     albertel 12058:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12059: 
                   12060:     while (my $configline=<$config>) {
1.483     albertel 12061: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12062: 	chomp($configline);
                   12063: 	my ($short,$plain)=split(/:/,$configline);
                   12064: 	my ($pack,$name)=split(/\&/,$short);
                   12065: 	if ($plain ne '') {
                   12066: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12067: 	    $packagetab{$short}=$plain; 
                   12068: 	}
1.11      www      12069:     }
1.448     albertel 12070:     close($config);
1.329     matthew  12071: }
                   12072: 
1.1073    raeburn  12073: # ---------------------------------------------------------- Read loncaparev table
                   12074: {
                   12075:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12076:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12077:             while (my $configline=<$config>) {
                   12078:                 chomp($configline);
                   12079:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12080:                 $loncaparevs{$hostid}=$loncaparev;
                   12081:             }
                   12082:             close($config);
                   12083:         }
                   12084:     }
                   12085: }
                   12086: 
1.1074    raeburn  12087: # ---------------------------------------------------------- Read serverhostID table
                   12088: {
                   12089:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12090:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12091:             while (my $configline=<$config>) {
                   12092:                 chomp($configline);
                   12093:                 my ($name,$id)=split(/:/,$configline);
                   12094:                 $serverhomeIDs{$name}=$id;
                   12095:             }
                   12096:             close($config);
                   12097:         }
                   12098:     }
                   12099: }
                   12100: 
1.1079    raeburn  12101: {
                   12102:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12103:     if (-e $file) {
                   12104:         my $parser = HTML::LCParser->new($file);
                   12105:         while (my $token = $parser->get_token()) {
                   12106:             if ($token->[0] eq 'S') {
                   12107:                 my $item = $token->[1];
                   12108:                 my $name = $token->[2]{'name'};
                   12109:                 my $value = $token->[2]{'value'};
                   12110:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12111:                     my $release = $parser->get_text();
                   12112:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12113:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12114:                 }
                   12115:             }
                   12116:         }
                   12117:     }
1.1073    raeburn  12118: }
                   12119: 
1.1138    raeburn  12120: # ---------------------------------------------------------- Read managers table
                   12121: {
                   12122:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12123:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12124:             while (my $configline=<$config>) {
                   12125:                 chomp($configline);
                   12126:                 next if ($configline =~ /^\#/);
                   12127:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12128:                     $managerstab{$configline} = 1;
                   12129:                 }
                   12130:             }
                   12131:             close($config);
                   12132:         }
                   12133:     }
                   12134: }
                   12135: 
1.329     matthew  12136: # ------------- set up temporary directory
                   12137: {
1.1117    foxr     12138:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12139: 
1.11      www      12140: }
                   12141: 
1.794     albertel 12142: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12143: 				'compress_threshold'=> 20_000,
                   12144:  			        });
1.185     www      12145: 
1.281     www      12146: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12147: $dumpcount=0;
1.958     www      12148: $locknum=0;
1.22      www      12149: 
1.163     harris41 12150: &logtouch();
1.672     albertel 12151: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12152: $readit=1;
1.564     albertel 12153:     {
                   12154: 	use integer;
                   12155: 	my $test=(2**32)+1;
1.568     albertel 12156: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12157: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12158:     }
1.1172.2.18! raeburn  12159: 
        !          12160:     {
        !          12161:         eval {
        !          12162:             ($apache) =
        !          12163:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
        !          12164:         };
        !          12165:         if ($@) {
        !          12166:            $apache = 1.3;
        !          12167:         }
        !          12168:     }
        !          12169: 
1.195     www      12170: }
1.1       albertel 12171: }
1.179     www      12172: 
1.1       albertel 12173: 1;
1.191     harris41 12174: __END__
                   12175: 
1.243     albertel 12176: =pod
                   12177: 
1.191     harris41 12178: =head1 NAME
                   12179: 
1.243     albertel 12180: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12181: 
                   12182: =head1 SYNOPSIS
                   12183: 
1.243     albertel 12184: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12185: 
                   12186:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12187: 
1.243     albertel 12188: Common parameters:
                   12189: 
                   12190: =over 4
                   12191: 
                   12192: =item *
                   12193: 
                   12194: $uname : an internal username (if $cname expecting a course Id specifically)
                   12195: 
                   12196: =item *
                   12197: 
                   12198: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12199: 
                   12200: =item *
                   12201: 
                   12202: $symb : a resource instance identifier
                   12203: 
                   12204: =item *
                   12205: 
                   12206: $namespace : the name of a .db file that contains the data needed or
                   12207: being set.
                   12208: 
                   12209: =back
                   12210: 
1.394     bowersj2 12211: =head1 OVERVIEW
1.191     harris41 12212: 
1.394     bowersj2 12213: lonnet provides subroutines which interact with the
                   12214: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12215: about classes, users, and resources.
1.243     albertel 12216: 
                   12217: For many of these objects you can also use this to store data about
                   12218: them or modify them in various ways.
1.191     harris41 12219: 
1.394     bowersj2 12220: =head2 Symbs
1.191     harris41 12221: 
1.394     bowersj2 12222: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12223: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12224: map, the resource number of the resource in the map, and the URL of
                   12225: the resource itself. The latter is somewhat redundant, but might help
                   12226: if maps change.
                   12227: 
                   12228: An example is
                   12229: 
                   12230:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12231: 
                   12232: The respective map entry is
                   12233: 
                   12234:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12235:   title="Problem 2">
                   12236:  </resource>
                   12237: 
                   12238: Symbs are used by the random number generator, as well as to store and
                   12239: restore data specific to a certain instance of for example a problem.
                   12240: 
                   12241: =head2 Storing And Retrieving Data
                   12242: 
                   12243: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12244: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12245: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12246: is is the non-critical message twin of cstore. These functions are for
                   12247: handlers to store a perl hash to a user's permanent data space in an
                   12248: easy manner, and to retrieve it again on another call. It is expected
                   12249: that a handler would use this once at the beginning to retrieve data,
                   12250: and then again once at the end to send only the new data back.
                   12251: 
                   12252: The data is stored in the user's data directory on the user's
                   12253: homeserver under the ID of the course.
                   12254: 
                   12255: The hash that is returned by restore will have all of the previous
                   12256: value for all of the elements of the hash.
                   12257: 
                   12258: Example:
                   12259: 
                   12260:  #creating a hash
                   12261:  my %hash;
                   12262:  $hash{'foo'}='bar';
                   12263: 
                   12264:  #storing it
                   12265:  &Apache::lonnet::cstore(\%hash);
                   12266: 
                   12267:  #changing a value
                   12268:  $hash{'foo'}='notbar';
                   12269: 
                   12270:  #adding a new value
                   12271:  $hash{'bar'}='foo';
                   12272:  &Apache::lonnet::cstore(\%hash);
                   12273: 
                   12274:  #retrieving the hash
                   12275:  my %history=&Apache::lonnet::restore();
                   12276: 
                   12277:  #print the hash
                   12278:  foreach my $key (sort(keys(%history))) {
                   12279:    print("\%history{$key} = $history{$key}");
                   12280:  }
                   12281: 
                   12282: Will print out:
1.191     harris41 12283: 
1.394     bowersj2 12284:  %history{1:foo} = bar
                   12285:  %history{1:keys} = foo:timestamp
                   12286:  %history{1:timestamp} = 990455579
                   12287:  %history{2:bar} = foo
                   12288:  %history{2:foo} = notbar
                   12289:  %history{2:keys} = foo:bar:timestamp
                   12290:  %history{2:timestamp} = 990455580
                   12291:  %history{bar} = foo
                   12292:  %history{foo} = notbar
                   12293:  %history{timestamp} = 990455580
                   12294:  %history{version} = 2
                   12295: 
                   12296: Note that the special hash entries C<keys>, C<version> and
                   12297: C<timestamp> were added to the hash. C<version> will be equal to the
                   12298: total number of versions of the data that have been stored. The
                   12299: C<timestamp> attribute will be the UNIX time the hash was
                   12300: stored. C<keys> is available in every historical section to list which
                   12301: keys were added or changed at a specific historical revision of a
                   12302: hash.
                   12303: 
                   12304: B<Warning>: do not store the hash that restore returns directly. This
                   12305: will cause a mess since it will restore the historical keys as if the
                   12306: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12307: 
1.394     bowersj2 12308: Calling convention:
1.191     harris41 12309: 
1.394     bowersj2 12310:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12311:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12312: 
1.394     bowersj2 12313: For more detailed information, see lonnet specific documentation.
1.191     harris41 12314: 
1.394     bowersj2 12315: =head1 RETURN MESSAGES
1.191     harris41 12316: 
1.394     bowersj2 12317: =over 4
1.191     harris41 12318: 
1.394     bowersj2 12319: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12320: 
1.394     bowersj2 12321: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12322: when the connection is brought back up
1.191     harris41 12323: 
1.394     bowersj2 12324: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12325: for later delivery
1.191     harris41 12326: 
1.967     bisitz   12327: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12328: 
1.394     bowersj2 12329: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12330: that was requested
1.191     harris41 12331: 
1.243     albertel 12332: =back
1.191     harris41 12333: 
1.243     albertel 12334: =head1 PUBLIC SUBROUTINES
1.191     harris41 12335: 
1.243     albertel 12336: =head2 Session Environment Functions
1.191     harris41 12337: 
1.243     albertel 12338: =over 4
1.191     harris41 12339: 
1.394     bowersj2 12340: =item * 
                   12341: X<appenv()>
1.949     raeburn  12342: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12343: the user envirnoment file, and will be restored for each access this
1.620     albertel 12344: user makes during this session, also modifies the %env for the current
1.949     raeburn  12345: process. Optional rolesarrayref - if defined contains a reference to an array
                   12346: of roles which are exempt from the restriction on modifying user.role entries 
                   12347: in the user's environment.db and in %env.    
1.191     harris41 12348: 
                   12349: =item *
1.394     bowersj2 12350: X<delenv()>
1.987     raeburn  12351: B<delenv($delthis,$regexp)>: removes all items from the session
                   12352: environment file that begin with $delthis. If the 
                   12353: optional second arg - $regexp - is true, $delthis is treated as a 
                   12354: regular expression, otherwise \Q$delthis\E is used. 
                   12355: The values are also deleted from the current processes %env.
1.191     harris41 12356: 
1.795     albertel 12357: =item * get_env_multiple($name) 
                   12358: 
                   12359: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12360: values may be defined and end up as an array ref.
                   12361: 
                   12362: returns an array of values
                   12363: 
1.243     albertel 12364: =back
                   12365: 
                   12366: =head2 User Information
1.191     harris41 12367: 
1.243     albertel 12368: =over 4
1.191     harris41 12369: 
                   12370: =item *
1.394     bowersj2 12371: X<queryauthenticate()>
                   12372: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12373: authentication scheme
                   12374: 
                   12375: =item *
1.394     bowersj2 12376: X<authenticate()>
1.1073    raeburn  12377: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12378: authenticate user from domain's lib servers (first use the current
                   12379: one). C<$upass> should be the users password.
1.1073    raeburn  12380: $checkdefauth is optional (value is 1 if a check should be made to
                   12381:    authenticate user using default authentication method, and allow
                   12382:    account creation if username does not have account in the domain).
                   12383: $clientcancheckhost is optional (value is 1 if checking whether the
                   12384:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12385: 
                   12386: =item *
1.394     bowersj2 12387: X<homeserver()>
                   12388: B<homeserver($uname,$udom)>: find the server which has
                   12389: the user's directory and files (there must be only one), this caches
                   12390: the answer, and also caches if there is a borken connection.
1.191     harris41 12391: 
                   12392: =item *
1.394     bowersj2 12393: X<idget()>
                   12394: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12395: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12396: username, and only 1 username per ID in a specific domain) (returns
                   12397: hash: id=>name,id=>name)
1.191     harris41 12398: 
                   12399: =item *
1.394     bowersj2 12400: X<idrget()>
                   12401: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12402: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12403: 
                   12404: =item *
1.394     bowersj2 12405: X<idput()>
                   12406: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12407: 
                   12408: =item *
1.394     bowersj2 12409: X<rolesinit()>
1.1169    droeschl 12410: B<rolesinit($udom,$username)>: get user privileges.
                   12411: returns user role, first access and timer interval hashes
1.243     albertel 12412: 
                   12413: =item *
1.1171    droeschl 12414: X<privileged()>
                   12415: B<privileged($username,$domain)>: returns a true if user has a
                   12416: privileged and active role (i.e. su or dc), false otherwise.
                   12417: 
                   12418: =item *
1.551     albertel 12419: X<getsection()>
                   12420: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12421: course $cname, return section name/number or '' for "not in course"
                   12422: and '-1' for "no section"
                   12423: 
                   12424: =item *
1.394     bowersj2 12425: X<userenvironment()>
                   12426: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12427: passed in @what from the requested user's environment, returns a hash
                   12428: 
1.858     raeburn  12429: =item * 
                   12430: X<userlog_query()>
1.859     albertel 12431: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12432: activity.log file. %filters defines filters applied when parsing the
                   12433: log file. These can be start or end timestamps, or the type of action
                   12434: - log to look for Login or Logout events, check for Checkin or
                   12435: Checkout, role for role selection. The response is in the form
                   12436: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12437: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12438: 
1.243     albertel 12439: =back
                   12440: 
                   12441: =head2 User Roles
                   12442: 
                   12443: =over 4
                   12444: 
                   12445: =item *
                   12446: 
1.810     raeburn  12447: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12448:  F: full access
                   12449:  U,I,K: authentication modes (cxx only)
                   12450:  '': forbidden
                   12451:  1: user needs to choose course
                   12452:  2: browse allowed
1.766     albertel 12453:  A: passphrase authentication needed
1.243     albertel 12454: 
                   12455: =item *
                   12456: 
1.1172.2.13  raeburn  12457: constructaccess($url,$setpriv) : check for access to construction space URL
                   12458: 
                   12459: See if the owner domain and name in the URL match those in the
                   12460: expected environment.  If so, return three element list
                   12461: ($ownername,$ownerdomain,$ownerhome).
                   12462: 
                   12463: Otherwise return the null string.
                   12464: 
                   12465: If second argument 'setpriv' is true, it assigns the privileges,
                   12466: and returns the same three element list, unless the owner has
                   12467: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12468: in which case the null string is returned.
                   12469: 
                   12470: =item *
                   12471: 
1.243     albertel 12472: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12473: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12474: and course level
                   12475: 
                   12476: =item *
                   12477: 
1.988     raeburn  12478: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12479: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12480: $type is Course (default) or Community.
1.988     raeburn  12481: If $forcedefault evaluates to true, text returned will be default 
                   12482: text for $type. Otherwise, if this is a course, the text returned 
                   12483: will be a custom name for the role (if defined in the course's 
                   12484: environment).  If no custom name is defined the default is returned.
                   12485:    
1.832     raeburn  12486: =item *
                   12487: 
1.935     raeburn  12488: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12489: All arguments are optional. Returns a hash of a roles, either for
                   12490: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12491: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12492: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12493: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12494: For each key, value is set to colon-separated start and end times for
                   12495: the role.  If no username and domain are specified, will default to
1.934     raeburn  12496: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12497: of role statuses (active, future or previous), roles 
                   12498: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12499: to restrict the list of roles reported. If no array ref is 
                   12500: provided for types, will default to return only active roles.
1.834     albertel 12501: 
1.1172.2.13  raeburn  12502: =item *
                   12503: 
                   12504: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12505: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12506: 
                   12507: Additional optional arguments are: $type (if role checking is to be restricted
                   12508: to certain user status types -- previous (expired roles), active (currently
                   12509: available roles) or future (roles available in the future), and
                   12510: $hideprivileged -- if true will not report course roles for users who
                   12511: have active Domain Coordinator or Super User roles.
                   12512: 
1.243     albertel 12513: =back
                   12514: 
                   12515: =head2 User Modification
                   12516: 
                   12517: =over 4
                   12518: 
                   12519: =item *
                   12520: 
1.957     raeburn  12521: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12522: user for the level given by URL.  Optional start and end dates (leave empty
                   12523: string or zero for "no date")
1.191     harris41 12524: 
                   12525: =item *
                   12526: 
1.243     albertel 12527: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12528: change a users, password, possible return values are: ok,
                   12529: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12530: refused
1.191     harris41 12531: 
                   12532: =item *
                   12533: 
1.243     albertel 12534: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12535: 
                   12536: =item *
                   12537: 
1.1058    raeburn  12538: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12539:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12540: 
                   12541: will update user information (firstname,middlename,lastname,generation,
                   12542: permanentemail), and if forceid is true, student/employee ID also.
                   12543: A user's institutional affiliation(s) can also be updated.
                   12544: User information fields will not be overwritten with empty entries 
                   12545: unless the field is included in the $candelete array reference.
                   12546: This array is included when a single user is modified via "Manage Users",
                   12547: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12548: 
                   12549: =item *
                   12550: 
1.286     matthew  12551: modifystudent
                   12552: 
1.957     raeburn  12553: modify a student's enrollment and identification information.
1.286     matthew  12554: The course id is resolved based on the current users environment.  
                   12555: This means the envoking user must be a course coordinator or otherwise
                   12556: associated with a course.
                   12557: 
1.297     matthew  12558: This call is essentially a wrapper for lonnet::modifyuser and
                   12559: lonnet::modify_student_enrollment
1.286     matthew  12560: 
                   12561: Inputs: 
                   12562: 
                   12563: =over 4
                   12564: 
1.957     raeburn  12565: =item B<$udom> Student's loncapa domain
1.286     matthew  12566: 
1.957     raeburn  12567: =item B<$uname> Student's loncapa login name
1.286     matthew  12568: 
1.964     bisitz   12569: =item B<$uid> Student/Employee ID
1.286     matthew  12570: 
1.957     raeburn  12571: =item B<$umode> Student's authentication mode
1.286     matthew  12572: 
1.957     raeburn  12573: =item B<$upass> Student's password
1.286     matthew  12574: 
1.957     raeburn  12575: =item B<$first> Student's first name
1.286     matthew  12576: 
1.957     raeburn  12577: =item B<$middle> Student's middle name
1.286     matthew  12578: 
1.957     raeburn  12579: =item B<$last> Student's last name
1.286     matthew  12580: 
1.957     raeburn  12581: =item B<$gene> Student's generation
1.286     matthew  12582: 
1.957     raeburn  12583: =item B<$usec> Student's section in course
1.286     matthew  12584: 
                   12585: =item B<$end> Unix time of the roles expiration
                   12586: 
                   12587: =item B<$start> Unix time of the roles start date
                   12588: 
                   12589: =item B<$forceid> If defined, allow $uid to be changed
                   12590: 
                   12591: =item B<$desiredhome> server to use as home server for student
                   12592: 
1.957     raeburn  12593: =item B<$email> Student's permanent e-mail address
                   12594: 
                   12595: =item B<$type> Type of enrollment (auto or manual)
                   12596: 
1.963     raeburn  12597: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12598: 
                   12599: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12600: 
1.963     raeburn  12601: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12602: 
1.963     raeburn  12603: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12604: 
1.963     raeburn  12605: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12606: 
1.286     matthew  12607: =back
1.297     matthew  12608: 
                   12609: =item *
                   12610: 
                   12611: modify_student_enrollment
                   12612: 
                   12613: Change a students enrollment status in a class.  The environment variable
                   12614: 'role.request.course' must be defined for this function to proceed.
                   12615: 
                   12616: Inputs:
                   12617: 
                   12618: =over 4
                   12619: 
                   12620: =item $udom, students domain
                   12621: 
                   12622: =item $uname, students name
                   12623: 
                   12624: =item $uid, students user id
                   12625: 
                   12626: =item $first, students first name
                   12627: 
                   12628: =item $middle
                   12629: 
                   12630: =item $last
                   12631: 
                   12632: =item $gene
                   12633: 
                   12634: =item $usec
                   12635: 
                   12636: =item $end
                   12637: 
                   12638: =item $start
                   12639: 
1.957     raeburn  12640: =item $type
                   12641: 
                   12642: =item $locktype
                   12643: 
                   12644: =item $cid
                   12645: 
                   12646: =item $selfenroll
                   12647: 
                   12648: =item $context
                   12649: 
1.297     matthew  12650: =back
                   12651: 
1.191     harris41 12652: 
                   12653: =item *
                   12654: 
1.243     albertel 12655: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12656: custom role; give a custom role to a user for the level given by URL.  Specify
                   12657: name and domain of role author, and role name
1.191     harris41 12658: 
                   12659: =item *
                   12660: 
1.243     albertel 12661: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12662: 
                   12663: =item *
                   12664: 
1.243     albertel 12665: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12666: 
                   12667: =back
                   12668: 
                   12669: =head2 Course Infomation
                   12670: 
                   12671: =over 4
1.191     harris41 12672: 
                   12673: =item *
                   12674: 
1.1118    foxr     12675: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12676: specified course id, including all environment settings for the
                   12677: course, the description of the course will be in the hash under the
                   12678: key 'description'
1.191     harris41 12679: 
1.1118    foxr     12680: $options is an optional parameter that if supplied is a hash reference that controls
                   12681: what how this function works.  It has the following key/values:
                   12682: 
                   12683: =over 4
                   12684: 
                   12685: =item freshen_cache
                   12686: 
                   12687: If defined, and the environment cache for the course is valid, it is 
                   12688: returned in the returned hash.
                   12689: 
                   12690: =item one_time
                   12691: 
                   12692: If defined, the last cache time is set to _now_
                   12693: 
                   12694: =item user
                   12695: 
                   12696: If defined, the supplied username is used instead of the current user.
                   12697: 
                   12698: 
                   12699: =back
                   12700: 
1.191     harris41 12701: =item *
                   12702: 
1.624     albertel 12703: resdata($name,$domain,$type,@which) : request for current parameter
                   12704: setting for a specific $type, where $type is either 'course' or 'user',
                   12705: @what should be a list of parameters to ask about. This routine caches
                   12706: answers for 5 minutes.
1.243     albertel 12707: 
1.877     foxr     12708: =item *
                   12709: 
                   12710: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12711: data base, returning a hash that is keyed by the resource name and has
                   12712: values that are the resource value.  I believe that the timestamps and
                   12713: versions are also returned.
                   12714: 
1.243     albertel 12715: =back
                   12716: 
                   12717: =head2 Course Modification
                   12718: 
                   12719: =over 4
1.191     harris41 12720: 
                   12721: =item *
                   12722: 
1.243     albertel 12723: writecoursepref($courseid,%prefs) : write preferences (environment
                   12724: database) for a course
1.191     harris41 12725: 
                   12726: =item *
                   12727: 
1.1011    raeburn  12728: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12729: 
                   12730: =item *
                   12731: 
1.1038    raeburn  12732: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12733: 
1.1167    droeschl 12734: =item *
                   12735: 
                   12736: is_course($courseid), is_course($cdom, $cnum)
                   12737: 
                   12738: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12739: two component version $cdom, $cnum. It checks if the specified course exists.
                   12740: 
                   12741: Returns:
                   12742:     undef if the course doesn't exist, otherwise
                   12743:     in scalar context the combined courseid.
                   12744:     in list context the two components of the course identifier, domain and 
                   12745:     courseid.    
                   12746: 
1.243     albertel 12747: =back
                   12748: 
                   12749: =head2 Resource Subroutines
                   12750: 
                   12751: =over 4
1.191     harris41 12752: 
                   12753: =item *
                   12754: 
1.243     albertel 12755: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12756: 
                   12757: =item *
                   12758: 
1.243     albertel 12759: repcopy($filename) : subscribes to the requested file, and attempts to
                   12760: replicate from the owning library server, Might return
1.607     raeburn  12761: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12762: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12763: resource. Expects the local filesystem pathname
                   12764: (/home/httpd/html/res/....)
                   12765: 
                   12766: =back
                   12767: 
                   12768: =head2 Resource Information
                   12769: 
                   12770: =over 4
1.191     harris41 12771: 
                   12772: =item *
                   12773: 
1.243     albertel 12774: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12775: a vairety of different possible values, $varname should be a request
                   12776: string, and the other parameters can be used to specify who and what
                   12777: one is asking about.
                   12778: 
                   12779: Possible values for $varname are environment.lastname (or other item
                   12780: from the envirnment hash), user.name (or someother aspect about the
                   12781: user), resource.0.maxtries (or some other part and parameter of a
                   12782: resource)
1.204     albertel 12783: 
                   12784: =item *
                   12785: 
1.243     albertel 12786: directcondval($number) : get current value of a condition; reads from a state
                   12787: string
1.204     albertel 12788: 
                   12789: =item *
                   12790: 
1.243     albertel 12791: condval($condidx) : value of condition index based on state
1.204     albertel 12792: 
                   12793: =item *
                   12794: 
1.243     albertel 12795: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12796: resource's metadata, $what should be either a specific key, or either
                   12797: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12798: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12799: 
                   12800: this function automatically caches all requests
1.191     harris41 12801: 
                   12802: =item *
                   12803: 
1.243     albertel 12804: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12805: network of library servers; returns file handle of where SQL and regex results
                   12806: will be stored for query
1.191     harris41 12807: 
                   12808: =item *
                   12809: 
1.243     albertel 12810: symbread($filename) : return symbolic list entry (filename argument optional);
                   12811: returns the data handle
1.191     harris41 12812: 
                   12813: =item *
                   12814: 
1.1172.2.17  raeburn  12815: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12816: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12817: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12818: on failure, user must be in a course, as it assumes the existence of
                   12819: the course initial hash, and uses $env('request.course.id'}.  The third
                   12820: arg is an optional reference to a scalar.  If this arg is passed in the
                   12821: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12822: encrypted; otherwise it will be null.
1.243     albertel 12823: 
1.191     harris41 12824: =item *
                   12825: 
1.243     albertel 12826: symbclean($symb) : removes versions numbers from a symb, returns the
                   12827: cleaned symb
1.191     harris41 12828: 
                   12829: =item *
                   12830: 
1.243     albertel 12831: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12832: course map, user must be in a course for it to work.
1.191     harris41 12833: 
                   12834: =item *
                   12835: 
1.243     albertel 12836: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12837: 
                   12838: =item *
                   12839: 
1.243     albertel 12840: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12841: a random seed, all arguments are optional, if they aren't sent it uses the
                   12842: environment to derive them. Note: if symb isn't sent and it can't get one
                   12843: from &symbread it will use the current time as its return value
1.191     harris41 12844: 
                   12845: =item *
                   12846: 
1.243     albertel 12847: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12848: unfakeable, receipt
1.191     harris41 12849: 
                   12850: =item *
                   12851: 
1.620     albertel 12852: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12853: 
                   12854: =item *
                   12855: 
1.243     albertel 12856: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12857: 
                   12858: =item *
                   12859: 
1.243     albertel 12860: 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 12861: 
                   12862: =item *
                   12863: 
1.243     albertel 12864: 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 12865: 
                   12866: =item *
                   12867: 
1.243     albertel 12868: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12869: 
                   12870: =item *
                   12871: 
1.243     albertel 12872: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12873: forcing spreadsheet to reevaluate the resource scores next time.
                   12874: 
1.1172.2.13  raeburn  12875: =item *
                   12876: 
                   12877: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12878: when viewing in course context.
                   12879: 
                   12880:  input: six args -- filename (decluttered), course number, course domain,
                   12881:                     url, symb (if registered) and group (if this is a
                   12882:                     group item -- e.g., bulletin board, group page etc.).
                   12883: 
                   12884:  output: array of five scalars --
                   12885:          $cfile -- url for file editing if editable on current server
                   12886:          $home -- homeserver of resource (i.e., for author if published,
                   12887:                                           or course if uploaded.).
                   12888:          $switchserver --  1 if server switch will be needed.
                   12889:          $forceedit -- 1 if icon/link should be to go to edit mode
                   12890:          $forceview -- 1 if icon/link should be to go to view mode
                   12891: 
                   12892: =item *
                   12893: 
                   12894: is_course_upload($file,$cnum,$cdom)
                   12895: 
                   12896: Used in course context to determine if current file was uploaded to
                   12897: the course (i.e., would be found in /userfiles/docs on the course's
                   12898: homeserver.
                   12899: 
                   12900:   input: 3 args -- filename (decluttered), course number and course domain.
                   12901:   output: boolean -- 1 if file was uploaded.
                   12902: 
1.243     albertel 12903: =back
                   12904: 
                   12905: =head2 Storing/Retreiving Data
                   12906: 
                   12907: =over 4
1.191     harris41 12908: 
                   12909: =item *
                   12910: 
1.243     albertel 12911: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12912: for this url; hashref needs to be given and should be a \%hashname; the
                   12913: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12914: be derived from the env
1.191     harris41 12915: 
                   12916: =item *
                   12917: 
1.243     albertel 12918: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12919: uses critical subroutine
1.191     harris41 12920: 
                   12921: =item *
                   12922: 
1.243     albertel 12923: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12924: all args are optional
1.191     harris41 12925: 
                   12926: =item *
                   12927: 
1.717     albertel 12928: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12929: dumps the complete (or key matching regexp) namespace into a hash
                   12930: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12931: normally &store()ed into
                   12932: 
                   12933: $range should be either an integer '100' (give me the first 100
                   12934:                                            matching records)
                   12935:               or be  two integers sperated by a - with no spaces
                   12936:                  '30-50' (give me the 30th through the 50th matching
                   12937:                           records)
                   12938: 
                   12939: 
                   12940: =item *
                   12941: 
                   12942: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12943: replaces a &store() version of data with a replacement set of data
                   12944: for a particular resource in a namespace passed in the $storehash hash 
                   12945: reference
                   12946: 
                   12947: =item *
                   12948: 
1.243     albertel 12949: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12950: works very similar to store/cstore, but all data is stored in a
                   12951: temporary location and can be reset using tmpreset, $storehash should
                   12952: be a hash reference, returns nothing on success
1.191     harris41 12953: 
                   12954: =item *
                   12955: 
1.243     albertel 12956: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12957: similar to restore, but all data is stored in a temporary location and
                   12958: can be reset using tmpreset. Returns a hash of values on success,
                   12959: error string otherwise.
1.191     harris41 12960: 
                   12961: =item *
                   12962: 
1.243     albertel 12963: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12964: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12965: 
                   12966: =item *
                   12967: 
1.243     albertel 12968: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12969: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12970: 
                   12971: =item *
                   12972: 
1.243     albertel 12973: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12974: namesp ($udom and $uname are optional)
1.191     harris41 12975: 
                   12976: =item *
                   12977: 
1.702     albertel 12978: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12979: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12980: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12981: 
1.702     albertel 12982: $range should be either an integer '100' (give me the first 100
                   12983:                                            matching records)
                   12984:               or be  two integers sperated by a - with no spaces
                   12985:                  '30-50' (give me the 30th through the 50th matching
                   12986:                           records)
1.449     matthew  12987: =item *
                   12988: 
                   12989: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12990: $store can be a scalar, an array reference, or if the amount to be 
                   12991: incremented is > 1, a hash reference.
                   12992: 
                   12993: ($udom and $uname are optional)
1.191     harris41 12994: 
                   12995: =item *
                   12996: 
1.243     albertel 12997: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12998: ($udom and $uname are optional)
1.191     harris41 12999: 
                   13000: =item *
                   13001: 
1.243     albertel 13002: cput($namespace,$storehash,$udom,$uname) : critical put
                   13003: ($udom and $uname are optional)
1.191     harris41 13004: 
                   13005: =item *
                   13006: 
1.748     albertel 13007: newput($namespace,$storehash,$udom,$uname) :
                   13008: 
                   13009: Attempts to store the items in the $storehash, but only if they don't
                   13010: currently exist, if this succeeds you can be certain that you have 
                   13011: successfully created a new key value pair in the $namespace db.
                   13012: 
                   13013: 
                   13014: Args:
                   13015:  $namespace: name of database to store values to
                   13016:  $storehash: hashref to store to the db
                   13017:  $udom: (optional) domain of user containing the db
                   13018:  $uname: (optional) name of user caontaining the db
                   13019: 
                   13020: Returns:
                   13021:  'ok' -> succeeded in storing all keys of $storehash
                   13022:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13023:                         least <key> already existed in the db (other
                   13024:                         requested keys may also already exist)
1.967     bisitz   13025:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13026:  'con_lost' -> unable to contact request server
                   13027:  'refused' -> action was not allowed by remote machine
                   13028: 
                   13029: 
                   13030: =item *
                   13031: 
1.243     albertel 13032: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13033: reference filled in from namesp (encrypts the return communication)
                   13034: ($udom and $uname are optional)
1.191     harris41 13035: 
                   13036: =item *
                   13037: 
1.243     albertel 13038: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13039: critical subroutine
                   13040: 
1.806     raeburn  13041: =item *
                   13042: 
1.860     raeburn  13043: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13044: array reference filled in from namespace found in domain level on either
                   13045: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13046: 
                   13047: =item *
                   13048: 
1.860     raeburn  13049: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13050: domain level either on specified domain server ($uhome) or primary domain 
                   13051: server ($udom and $uhome are optional)
1.806     raeburn  13052: 
1.943     raeburn  13053: =item * 
                   13054: 
                   13055: get_domain_defaults($target_domain) : returns hash with defaults for
                   13056: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13057: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13058: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13059: Values are retrieved from cache (if current), or from domain's configuration.db
                   13060: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13061: or lonTabs/domain.tab. 
                   13062: 
                   13063: %domdefaults = &get_auth_defaults($target_domain);
                   13064: 
1.243     albertel 13065: =back
                   13066: 
                   13067: =head2 Network Status Functions
                   13068: 
                   13069: =over 4
1.191     harris41 13070: 
                   13071: =item *
                   13072: 
1.1137    raeburn  13073: dirlist() : return directory list based on URI (first arg).
                   13074: 
                   13075: Inputs: 1 required, 5 optional.
                   13076: 
                   13077: =over
                   13078: 
                   13079: =item 
                   13080: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13081: 
                   13082: =item
                   13083: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13084: 
                   13085: =item
                   13086: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13087: 
                   13088: =item
                   13089: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13090: 
                   13091: =item
                   13092: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13093: 
                   13094: =item 
                   13095: $alternateRoot - path to prepend in place of path from $uri.
                   13096: 
                   13097: =back
                   13098: 
                   13099: Returns: Array of up to two items.
                   13100: 
                   13101: =over
                   13102: 
                   13103: a reference to an array of files/subdirectories
                   13104: 
                   13105: =over
                   13106: 
                   13107: Each element in the array of files/subdirectories is a & separated list of
                   13108: item name and the result of running stat on the item.  If dirlist was requested
                   13109: for a file instead of a directory, the item name will be ''. For a directory 
                   13110: listing, if the item is a metadata file, the element will end &N&M 
                   13111: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13112: default copyright set (1).  
                   13113: 
                   13114: =back
                   13115: 
                   13116: a scalar containing error condition (if encountered).
                   13117: 
                   13118: =over
                   13119: 
                   13120: =item 
                   13121: no_host (no homeserver identified for $username:$domain).
                   13122: 
                   13123: =item 
                   13124: no_such_host (server contacted for listing not identified as valid host).
                   13125: 
                   13126: =item 
                   13127: con_lost (connection to remote server failed).
                   13128: 
                   13129: =item 
                   13130: refused (invalid $username:$domain received on lond side).
                   13131: 
                   13132: =item 
                   13133: no_such_dir (directory at specified path on lond side does not exist). 
                   13134: 
                   13135: =item 
                   13136: empty (directory at specified path on lond side is empty).
                   13137: 
                   13138: =over
                   13139: 
                   13140: This is currently not encountered because the &ls3, &ls2, 
                   13141: &ls (_handler) routines on the lond side do not filter out
                   13142: . and .. from a directory listing. 
                   13143: 
                   13144: =back
                   13145: 
                   13146: =back
                   13147: 
                   13148: =back
1.191     harris41 13149: 
                   13150: =item *
                   13151: 
1.243     albertel 13152: spareserver() : find server with least workload from spare.tab
                   13153: 
1.986     foxr     13154: 
                   13155: =item *
                   13156: 
                   13157: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13158: if there is no corresponding loncapa host.
                   13159: 
1.243     albertel 13160: =back
                   13161: 
1.986     foxr     13162: 
1.243     albertel 13163: =head2 Apache Request
                   13164: 
                   13165: =over 4
1.191     harris41 13166: 
                   13167: =item *
                   13168: 
1.243     albertel 13169: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13170: localhost, posts hash
                   13171: 
                   13172: =back
                   13173: 
                   13174: =head2 Data to String to Data
                   13175: 
                   13176: =over 4
1.191     harris41 13177: 
                   13178: =item *
                   13179: 
1.243     albertel 13180: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13181: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13182: 
                   13183: =item *
                   13184: 
1.243     albertel 13185: hashref2str($hashref) : convert a hashref into a string complete with
                   13186: escaping and '=' and '&' separators, supports elements that are
                   13187: arrayrefs and hashrefs
1.191     harris41 13188: 
                   13189: =item *
                   13190: 
1.243     albertel 13191: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13192: with escaping and '&' separators, supports elements that are arrayrefs
                   13193: and hashrefs
1.191     harris41 13194: 
                   13195: =item *
                   13196: 
1.243     albertel 13197: str2hash($string) : convert string to hash using unescaping and
                   13198: splitting on '=' and '&', supports elements that are arrayrefs and
                   13199: hashrefs
1.191     harris41 13200: 
                   13201: =item *
                   13202: 
1.243     albertel 13203: str2array($string) : convert string to hash using unescaping and
                   13204: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13205: 
                   13206: =back
                   13207: 
                   13208: =head2 Logging Routines
                   13209: 
                   13210: 
                   13211: These routines allow one to make log messages in the lonnet.log and
                   13212: lonnet.perm logfiles.
1.191     harris41 13213: 
1.1119    foxr     13214: =over 4
                   13215: 
1.191     harris41 13216: =item *
                   13217: 
1.243     albertel 13218: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13219: 
                   13220: =item *
                   13221: 
1.243     albertel 13222: logthis() : append message to the normal lonnet.log file, it gets
                   13223: preiodically rolled over and deleted.
1.191     harris41 13224: 
                   13225: =item *
                   13226: 
1.243     albertel 13227: logperm() : append a permanent message to lonnet.perm.log, this log
                   13228: file never gets deleted by any automated portion of the system, only
                   13229: messages of critical importance should go in here.
                   13230: 
1.1119    foxr     13231: 
1.243     albertel 13232: =back
                   13233: 
                   13234: =head2 General File Helper Routines
                   13235: 
                   13236: =over 4
1.191     harris41 13237: 
                   13238: =item *
                   13239: 
1.481     raeburn  13240: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13241: (a) files in /uploaded
                   13242:   (i) If a local copy of the file exists - 
                   13243:       compares modification date of local copy with last-modified date for 
                   13244:       definitive version stored on home server for course. If local copy is 
                   13245:       stale, requests a new version from the home server and stores it. 
                   13246:       If the original has been removed from the home server, then local copy 
                   13247:       is unlinked.
                   13248:   (ii) If local copy does not exist -
                   13249:       requests the file from the home server and stores it. 
                   13250:   
                   13251:   If $caller is 'uploadrep':  
                   13252:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13253:     for request for files originally uploaded via DOCS. 
                   13254:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13255:   
                   13256:   Otherwise:
                   13257:      This indicates a call from the content generation phase of the request.
                   13258:      -  returns the entire contents of the file or -1.
                   13259:      
                   13260: (b) files in /res
                   13261:    - returns the entire contents of a file or -1; 
                   13262:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13263: 
1.712     albertel 13264: 
                   13265: =item *
                   13266: 
                   13267: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13268:                   reference
                   13269: 
                   13270: returns either a stat() list of data about the file or an empty list
                   13271: if the file doesn't exist or couldn't find out about it (connection
                   13272: problems or user unknown)
                   13273: 
1.191     harris41 13274: =item *
                   13275: 
1.243     albertel 13276: filelocation($dir,$file) : returns file system location of a file
                   13277: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13278: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13279: and a file of ../bob will become /a/bob)
1.191     harris41 13280: 
                   13281: =item *
                   13282: 
                   13283: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13284: filelocation except for hrefs
                   13285: 
                   13286: =item *
                   13287: 
                   13288: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13289: 
1.243     albertel 13290: =back
                   13291: 
1.608     albertel 13292: =head2 Usererfile file routines (/uploaded*)
                   13293: 
                   13294: =over 4
                   13295: 
                   13296: =item *
                   13297: 
                   13298: userfileupload(): main rotine for putting a file in a user or course's
                   13299:                   filespace, arguments are,
                   13300: 
1.620     albertel 13301:  formname - required - this is the name of the element in $env where the
1.608     albertel 13302:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13303:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13304:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13305:  context - if coursedoc, store the file in the course of the active role
                   13306:              of the current user; 
                   13307:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13308:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13309:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13310:          if undefined, it will be placed in "unknown"
                   13311: 
                   13312:  (This routine calls clean_filename() to remove any dangerous
                   13313:  characters from the filename, and then calls finuserfileupload() to
                   13314:  complete the transaction)
                   13315: 
                   13316:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13317:  and /adm/notfound.html if unsuccessful
                   13318: 
                   13319: =item *
                   13320: 
                   13321: clean_filename(): routine for cleaing a filename up for storage in
                   13322:                  userfile space, argument is:
                   13323: 
                   13324:  filename - proposed filename
                   13325: 
                   13326: returns: the new clean filename
                   13327: 
                   13328: =item *
                   13329: 
1.1090    raeburn  13330: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13331: userspace, probably shouldn't be called directly
                   13332: 
                   13333:   docuname: username or courseid of destination for the file
                   13334:   docudom: domain of user/course of destination for the file
                   13335:   formname: same as for userfileupload()
1.1090    raeburn  13336:   fname: filename (including subdirectories) for the file
                   13337:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13338:   allfiles: reference to hash used to store objects found by parser
                   13339:   codebase: reference to hash used for codebases of java objects found by parser
                   13340:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13341:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13342:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13343:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13344:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13345:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13346:   mimetype: reference to scalar to accommodate mime type determined
                   13347:             from File::MMagic if $parser = parse.
1.608     albertel 13348: 
                   13349:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13350:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13351:  was 'overwrite').
                   13352:  
1.608     albertel 13353: 
                   13354: =item *
                   13355: 
                   13356: renameuserfile(): renames an existing userfile to a new name
                   13357: 
                   13358:   Args:
                   13359:    docuname: username or courseid of destination for the file
                   13360:    docudom: domain of user/course of destination for the file
                   13361:    old: current file name (including any subdirs under userfiles)
                   13362:    new: desired file name (including any subdirs under userfiles)
                   13363: 
                   13364: =item *
                   13365: 
                   13366: mkdiruserfile(): creates a directory is a userfiles dir
                   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:    dir: dir to create (including any subdirs under userfiles)
                   13372: 
                   13373: =item *
                   13374: 
                   13375: removeuserfile(): removes a file that exists in userfiles
                   13376: 
                   13377:   Args:
                   13378:    docuname: username or courseid of destination for the file
                   13379:    docudom: domain of user/course of destination for the file
                   13380:    fname: filname to delete (including any subdirs under userfiles)
                   13381: 
                   13382: =item *
                   13383: 
                   13384: removeuploadedurl(): convience function for removeuserfile()
                   13385: 
                   13386:   Args:
                   13387:    url:  a full /uploaded/... url to delete
                   13388: 
1.747     albertel 13389: =item * 
                   13390: 
                   13391: get_portfile_permissions():
                   13392:   Args:
                   13393:     domain: domain of user or course contain the portfolio files
                   13394:     user: name of user or num of course contain the portfolio files
                   13395:   Returns:
                   13396:     hashref of a dump of the proper file_permissions.db
                   13397:    
                   13398: 
                   13399: =item * 
                   13400: 
                   13401: get_access_controls():
                   13402: 
                   13403: Args:
                   13404:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13405:   group: (optional) the group you want the files associated with
                   13406:   file: (optional) the file you want access info on
                   13407: 
                   13408: Returns:
1.749     raeburn  13409:     a hash (keys are file names) of hashes containing
                   13410:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13411:         values are XML containing access control settings (see below) 
1.747     albertel 13412: 
                   13413: Internal notes:
                   13414: 
1.749     raeburn  13415:  access controls are stored in file_permissions.db as key=value pairs.
                   13416:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13417:         where scope -> public,guest,course,group,domains or users.
                   13418:               end -> UNIX time for end of access (0 -> no end date)
                   13419:               start -> UNIX time for start of access
                   13420: 
                   13421:     value -> XML description of access control
                   13422:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13423:             <start></start>
                   13424:             <end></end>
                   13425: 
                   13426:             <password></password>  for scope type = guest
                   13427: 
                   13428:             <domain></domain>     for scope type = course or group
                   13429:             <number></number>
                   13430:             <roles id="">
                   13431:              <role></role>
                   13432:              <access></access>
                   13433:              <section></section>
                   13434:              <group></group>
                   13435:             </roles>
                   13436: 
                   13437:             <dom></dom>         for scope type = domains
                   13438: 
                   13439:             <users>             for scope type = users
                   13440:              <user>
                   13441:               <uname></uname>
                   13442:               <udom></udom>
                   13443:              </user>
                   13444:             </users>
                   13445:            </scope> 
                   13446:               
                   13447:  Access data is also aggregated for each file in an additional key=value pair:
                   13448:  key -> path to file/file_name\0accesscontrol 
                   13449:  value -> reference to hash
                   13450:           hash contains key = value pairs
                   13451:           where key = uniqueID:scope_end_start
                   13452:                 value = UNIX time record was last updated
                   13453: 
                   13454:           Used to improve speed of look-ups of access controls for each file.  
                   13455:  
                   13456:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13457: 
1.1172.2.13  raeburn  13458: =item *
                   13459: 
1.749     raeburn  13460: modify_access_controls():
                   13461: 
                   13462: Modifies access controls for a portfolio file
                   13463: Args
                   13464: 1. file name
                   13465: 2. reference to hash of required changes,
                   13466: 3. domain
                   13467: 4. username
                   13468:   where domain,username are the domain of the portfolio owner 
                   13469:   (either a user or a course) 
                   13470: 
                   13471: Returns:
                   13472: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13473: 2. result of deletions ('ok' or 'error', with error message).
                   13474: 3. reference to hash of any new or updated access controls.
                   13475: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13476:    key = integer (inbound ID)
1.1172.2.13  raeburn  13477:    value = uniqueID
                   13478: 
                   13479: =item *
                   13480: 
                   13481: get_timebased_id():
                   13482: 
                   13483: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13484: course via the Course Editor (e.g., folders, composite pages,
                   13485: group bulletin boards).
                   13486: 
                   13487: Args: (first three required; six others optional)
                   13488: 
                   13489: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13490:    docssequence, or name of group
                   13491: 
                   13492: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13493:    e.g., num, boardids
                   13494: 
                   13495: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13496:    file will be named nohist_namespace.db
                   13497: 
                   13498: 4. cdom: domain of course; default is current course domain from %env
                   13499: 
                   13500: 5. cnum: course number; default is current course number from %env
                   13501: 
                   13502: 6. idtype: set to concat if an additional digit is to be appended to the
                   13503:    unix timestamp to form the suffix, if the plain timestamp is already
                   13504:    in use.  Default is to not do this, but simply increment the unix
                   13505:    timestamp by 1 until a unique key is obtained.
                   13506: 
                   13507: 7. who: holder of locking key; defaults to user:domain for user.
                   13508: 
                   13509: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13510:    retrying); default is 3.
                   13511: 
                   13512: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13513: 
                   13514: Returns:
                   13515: 
                   13516: 1. suffix obtained (numeric)
                   13517: 
                   13518: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13519: 
                   13520: 3. error: contains (localized) error message if an error occurred.
                   13521: 
1.747     albertel 13522: 
1.608     albertel 13523: =back
                   13524: 
1.243     albertel 13525: =head2 HTTP Helper Routines
                   13526: 
                   13527: =over 4
                   13528: 
1.191     harris41 13529: =item *
                   13530: 
                   13531: escape() : unpack non-word characters into CGI-compatible hex codes
                   13532: 
                   13533: =item *
                   13534: 
                   13535: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13536: 
1.243     albertel 13537: =back
                   13538: 
                   13539: =head1 PRIVATE SUBROUTINES
                   13540: 
                   13541: =head2 Underlying communication routines (Shouldn't call)
                   13542: 
                   13543: =over 4
                   13544: 
                   13545: =item *
                   13546: 
                   13547: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13548: 
                   13549: =item *
                   13550: 
                   13551: reply() : uses subreply to send a message to remote machine, logs all failures
                   13552: 
                   13553: =item *
                   13554: 
                   13555: critical() : passes a critical message to another server; if cannot
                   13556: get through then place message in connection buffer directory and
                   13557: returns con_delayed, if incapable of saving message, returns
                   13558: con_failed
                   13559: 
                   13560: =item *
                   13561: 
                   13562: reconlonc() : tries to reconnect lonc client processes.
                   13563: 
                   13564: =back
                   13565: 
                   13566: =head2 Resource Access Logging
                   13567: 
                   13568: =over 4
                   13569: 
                   13570: =item *
                   13571: 
                   13572: flushcourselogs() : flush (save) buffer logs and access logs
                   13573: 
                   13574: =item *
                   13575: 
                   13576: courselog($what) : save message for course in hash
                   13577: 
                   13578: =item *
                   13579: 
                   13580: courseacclog($what) : save message for course using &courselog().  Perform
                   13581: special processing for specific resource types (problems, exams, quizzes, etc).
                   13582: 
1.191     harris41 13583: =item *
                   13584: 
                   13585: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13586: as a PerlChildExitHandler
1.243     albertel 13587: 
                   13588: =back
                   13589: 
                   13590: =head2 Other
                   13591: 
                   13592: =over 4
                   13593: 
                   13594: =item *
                   13595: 
                   13596: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13597: 
                   13598: =back
                   13599: 
                   13600: =cut
1.877     foxr     13601: 

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