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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.20! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.19 2013/03/02 15:34:17 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.18  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1117    foxr      100: 
1.1090    raeburn   101: use File::Copy;
1.676     albertel  102: 
1.195     www       103: my $readit;
1.550     foxr      104: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  105: 
1.619     albertel  106: require Exporter;
                    107: 
                    108: our @ISA = qw (Exporter);
                    109: our @EXPORT = qw(%env);
                    110: 
1.1172.2.9  raeburn   111: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       112: {
                    113:     my $logid;
1.1172.2.9  raeburn   114:     sub write_log {
                    115: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    116:         if ($context eq 'course') {
                    117:             if (($cnum eq '') || ($cdom eq '')) {
                    118:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    119:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    120:             }
1.957     raeburn   121:         }
1.1172.2.13  raeburn   122: 	$logid ++;
1.957     raeburn   123:         my $now = time();
                    124: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   125:         my $logentry = {
                    126:                          $id => {
                    127:                                   'exe_uname' => $env{'user.name'},
                    128:                                   'exe_udom'  => $env{'user.domain'},
                    129:                                   'exe_time'  => $now,
                    130:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    131:                                   'delflag'   => $delflag,
                    132:                                   'logentry'  => $storehash,
                    133:                                   'uname'     => $uname,
                    134:                                   'udom'      => $udom,
                    135:                                 }
                    136:                        };
                    137:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       138:     }
                    139: }
1.1       albertel  140: 
1.163     harris41  141: sub logtouch {
                    142:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  143:     unless (-e "$execdir/logs/lonnet.log") {	
                    144: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  145: 	close $fh;
                    146:     }
                    147:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    148:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    149: }
                    150: 
1.1       albertel  151: sub logthis {
                    152:     my $message=shift;
                    153:     my $execdir=$perlvar{'lonDaemons'};
                    154:     my $now=time;
                    155:     my $local=localtime($now);
1.448     albertel  156:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      157: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    158: 	print $fh $logstring;
1.448     albertel  159: 	close($fh);
                    160:     }
1.1       albertel  161:     return 1;
                    162: }
                    163: 
                    164: sub logperm {
                    165:     my $message=shift;
                    166:     my $execdir=$perlvar{'lonDaemons'};
                    167:     my $now=time;
                    168:     my $local=localtime($now);
1.448     albertel  169:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    170: 	print $fh "$now:$message:$local\n";
                    171: 	close($fh);
                    172:     }
1.1       albertel  173:     return 1;
                    174: }
                    175: 
1.850     albertel  176: sub create_connection {
1.853     albertel  177:     my ($hostname,$lonid) = @_;
1.851     albertel  178:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  179: 				     Type    => SOCK_STREAM,
                    180: 				     Timeout => 10);
                    181:     return 0 if (!$client);
1.890     albertel  182:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  183:     my $result = <$client>;
                    184:     chomp($result);
                    185:     return 1 if ($result eq 'done');
                    186:     return 0;
                    187: }
                    188: 
1.983     raeburn   189: sub get_server_timezone {
                    190:     my ($cnum,$cdom) = @_;
                    191:     my $home=&homeserver($cnum,$cdom);
                    192:     if ($home ne 'no_host') {
                    193:         my $cachetime = 24*3600;
                    194:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    195:         if (defined($cached)) {
                    196:             return $timezone;
                    197:         } else {
                    198:             my $timezone = &reply('servertimezone',$home);
                    199:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    200:         }
                    201:     }
                    202: }
1.850     albertel  203: 
1.1106    raeburn   204: sub get_server_distarch {
                    205:     my ($lonhost,$ignore_cache) = @_;
                    206:     if (defined($lonhost)) {
                    207:         if (!defined(&hostname($lonhost))) {
                    208:             return;
                    209:         }
                    210:         my $cachetime = 12*3600;
                    211:         if (!$ignore_cache) {
                    212:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    213:             if (defined($cached)) {
                    214:                 return $distarch;
                    215:             }
                    216:         }
                    217:         my $rep = &reply('serverdistarch',$lonhost);
                    218:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    219:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    220:                 $rep eq '') {
                    221:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    222:         }
                    223:     }
                    224:     return;
                    225: }
                    226: 
1.993     raeburn   227: sub get_server_loncaparev {
1.1073    raeburn   228:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   229:     if (defined($lonhost)) {
                    230:         if (!defined(&hostname($lonhost))) {
                    231:             undef($lonhost);
                    232:         }
                    233:     }
                    234:     if (!defined($lonhost)) {
                    235:         if (defined(&domain($dom,'primary'))) {
                    236:             $lonhost=&domain($dom,'primary');
                    237:             if ($lonhost eq 'no_host') {
                    238:                 undef($lonhost);
                    239:             }
                    240:         }
                    241:     }
                    242:     if (defined($lonhost)) {
1.1073    raeburn   243:         my $cachetime = 12*3600;
                    244:         if (!$ignore_cache) {
                    245:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    246:             if (defined($cached)) {
                    247:                 return $loncaparev;
                    248:             }
                    249:         }
                    250:         my ($answer,$loncaparev);
                    251:         my @ids=&current_machine_ids();
                    252:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    253:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   254:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   255:                 $loncaparev = $1;
                    256:             }
                    257:         } else {
                    258:             $answer = &reply('serverloncaparev',$lonhost);
                    259:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    260:                 if ($caller eq 'loncron') {
                    261:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   262:                     $ua->timeout(4);
1.1073    raeburn   263:                     my $protocol = $protocol{$lonhost};
                    264:                     $protocol = 'http' if ($protocol ne 'https');
                    265:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    266:                     my $request=new HTTP::Request('GET',$url);
                    267:                     my $response=$ua->request($request);
                    268:                     unless ($response->is_error()) {
                    269:                         my $content = $response->content;
1.1081    raeburn   270:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   271:                             $loncaparev = $1;
                    272:                         }
                    273:                     }
                    274:                 } else {
                    275:                     $loncaparev = $loncaparevs{$lonhost};
                    276:                 }
1.1081    raeburn   277:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   278:                 $loncaparev = $1;
                    279:             }
1.993     raeburn   280:         }
1.1073    raeburn   281:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   282:     }
                    283: }
                    284: 
1.1074    raeburn   285: sub get_server_homeID {
                    286:     my ($hostname,$ignore_cache,$caller) = @_;
                    287:     unless ($ignore_cache) {
                    288:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    289:         if (defined($cached)) {
                    290:             return $serverhomeID;
                    291:         }
                    292:     }
                    293:     my $cachetime = 12*3600;
                    294:     my $serverhomeID;
                    295:     if ($caller eq 'loncron') { 
                    296:         my @machine_ids = &machine_ids($hostname);
                    297:         foreach my $id (@machine_ids) {
                    298:             my $response = &reply('serverhomeID',$id);
                    299:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    300:                 $serverhomeID = $response;
                    301:                 last;
                    302:             }
                    303:         }
                    304:         if ($serverhomeID eq '') {
                    305:             $serverhomeID = $machine_ids[-1];
                    306:         }
                    307:     } else {
                    308:         $serverhomeID = $serverhomeIDs{$hostname};
                    309:     }
                    310:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    311: }
                    312: 
1.1121    raeburn   313: sub get_remote_globals {
                    314:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   315:     my ($result,%returnhash,%whatneeded);
                    316:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   317:         foreach my $what (sort(keys(%{$whathash}))) {
                    318:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   319:             my ($response,$cached);
1.1121    raeburn   320:             unless ($ignore_cache) {
1.1125    raeburn   321:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   322:             }
                    323:             if (defined($cached)) {
1.1125    raeburn   324:                 $returnhash{$what} = $response;
1.1121    raeburn   325:             } else {
1.1125    raeburn   326:                 $whatneeded{$what} = 1;
1.1121    raeburn   327:             }
                    328:         }
1.1125    raeburn   329:         if (keys(%whatneeded) == 0) {
                    330:             $result = 'ok';
                    331:         } else {
1.1121    raeburn   332:             my $requested = &freeze_escape(\%whatneeded);
                    333:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   334:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    335:                 ($rep eq 'unknown_cmd')) {
                    336:                 $result = $rep;
                    337:             } else {
                    338:                 $result = 'ok';
1.1121    raeburn   339:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   340:                 foreach my $item (@pairs) {
                    341:                     my ($key,$value)=split(/=/,$item,2);
                    342:                     my $what = &unescape($key);
                    343:                     my $hashid = $lonhost.'-'.$what;
                    344:                     $returnhash{$what}=&thaw_unescape($value);
                    345:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   346:                 }
                    347:             }
                    348:         }
                    349:     }
1.1125    raeburn   350:     return ($result,\%returnhash);
1.1121    raeburn   351: }
                    352: 
1.1124    raeburn   353: sub remote_devalidate_cache {
                    354:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   355:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   356:     return $response;
                    357: }
                    358: 
1.1       albertel  359: # -------------------------------------------------- Non-critical communication
                    360: sub subreply {
                    361:     my ($cmd,$server)=@_;
1.838     albertel  362:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      363:     #
                    364:     #  With loncnew process trimming, there's a timing hole between lonc server
                    365:     #  process exit and the master server picking up the listen on the AF_UNIX
                    366:     #  socket.  In that time interval, a lock file will exist:
                    367: 
                    368:     my $lockfile=$peerfile.".lock";
                    369:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    370: 	sleep(1);
                    371:     }
                    372:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      373:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      374:     #
1.550     foxr      375:     #   We'll give the connection a few tries before abandoning it.  If
                    376:     #   connection is not possible, we'll con_lost back to the client.
                    377:     #   
                    378:     my $client;
                    379:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    380: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    381: 				      Type    => SOCK_STREAM,
                    382: 				      Timeout => 10);
1.869     albertel  383: 	if ($client) {
1.550     foxr      384: 	    last;		# Connected!
1.850     albertel  385: 	} else {
1.853     albertel  386: 	    &create_connection(&hostname($server),$server);
1.550     foxr      387: 	}
1.850     albertel  388:         sleep(1);		# Try again later if failed connection.
1.550     foxr      389:     }
                    390:     my $answer;
                    391:     if ($client) {
1.704     albertel  392: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      393: 	$answer=<$client>;
                    394: 	if (!$answer) { $answer="con_lost"; }
                    395: 	chomp($answer);
                    396:     } else {
                    397: 	$answer = 'con_lost';	# Failed connection.
                    398:     }
1.1       albertel  399:     return $answer;
                    400: }
                    401: 
                    402: sub reply {
                    403:     my ($cmd,$server)=@_;
1.838     albertel  404:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  405:     my $answer=subreply($cmd,$server);
1.65      www       406:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  407:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       408:                 " $cmd to $server returned $answer</font>");
                    409:     }
1.1       albertel  410:     return $answer;
                    411: }
                    412: 
                    413: # ----------------------------------------------------------- Send USR1 to lonc
                    414: 
                    415: sub reconlonc {
1.891     albertel  416:     my ($lonid) = @_;
                    417:     my $hostname = &hostname($lonid);
                    418:     if ($lonid) {
                    419: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    420: 	if ($hostname && -e $peerfile) {
                    421: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    422: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    423: 					     Type    => SOCK_STREAM,
                    424: 					     Timeout => 10);
                    425: 	    if ($client) {
                    426: 		print $client ("reset_retries\n");
                    427: 		my $answer=<$client>;
                    428: 		#reset just this one.
                    429: 	    }
                    430: 	}
                    431: 	return;
                    432:     }
                    433: 
1.836     www       434:     &logthis("Trying to reconnect lonc");
1.1       albertel  435:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  436:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  437: 	my $loncpid=<$fh>;
                    438:         chomp($loncpid);
                    439:         if (kill 0 => $loncpid) {
                    440: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    441:             kill USR1 => $loncpid;
                    442:             sleep 1;
1.836     www       443:          } else {
1.12      www       444: 	    &logthis(
1.672     albertel  445:                "<font color=\"blue\">WARNING:".
1.12      www       446:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  447:         }
                    448:     } else {
1.836     www       449: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  450:     }
                    451: }
                    452: 
                    453: # ------------------------------------------------------ Critical communication
1.12      www       454: 
1.1       albertel  455: sub critical {
                    456:     my ($cmd,$server)=@_;
1.838     albertel  457:     unless (&hostname($server)) {
1.672     albertel  458:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       459:                " Critical message to unknown server ($server)</font>");
                    460:         return 'no_such_host';
                    461:     }
1.1       albertel  462:     my $answer=reply($cmd,$server);
                    463:     if ($answer eq 'con_lost') {
                    464: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  465: 	my $answer=reply($cmd,$server);
1.1       albertel  466:         if ($answer eq 'con_lost') {
                    467:             my $now=time;
                    468:             my $middlename=$cmd;
1.5       www       469:             $middlename=substr($middlename,0,16);
1.1       albertel  470:             $middlename=~s/\W//g;
                    471:             my $dfilename=
1.305     www       472:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    473:             $dumpcount++;
1.1       albertel  474:             {
1.448     albertel  475: 		my $dfh;
                    476: 		if (open($dfh,">$dfilename")) {
                    477: 		    print $dfh "$cmd\n"; 
                    478: 		    close($dfh);
                    479: 		}
1.1       albertel  480:             }
                    481:             sleep 2;
                    482:             my $wcmd='';
                    483:             {
1.448     albertel  484: 		my $dfh;
                    485: 		if (open($dfh,"<$dfilename")) {
                    486: 		    $wcmd=<$dfh>; 
                    487: 		    close($dfh);
                    488: 		}
1.1       albertel  489:             }
                    490:             chomp($wcmd);
1.7       www       491:             if ($wcmd eq $cmd) {
1.672     albertel  492: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       493:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  494:                 &logperm("D:$server:$cmd");
                    495: 	        return 'con_delayed';
                    496:             } else {
1.672     albertel  497:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       498:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  499:                 &logperm("F:$server:$cmd");
                    500:                 return 'con_failed';
                    501:             }
                    502:         }
                    503:     }
                    504:     return $answer;
1.405     albertel  505: }
                    506: 
1.755     albertel  507: # ------------------------------------------- check if return value is an error
                    508: 
                    509: sub error {
                    510:     my ($result) = @_;
1.756     albertel  511:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  512: 	if ($2 == 2) { return undef; }
                    513: 	return $1;
                    514:     }
                    515:     return undef;
                    516: }
                    517: 
1.783     albertel  518: sub convert_and_load_session_env {
                    519:     my ($lonidsdir,$handle)=@_;
                    520:     my @profile;
                    521:     {
1.917     albertel  522: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    523: 	if (!$opened) {
1.915     albertel  524: 	    return 0;
                    525: 	}
1.783     albertel  526: 	flock($idf,LOCK_SH);
                    527: 	@profile=<$idf>;
                    528: 	close($idf);
                    529:     }
                    530:     my %temp_env;
                    531:     foreach my $line (@profile) {
1.786     albertel  532: 	if ($line !~ m/=/) {
                    533: 	    return 0;
                    534: 	}
1.783     albertel  535: 	chomp($line);
                    536: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    537: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    538:     }
                    539:     unlink("$lonidsdir/$handle.id");
                    540:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    541: 	    0640)) {
                    542: 	%disk_env = %temp_env;
                    543: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    544: 	untie(%disk_env);
                    545:     }
1.786     albertel  546:     return 1;
1.783     albertel  547: }
                    548: 
1.374     www       549: # ------------------------------------------- Transfer profile into environment
1.780     albertel  550: my $env_loaded;
                    551: sub transfer_profile_to_env {
1.788     albertel  552:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    553:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       554: 
1.720     albertel  555:     if (!defined($lonidsdir)) {
                    556: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    557:     }
                    558:     if (!defined($handle)) {
                    559:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    560:     }
                    561: 
1.786     albertel  562:     my $convert;
                    563:     {
1.917     albertel  564:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    565: 	if (!$opened) {
1.915     albertel  566: 	    return;
                    567: 	}
1.786     albertel  568: 	flock($idf,LOCK_SH);
                    569: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    570: 		&GDBM_READER(),0640)) {
                    571: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    572: 	    untie(%disk_env);
                    573: 	} else {
                    574: 	    $convert = 1;
                    575: 	}
                    576:     }
                    577:     if ($convert) {
                    578: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    579: 	    &logthis("Failed to load session, or convert session.");
                    580: 	}
1.374     www       581:     }
1.783     albertel  582: 
1.786     albertel  583:     my %remove;
1.783     albertel  584:     while ( my $envname = each(%env) ) {
1.433     matthew   585:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    586:             if ($time < time-300) {
1.783     albertel  587:                 $remove{$key}++;
1.433     matthew   588:             }
                    589:         }
                    590:     }
1.783     albertel  591: 
1.619     albertel  592:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  593:     $env_loaded=1;
1.783     albertel  594:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   595:         &delenv($expired_key);
1.374     www       596:     }
1.1       albertel  597: }
                    598: 
1.916     albertel  599: # ---------------------------------------------------- Check for valid session 
                    600: sub check_for_valid_session {
1.1155    raeburn   601:     my ($r,$name) = @_;
1.916     albertel  602:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   603:     if ($name eq '') {
                    604:         $name = 'lonID';
                    605:     }
                    606:     my $lonid=$cookies{$name};
1.916     albertel  607:     return undef if (!$lonid);
                    608: 
                    609:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   610:     my $lonidsdir;
                    611:     if ($name eq 'lonDAV') {
                    612:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    613:     } else {
                    614:         $lonidsdir=$r->dir_config('lonIDsDir');
                    615:     }
1.916     albertel  616:     return undef if (!-e "$lonidsdir/$handle.id");
                    617: 
1.917     albertel  618:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    619:     return undef if (!$opened);
1.916     albertel  620: 
                    621:     flock($idf,LOCK_SH);
                    622:     my %disk_env;
                    623:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    624: 	    &GDBM_READER(),0640)) {
                    625: 	return undef;	
                    626:     }
                    627: 
                    628:     if (!defined($disk_env{'user.name'})
                    629: 	|| !defined($disk_env{'user.domain'})) {
                    630: 	return undef;
                    631:     }
1.1172.2.18  raeburn   632: 
                    633:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    634:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    635:             $r->user($disk_env{'user.name'});
                    636:         } else {
                    637:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    638:         }
                    639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
                    674:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    847:                 if ($uint_dom) {
                    848:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    849:                                                  $try_server));
                    850:                 }
                    851: 	        ($spare_server, $lowest_load) =
                    852: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    853:             }
1.1083    raeburn   854:         }
1.784     albertel  855: 
1.1123    raeburn   856:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    857: 
                    858:         if (!$found_server) {
                    859:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    860: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    861:                     if ($uint_dom) {
                    862:                         next unless (&spare_can_host($udom,$uint_dom,
                    863:                                                      $remotesessions,$try_server));
                    864:                     }
                    865: 	            ($spare_server, $lowest_load) =
                    866: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    867:                 }
                    868: 	    }
                    869:         }
1.784     albertel  870:     }
                    871: 
                    872:     if (!$want_server_name) {
1.968     raeburn   873:         my $protocol = 'http';
                    874:         if ($protocol{$spare_server} eq 'https') {
                    875:             $protocol = $protocol{$spare_server};
                    876:         }
1.1001    raeburn   877:         if (defined($spare_server)) {
                    878:             my $hostname = &hostname($spare_server);
1.1083    raeburn   879:             if (defined($hostname)) {
1.1001    raeburn   880: 	        $spare_server = $protocol.'://'.$hostname;
                    881:             }
                    882:         }
1.784     albertel  883:     }
                    884:     return $spare_server;
                    885: }
                    886: 
                    887: sub compare_server_load {
                    888:     my ($try_server, $spare_server, $lowest_load) = @_;
                    889: 
                    890:     my $loadans     = &reply('load',    $try_server);
                    891:     my $userloadans = &reply('userload',$try_server);
                    892: 
                    893:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   894: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  895:     }
                    896: 
                    897:     my $load;
                    898:     if ($loadans =~ /\d/) {
                    899: 	if ($userloadans =~ /\d/) {
                    900: 	    #both are numbers, pick the bigger one
                    901: 	    $load = ($loadans > $userloadans) ? $loadans 
                    902: 		                              : $userloadans;
1.411     albertel  903: 	} else {
1.784     albertel  904: 	    $load = $loadans;
1.411     albertel  905: 	}
1.784     albertel  906:     } else {
                    907: 	$load = $userloadans;
                    908:     }
                    909: 
                    910:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    911: 	$spare_server = $try_server;
                    912: 	$lowest_load  = $load;
1.370     albertel  913:     }
1.784     albertel  914:     return ($spare_server,$lowest_load);
1.202     matthew   915: }
1.914     albertel  916: 
                    917: # --------------------------- ask offload servers if user already has a session
                    918: sub find_existing_session {
                    919:     my ($udom,$uname) = @_;
1.1123    raeburn   920:     my $spareshash = &this_host_spares($udom);
                    921:     if (ref($spareshash) eq 'HASH') {
                    922:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    923:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    924:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    925:             }
                    926:         }
                    927:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    928:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    929:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    930:             }
                    931:         }
1.914     albertel  932:     }
                    933:     return;
                    934: }
                    935: 
                    936: # -------------------------------- ask if server already has a session for user
                    937: sub has_user_session {
                    938:     my ($lonid,$udom,$uname) = @_;
                    939:     my $result = &reply(join(':','userhassession',
                    940: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    941:     return 1 if ($result eq 'ok');
                    942: 
                    943:     return 0;
                    944: }
                    945: 
1.1076    raeburn   946: # --------- determine least loaded server in a user's domain which allows login
                    947: 
                    948: sub choose_server {
1.1115    raeburn   949:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   950:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   951:     my %servers = &get_servers($udom);
1.1076    raeburn   952:     my $lowest_load = 30000;
1.1151    raeburn   953:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   954:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   955:         my $loginvia;
                    956:         if ($checkloginvia) {
                    957:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   958:             if ($loginvia) {
                    959:                 my ($server,$path) = split(/:/,$loginvia);
                    960:                 ($login_host, $lowest_load) =
                    961:                     &compare_server_load($server, $login_host, $lowest_load);
                    962:                 if ($login_host eq $server) {
                    963:                     $portal_path = $path;
1.1151    raeburn   964:                     $isredirect = 1;
1.1116    raeburn   965:                 }
                    966:             } else {
                    967:                 ($login_host, $lowest_load) =
                    968:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    969:                 if ($login_host eq $lonhost) {
                    970:                     $portal_path = '';
1.1151    raeburn   971:                     $isredirect = ''; 
1.1116    raeburn   972:                 }
                    973:             }
                    974:         } else {
1.1076    raeburn   975:             ($login_host, $lowest_load) =
1.1116    raeburn   976:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   977:         }
                    978:     }
                    979:     if ($login_host ne '') {
1.1116    raeburn   980:         $hostname = &hostname($login_host);
1.1076    raeburn   981:     }
1.1151    raeburn   982:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   983: }
                    984: 
1.202     matthew   985: # --------------------------------------------- Try to change a user's password
                    986: 
                    987: sub changepass {
1.799     raeburn   988:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   989:     $currentpass = &escape($currentpass);
                    990:     $newpass     = &escape($newpass);
1.1030    raeburn   991:     my $lonhost = $perlvar{'lonHostID'};
                    992:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   993: 		       $server);
                    994:     if (! $answer) {
                    995: 	&logthis("No reply on password change request to $server ".
                    996: 		 "by $uname in domain $udom.");
                    997:     } elsif ($answer =~ "^ok") {
                    998:         &logthis("$uname in $udom successfully changed their password ".
                    999: 		 "on $server.");
                   1000:     } elsif ($answer =~ "^pwchange_failure") {
                   1001: 	&logthis("$uname in $udom was unable to change their password ".
                   1002: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1003: 		 "or pwchange");
                   1004:     } elsif ($answer =~ "^non_authorized") {
                   1005:         &logthis("$uname in $udom did not get their password correct when ".
                   1006: 		 "attempting to change it on $server.");
                   1007:     } elsif ($answer =~ "^auth_mode_error") {
                   1008:         &logthis("$uname in $udom attempted to change their password despite ".
                   1009: 		 "not being locally or internally authenticated on $server.");
                   1010:     } elsif ($answer =~ "^unknown_user") {
                   1011:         &logthis("$uname in $udom attempted to change their password ".
                   1012: 		 "on $server but were unable to because $server is not ".
                   1013: 		 "their home server.");
                   1014:     } elsif ($answer =~ "^refused") {
                   1015: 	&logthis("$server refused to change $uname in $udom password because ".
                   1016: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1017:     } elsif ($answer =~ "invalid_client") {
                   1018:         &logthis("$server refused to change $uname in $udom password because ".
                   1019:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1020:     }
                   1021:     return $answer;
1.1       albertel 1022: }
                   1023: 
1.169     harris41 1024: # ----------------------- Try to determine user's current authentication scheme
                   1025: 
                   1026: sub queryauthenticate {
                   1027:     my ($uname,$udom)=@_;
1.456     albertel 1028:     my $uhome=&homeserver($uname,$udom);
                   1029:     if (!$uhome) {
                   1030: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1031: 	return 'no_host';
                   1032:     }
                   1033:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1034:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1035: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1036:     }
1.456     albertel 1037:     return $answer;
1.169     harris41 1038: }
                   1039: 
1.1       albertel 1040: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1041: 
1.1       albertel 1042: sub authenticate {
1.1073    raeburn  1043:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1044:     $upass=&escape($upass);
                   1045:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1046:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1047:     my $newhome;
1.836     www      1048:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1049: # Maybe the machine was offline and only re-appeared again recently?
                   1050:         &reconlonc();
                   1051: # One more
1.952     raeburn  1052: 	$uhome=&homeserver($uname,$udom,1);
                   1053:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1054:             if (defined(&domain($udom,'primary'))) {
                   1055:                 $newhome=&domain($udom,'primary');
                   1056:             }
                   1057:             if ($newhome ne '') {
                   1058:                 $uhome = $newhome;
                   1059:             }
                   1060:         }
1.836     www      1061: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1062: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1063: 	    return 'no_host';
                   1064:         }
1.1       albertel 1065:     }
1.1073    raeburn  1066:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1067:     if ($answer eq 'authorized') {
1.952     raeburn  1068:         if ($newhome) {
                   1069:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1070:             return 'no_account_on_host'; 
                   1071:         } else {
                   1072:             &logthis("User $uname at $udom authorized by $uhome");
                   1073:             return $uhome;
                   1074:         }
1.471     albertel 1075:     }
                   1076:     if ($answer eq 'non_authorized') {
                   1077: 	&logthis("User $uname at $udom rejected by $uhome");
                   1078: 	return 'no_host'; 
1.9       www      1079:     }
1.471     albertel 1080:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1081:     return 'no_host';
                   1082: }
                   1083: 
1.1073    raeburn  1084: sub can_host_session {
1.1074    raeburn  1085:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1086:     my $canhost = 1;
1.1074    raeburn  1087:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1088:     if (ref($remotesessions) eq 'HASH') {
                   1089:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1090:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1091:                 $canhost = 0;
                   1092:             } else {
                   1093:                 $canhost = 1;
                   1094:             }
                   1095:         }
                   1096:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1097:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1098:                 $canhost = 1;
                   1099:             } else {
                   1100:                 $canhost = 0;
                   1101:             }
                   1102:         }
                   1103:         if ($canhost) {
                   1104:             if ($remotesessions->{'version'} ne '') {
                   1105:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1106:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1107:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1108:                         my $major = $1;
                   1109:                         my $minor = $2;
                   1110:                         if (($major < $reqmajor ) ||
                   1111:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1112:                             $canhost = 0;
                   1113:                         }
                   1114:                     } else {
                   1115:                         $canhost = 0;
                   1116:                     }
                   1117:                 }
                   1118:             }
                   1119:         }
                   1120:     }
                   1121:     if ($canhost) {
                   1122:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1123:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1124:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1125:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1126:                 if (($uint_dom ne '') && 
                   1127:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1128:                     $canhost = 0;
                   1129:                 } else {
                   1130:                     $canhost = 1;
                   1131:                 }
                   1132:             }
                   1133:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1134:                 if (($uint_dom ne '') && 
                   1135:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1136:                     $canhost = 1;
                   1137:                 } else {
                   1138:                     $canhost = 0;
                   1139:                 }
                   1140:             }
                   1141:         }
                   1142:     }
                   1143:     return $canhost;
                   1144: }
                   1145: 
1.1083    raeburn  1146: sub spare_can_host {
                   1147:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1148:     my $canhost=1;
                   1149:     my @intdoms;
                   1150:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1151:     if (ref($internet_names) eq 'ARRAY') {
                   1152:         @intdoms = @{$internet_names};
                   1153:     }
                   1154:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1155:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1156:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1157:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1158:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1159:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1160:                                      $remotesessions,
                   1161:                                      $defdomdefaults{'hostedsessions'});
                   1162:     }
                   1163:     return $canhost;
                   1164: }
                   1165: 
1.1123    raeburn  1166: sub this_host_spares {
                   1167:     my ($dom) = @_;
1.1126    raeburn  1168:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1169:     my @hosts = &current_machine_ids();
                   1170:     foreach my $lonhost (@hosts) {
                   1171:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1172:             $dom_in_use = $dom;
                   1173:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1174:             last;
                   1175:         }
                   1176:     }
1.1126    raeburn  1177:     if ($dom_in_use ne '') {
                   1178:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1179:     }
                   1180:     if (ref($result) ne 'HASH') {
                   1181:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1182:         $dom_in_use = &host_domain($lonhost_in_use);
                   1183:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1184:         if (ref($result) ne 'HASH') {
                   1185:             $result = \%spareid;
                   1186:         }
                   1187:     }
                   1188:     return $result;
                   1189: }
                   1190: 
                   1191: sub spares_for_offload  {
                   1192:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1193:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1194:     if (defined($cached)) {
                   1195:         return $result;
                   1196:     } else {
1.1126    raeburn  1197:         my $cachetime = 60*60*24;
                   1198:         my %domconfig =
                   1199:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1200:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1201:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1202:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1203:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1204:                 }
                   1205:             }
                   1206:         }
                   1207:     }
1.1126    raeburn  1208:     return;
1.1123    raeburn  1209: }
                   1210: 
1.1129    raeburn  1211: sub get_lonbalancer_config {
                   1212:     my ($servers) = @_;
                   1213:     my ($currbalancer,$currtargets);
                   1214:     if (ref($servers) eq 'HASH') {
                   1215:         foreach my $server (keys(%{$servers})) {
                   1216:             my %what = (
                   1217:                          spareid => 1,
                   1218:                          perlvar => 1,
                   1219:                        );
                   1220:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1221:             if ($result eq 'ok') {
                   1222:                 if (ref($returnhash) eq 'HASH') {
                   1223:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1224:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1225:                             $currbalancer = $server;
                   1226:                             $currtargets = {};
                   1227:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1228:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1229:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1230:                                 }
                   1231:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1232:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1233:                                 }
                   1234:                             }
                   1235:                             last;
                   1236:                         }
                   1237:                     }
                   1238:                 }
                   1239:             }
                   1240:         }
                   1241:     }
                   1242:     return ($currbalancer,$currtargets);
                   1243: }
                   1244: 
                   1245: sub check_loadbalancing {
                   1246:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1247:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1248:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1249:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1250:     my @hosts = &current_machine_ids();
1.1129    raeburn  1251:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1252:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1253:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1254:     my $serverhomedom = &host_domain($lonhost);
                   1255: 
                   1256:     my $cachetime = 60*60*24;
                   1257: 
                   1258:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1259:         $dom_in_use = $udom;
                   1260:         $homeintdom = 1;
                   1261:     } else {
                   1262:         $dom_in_use = $serverhomedom;
                   1263:     }
                   1264:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1265:     unless (defined($cached)) {
                   1266:         my %domconfig =
                   1267:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1268:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1269:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1270:         }
                   1271:     }
                   1272:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1273:         ($is_balancer,$currtargets,$currrules) =
                   1274:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1275:         if ($is_balancer) {
                   1276:             if (ref($currrules) eq 'HASH') {
                   1277:                 if ($homeintdom) {
                   1278:                     if ($uname ne '') {
                   1279:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1280:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1281:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1282:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1283:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1284:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1285:                             }
                   1286:                         }
                   1287:                         if ($rule_in_effect eq '') {
                   1288:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1289:                             if ($userenv{'inststatus'} ne '') {
                   1290:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1291:                                 my ($othertitle,$usertypes,$types) =
                   1292:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1293:                                 if (ref($types) eq 'ARRAY') {
                   1294:                                     foreach my $type (@{$types}) {
                   1295:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1296:                                             if (exists($currrules->{$type})) {
                   1297:                                                 $rule_in_effect = $currrules->{$type};
                   1298:                                             }
                   1299:                                         }
                   1300:                                     }
                   1301:                                 }
                   1302:                             } else {
                   1303:                                 if (exists($currrules->{'default'})) {
                   1304:                                     $rule_in_effect = $currrules->{'default'};
                   1305:                                 }
                   1306:                             }
                   1307:                         }
                   1308:                     } else {
                   1309:                         if (exists($currrules->{'default'})) {
                   1310:                             $rule_in_effect = $currrules->{'default'};
                   1311:                         }
                   1312:                     }
                   1313:                 } else {
                   1314:                     if ($currrules->{'_LC_external'} ne '') {
                   1315:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1316:                     }
                   1317:                 }
                   1318:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1319:                                                        $uname,$udom);
                   1320:             }
                   1321:         }
                   1322:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1323:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1324:         unless (defined($cached)) {
                   1325:             my %domconfig =
                   1326:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1327:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1328:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1329:             }
                   1330:         }
                   1331:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1332:             ($is_balancer,$currtargets,$currrules) =
                   1333:                 &check_balancer_result($result,@hosts);
                   1334:             if ($is_balancer) {
1.1129    raeburn  1335:                 if (ref($currrules) eq 'HASH') {
                   1336:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1337:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1338:                     }
                   1339:                 }
                   1340:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1341:                                                        $uname,$udom);
                   1342:             }
                   1343:         } else {
                   1344:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1345:                 $is_balancer = 1;
                   1346:                 $offloadto = &this_host_spares($dom_in_use);
                   1347:             }
                   1348:         }
                   1349:     } else {
                   1350:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1351:             $is_balancer = 1;
                   1352:             $offloadto = &this_host_spares($dom_in_use);
                   1353:         }
                   1354:     }
1.1172.2.5  raeburn  1355:     if ($is_balancer) {
                   1356:         my $lowest_load = 30000;
                   1357:         if (ref($offloadto) eq 'HASH') {
                   1358:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1359:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1360:                     ($otherserver,$lowest_load) =
                   1361:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1362:                 }
1.1129    raeburn  1363:             }
1.1172.2.5  raeburn  1364:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1365: 
1.1172.2.5  raeburn  1366:             if (!$found_server) {
                   1367:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1368:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1369:                         ($otherserver,$lowest_load) =
                   1370:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1371:                     }
                   1372:                 }
                   1373:             }
                   1374:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1375:             if (@{$offloadto} == 1) {
                   1376:                 $otherserver = $offloadto->[0];
                   1377:             } elsif (@{$offloadto} > 1) {
                   1378:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1379:                     ($otherserver,$lowest_load) =
                   1380:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1381:                 }
                   1382:             }
                   1383:         }
1.1172.2.5  raeburn  1384:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1385:             $is_balancer = 0;
                   1386:             if ($uname ne '' && $udom ne '') {
                   1387:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1388: 
                   1389:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1390:                              'user.loadbalcheck.time' => time});
                   1391:                 }
1.1129    raeburn  1392:             }
                   1393:         }
                   1394:     }
                   1395:     return ($is_balancer,$otherserver);
                   1396: }
                   1397: 
1.1172.2.12  raeburn  1398: sub check_balancer_result {
                   1399:     my ($result,@hosts) = @_;
                   1400:     my ($is_balancer,$currtargets,$currrules);
                   1401:     if (ref($result) eq 'HASH') {
                   1402:         if ($result->{'lonhost'} ne '') {
                   1403:             my $currbalancer = $result->{'lonhost'};
                   1404:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1405:                 $is_balancer = 1;
                   1406:                 $currtargets = $result->{'targets'};
                   1407:                 $currrules = $result->{'rules'};
                   1408:             }
                   1409:         } else {
                   1410:             foreach my $key (keys(%{$result})) {
                   1411:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1412:                     (ref($result->{$key}) eq 'HASH')) {
                   1413:                     $is_balancer = 1;
                   1414:                     $currrules = $result->{$key}{'rules'};
                   1415:                     $currtargets = $result->{$key}{'targets'};
                   1416:                     last;
                   1417:                 }
                   1418:             }
                   1419:         }
                   1420:     }
                   1421:     return ($is_balancer,$currtargets,$currrules);
                   1422: }
                   1423: 
1.1129    raeburn  1424: sub get_loadbalancer_targets {
                   1425:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1426:     my $offloadto;
1.1172.2.4  raeburn  1427:     if ($rule_in_effect eq 'none') {
                   1428:         return [$perlvar{'lonHostID'}];
                   1429:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1430:         $offloadto = $currtargets;
                   1431:     } else {
                   1432:         if ($rule_in_effect eq 'homeserver') {
                   1433:             my $homeserver = &homeserver($uname,$udom);
                   1434:             if ($homeserver ne 'no_host') {
                   1435:                 $offloadto = [$homeserver];
                   1436:             }
                   1437:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1438:             my %domconfig =
                   1439:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1440:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1441:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1442:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1443:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1444:                     }
                   1445:                 }
                   1446:             } else {
1.1172.2.7  raeburn  1447:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1448:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1449:                 if (&hostname($remotebalancer) ne '') {
                   1450:                     $offloadto = [$remotebalancer];
                   1451:                 }
                   1452:             }
                   1453:         } elsif (&hostname($rule_in_effect) ne '') {
                   1454:             $offloadto = [$rule_in_effect];
                   1455:         }
                   1456:     }
                   1457:     return $offloadto;
                   1458: }
                   1459: 
1.1127    raeburn  1460: sub internet_dom_servers {
                   1461:     my ($dom) = @_;
                   1462:     my (%uniqservers,%servers);
                   1463:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1464:     my @machinedoms = &machine_domains($primaryserver);
                   1465:     foreach my $mdom (@machinedoms) {
                   1466:         my %currservers = %servers;
                   1467:         my %server = &get_servers($mdom);
                   1468:         %servers = (%currservers,%server);
                   1469:     }
                   1470:     my %by_hostname;
                   1471:     foreach my $id (keys(%servers)) {
                   1472:         push(@{$by_hostname{$servers{$id}}},$id);
                   1473:     }
                   1474:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1475:         if (@{$by_hostname{$hostname}} > 1) {
                   1476:             my $match = 0;
                   1477:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1478:                 if (&host_domain($id) eq $dom) {
                   1479:                     $uniqservers{$id} = $hostname;
                   1480:                     $match = 1;
                   1481:                 }
                   1482:             }
                   1483:             unless ($match) {
                   1484:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1485:             }
                   1486:         } else {
                   1487:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1488:         }
                   1489:     }
                   1490:     return %uniqservers;
                   1491: }
                   1492: 
1.1       albertel 1493: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1494: 
1.599     albertel 1495: my %homecache;
1.1       albertel 1496: sub homeserver {
1.230     stredwic 1497:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1498:     my $index="$uname:$udom";
1.426     albertel 1499: 
1.599     albertel 1500:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1501: 
                   1502:     my %servers = &get_servers($udom,'library');
                   1503:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1504:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1505: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1506: 
                   1507: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1508: 	if ($answer eq 'found') {
                   1509: 	    delete($badServerCache{$tryserver}); 
                   1510: 	    return $homecache{$index}=$tryserver;
                   1511: 	} elsif ($answer eq 'no_host') {
                   1512: 	    $badServerCache{$tryserver}=1;
                   1513: 	}
1.1       albertel 1514:     }    
                   1515:     return 'no_host';
1.70      www      1516: }
                   1517: 
                   1518: # ------------------------------------- Find the usernames behind a list of IDs
                   1519: 
                   1520: sub idget {
                   1521:     my ($udom,@ids)=@_;
                   1522:     my %returnhash=();
                   1523:     
1.841     albertel 1524:     my %servers = &get_servers($udom,'library');
                   1525:     foreach my $tryserver (keys(%servers)) {
                   1526: 	my $idlist=join('&',@ids);
                   1527: 	$idlist=~tr/A-Z/a-z/; 
                   1528: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1529: 	my @answer=();
                   1530: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1531: 	    @answer=split(/\&/,$reply);
                   1532: 	}                    ;
                   1533: 	my $i;
                   1534: 	for ($i=0;$i<=$#ids;$i++) {
                   1535: 	    if ($answer[$i]) {
                   1536: 		$returnhash{$ids[$i]}=$answer[$i];
                   1537: 	    } 
                   1538: 	}
                   1539:     } 
1.70      www      1540:     return %returnhash;
                   1541: }
                   1542: 
                   1543: # ------------------------------------- Find the IDs behind a list of usernames
                   1544: 
                   1545: sub idrget {
                   1546:     my ($udom,@unames)=@_;
                   1547:     my %returnhash=();
1.800     albertel 1548:     foreach my $uname (@unames) {
                   1549:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1550:     }
1.70      www      1551:     return %returnhash;
                   1552: }
                   1553: 
                   1554: # ------------------------------- Store away a list of names and associated IDs
                   1555: 
                   1556: sub idput {
                   1557:     my ($udom,%ids)=@_;
                   1558:     my %servers=();
1.800     albertel 1559:     foreach my $uname (keys(%ids)) {
                   1560: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1561:         my $uhom=&homeserver($uname,$udom);
1.70      www      1562:         if ($uhom ne 'no_host') {
1.800     albertel 1563:             my $id=&escape($ids{$uname});
1.70      www      1564:             $id=~tr/A-Z/a-z/;
1.800     albertel 1565:             my $esc_unam=&escape($uname);
1.70      www      1566: 	    if ($servers{$uhom}) {
1.800     albertel 1567: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1568:             } else {
1.800     albertel 1569:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1570:             }
                   1571:         }
1.191     harris41 1572:     }
1.800     albertel 1573:     foreach my $server (keys(%servers)) {
                   1574:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1575:     }
1.344     www      1576: }
                   1577: 
1.1023    raeburn  1578: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1579: sub dump_dom {
1.1165    droeschl 1580:     my ($namespace, $udom, $regexp) = @_;
                   1581: 
                   1582:     $udom ||= $env{'user.domain'};
                   1583: 
                   1584:     return () unless $udom;
                   1585: 
                   1586:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1587: }
                   1588: 
1.1023    raeburn  1589: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1590: 
                   1591: sub get_dom {
1.860     raeburn  1592:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1593:     my $items='';
                   1594:     foreach my $item (@$storearr) {
                   1595:         $items.=&escape($item).'&';
                   1596:     }
                   1597:     $items=~s/\&$//;
1.860     raeburn  1598:     if (!$udom) {
                   1599:         $udom=$env{'user.domain'};
                   1600:         if (defined(&domain($udom,'primary'))) {
                   1601:             $uhome=&domain($udom,'primary');
                   1602:         } else {
1.874     albertel 1603:             undef($uhome);
1.860     raeburn  1604:         }
                   1605:     } else {
                   1606:         if (!$uhome) {
                   1607:             if (defined(&domain($udom,'primary'))) {
                   1608:                 $uhome=&domain($udom,'primary');
                   1609:             }
                   1610:         }
                   1611:     }
                   1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1613:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1614:         my %returnhash;
1.875     albertel 1615:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1616:             return %returnhash;
                   1617:         }
1.806     raeburn  1618:         my @pairs=split(/\&/,$rep);
                   1619:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1620:             return @pairs;
                   1621:         }
                   1622:         my $i=0;
                   1623:         foreach my $item (@$storearr) {
                   1624:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1625:             $i++;
                   1626:         }
                   1627:         return %returnhash;
                   1628:     } else {
1.880     banghart 1629:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1630:     }
                   1631: }
                   1632: 
                   1633: # -------------------------------------------- put items in domain db files 
                   1634: 
                   1635: sub put_dom {
1.860     raeburn  1636:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1637:     if (!$udom) {
                   1638:         $udom=$env{'user.domain'};
                   1639:         if (defined(&domain($udom,'primary'))) {
                   1640:             $uhome=&domain($udom,'primary');
                   1641:         } else {
1.874     albertel 1642:             undef($uhome);
1.860     raeburn  1643:         }
                   1644:     } else {
                   1645:         if (!$uhome) {
                   1646:             if (defined(&domain($udom,'primary'))) {
                   1647:                 $uhome=&domain($udom,'primary');
                   1648:             }
                   1649:         }
                   1650:     } 
                   1651:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1652:         my $items='';
                   1653:         foreach my $item (keys(%$storehash)) {
                   1654:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1655:         }
                   1656:         $items=~s/\&$//;
                   1657:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1658:     } else {
1.860     raeburn  1659:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1660:     }
                   1661: }
                   1662: 
1.1023    raeburn  1663: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1664: sub newput_dom {
1.1023    raeburn  1665:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1666:     my $result;
                   1667:     if (!$udom) {
                   1668:         $udom=$env{'user.domain'};
                   1669:     }
1.1023    raeburn  1670:     if ($udom) {
                   1671:         my $uname = &get_domainconfiguser($udom);
                   1672:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1673:     }
                   1674:     return $result;
                   1675: }
                   1676: 
1.1023    raeburn  1677: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1678: sub del_dom {
1.1023    raeburn  1679:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1680:     if (ref($storearr) eq 'ARRAY') {
                   1681:         if (!$udom) {
                   1682:             $udom=$env{'user.domain'};
                   1683:         }
1.1023    raeburn  1684:         if ($udom) {
                   1685:             my $uname = &get_domainconfiguser($udom); 
                   1686:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1687:         }
                   1688:     }
                   1689: }
                   1690: 
1.1023    raeburn  1691: # ----------------------------------construct domainconfig user for a domain 
                   1692: sub get_domainconfiguser {
                   1693:     my ($udom) = @_;
                   1694:     return $udom.'-domainconfig';
                   1695: }
                   1696: 
1.837     raeburn  1697: sub retrieve_inst_usertypes {
                   1698:     my ($udom) = @_;
                   1699:     my (%returnhash,@order);
1.989     raeburn  1700:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1701:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1702:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1703:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1704:         @order = @{$domdefs{'inststatusorder'}};
                   1705:     } else {
                   1706:         if (defined(&domain($udom,'primary'))) {
                   1707:             my $uhome=&domain($udom,'primary');
                   1708:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1709:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1710:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1711:                 return (\%returnhash,\@order);
                   1712:             }
                   1713:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1714:             my @pairs=split(/\&/,$hashitems);
                   1715:             foreach my $item (@pairs) {
                   1716:                 my ($key,$value)=split(/=/,$item,2);
                   1717:                 $key = &unescape($key);
                   1718:                 next if ($key =~ /^error: 2 /);
                   1719:                 $returnhash{$key}=&thaw_unescape($value);
                   1720:             }
                   1721:             my @esc_order = split(/\&/,$orderitems);
                   1722:             foreach my $item (@esc_order) {
                   1723:                 push(@order,&unescape($item));
                   1724:             }
                   1725:         } else {
                   1726:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1727:         }
                   1728:     }
                   1729:     return (\%returnhash,\@order);
                   1730: }
                   1731: 
1.868     raeburn  1732: sub is_domainimage {
                   1733:     my ($url) = @_;
                   1734:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1735:         if (&domain($1) ne '') {
                   1736:             return '1';
                   1737:         }
                   1738:     }
                   1739:     return;
                   1740: }
                   1741: 
1.899     raeburn  1742: sub inst_directory_query {
                   1743:     my ($srch) = @_;
                   1744:     my $udom = $srch->{'srchdomain'};
                   1745:     my %results;
                   1746:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1747:     my $outcome;
1.899     raeburn  1748:     if ($homeserver ne '') {
1.904     albertel 1749: 	my $queryid=&reply("querysend:instdirsearch:".
                   1750: 			   &escape($srch->{'srchby'}).':'.
                   1751: 			   &escape($srch->{'srchterm'}).':'.
                   1752: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1753: 	my $host=&hostname($homeserver);
                   1754: 	if ($queryid !~/^\Q$host\E\_/) {
                   1755: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1756: 	    return;
                   1757: 	}
                   1758: 	my $response = &get_query_reply($queryid);
                   1759: 	my $maxtries = 5;
                   1760: 	my $tries = 1;
                   1761: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1762: 	    $response = &get_query_reply($queryid);
                   1763: 	    $tries ++;
                   1764: 	}
                   1765: 
                   1766:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1767:             if ($response eq 'unavailable') {
                   1768:                 $outcome = $response;
                   1769:             } else {
                   1770:                 $outcome = 'ok';
                   1771:                 my @matches = split(/\n/,$response);
                   1772:                 foreach my $match (@matches) {
                   1773:                     my ($key,$value) = split(/=/,$match);
                   1774:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1775:                 }
1.899     raeburn  1776:             }
                   1777:         }
                   1778:     }
1.909     raeburn  1779:     return ($outcome,%results);
1.899     raeburn  1780: }
                   1781: 
                   1782: sub usersearch {
                   1783:     my ($srch) = @_;
                   1784:     my $dom = $srch->{'srchdomain'};
                   1785:     my %results;
                   1786:     my %libserv = &all_library();
                   1787:     my $query = 'usersearch';
                   1788:     foreach my $tryserver (keys(%libserv)) {
                   1789:         if (&host_domain($tryserver) eq $dom) {
                   1790:             my $host=&hostname($tryserver);
                   1791:             my $queryid=
1.911     raeburn  1792:                 &reply("querysend:".&escape($query).':'.
                   1793:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1794:                        &escape($srch->{'srchtype'}).':'.
                   1795:                        &escape($srch->{'srchterm'}),$tryserver);
                   1796:             if ($queryid !~/^\Q$host\E\_/) {
                   1797:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1798:                 next;
1.899     raeburn  1799:             }
                   1800:             my $reply = &get_query_reply($queryid);
                   1801:             my $maxtries = 1;
                   1802:             my $tries = 1;
                   1803:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1804:                 $reply = &get_query_reply($queryid);
                   1805:                 $tries ++;
                   1806:             }
                   1807:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1808:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1809:             } else {
1.911     raeburn  1810:                 my @matches;
                   1811:                 if ($reply =~ /\n/) {
                   1812:                     @matches = split(/\n/,$reply);
                   1813:                 } else {
                   1814:                     @matches = split(/\&/,$reply);
                   1815:                 }
1.899     raeburn  1816:                 foreach my $match (@matches) {
                   1817:                     my ($uname,$udom,%userhash);
1.911     raeburn  1818:                     foreach my $entry (split(/:/,$match)) {
                   1819:                         my ($key,$value) =
                   1820:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1821:                         $userhash{$key} = $value;
                   1822:                         if ($key eq 'username') {
                   1823:                             $uname = $value;
                   1824:                         } elsif ($key eq 'domain') {
                   1825:                             $udom = $value;
1.911     raeburn  1826:                         }
1.899     raeburn  1827:                     }
                   1828:                     $results{$uname.':'.$udom} = \%userhash;
                   1829:                 }
                   1830:             }
                   1831:         }
                   1832:     }
                   1833:     return %results;
                   1834: }
                   1835: 
1.912     raeburn  1836: sub get_instuser {
                   1837:     my ($udom,$uname,$id) = @_;
                   1838:     my $homeserver = &domain($udom,'primary');
                   1839:     my ($outcome,%results);
                   1840:     if ($homeserver ne '') {
                   1841:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1842:                            &escape($id).':'.&escape($udom),$homeserver);
                   1843:         my $host=&hostname($homeserver);
                   1844:         if ($queryid !~/^\Q$host\E\_/) {
                   1845:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1846:             return;
                   1847:         }
                   1848:         my $response = &get_query_reply($queryid);
                   1849:         my $maxtries = 5;
                   1850:         my $tries = 1;
                   1851:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1852:             $response = &get_query_reply($queryid);
                   1853:             $tries ++;
                   1854:         }
                   1855:         if (!&error($response) && $response ne 'refused') {
                   1856:             if ($response eq 'unavailable') {
                   1857:                 $outcome = $response;
                   1858:             } else {
                   1859:                 $outcome = 'ok';
                   1860:                 my @matches = split(/\n/,$response);
                   1861:                 foreach my $match (@matches) {
                   1862:                     my ($key,$value) = split(/=/,$match);
                   1863:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1864:                 }
                   1865:             }
                   1866:         }
                   1867:     }
                   1868:     my %userinfo;
                   1869:     if (ref($results{$uname}) eq 'HASH') {
                   1870:         %userinfo = %{$results{$uname}};
                   1871:     } 
                   1872:     return ($outcome,%userinfo);
                   1873: }
                   1874: 
                   1875: sub inst_rulecheck {
1.923     raeburn  1876:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1877:     my %returnhash;
                   1878:     if ($udom ne '') {
                   1879:         if (ref($rules) eq 'ARRAY') {
                   1880:             @{$rules} = map {&escape($_);} (@{$rules});
                   1881:             my $rulestr = join(':',@{$rules});
                   1882:             my $homeserver=&domain($udom,'primary');
                   1883:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1884:                 my $response;
                   1885:                 if ($item eq 'username') {                
                   1886:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1887:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1888:                                               $homeserver));
1.923     raeburn  1889:                 } elsif ($item eq 'id') {
                   1890:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1891:                                               ':'.&escape($id).':'.$rulestr,
                   1892:                                               $homeserver));
1.945     raeburn  1893:                 } elsif ($item eq 'selfcreate') {
                   1894:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1895:                                                &escape($udom).':'.&escape($uname).
                   1896:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1897:                 }
1.912     raeburn  1898:                 if ($response ne 'refused') {
                   1899:                     my @pairs=split(/\&/,$response);
                   1900:                     foreach my $item (@pairs) {
                   1901:                         my ($key,$value)=split(/=/,$item,2);
                   1902:                         $key = &unescape($key);
                   1903:                         next if ($key =~ /^error: 2 /);
                   1904:                         $returnhash{$key}=&thaw_unescape($value);
                   1905:                     }
                   1906:                 }
                   1907:             }
                   1908:         }
                   1909:     }
                   1910:     return %returnhash;
                   1911: }
                   1912: 
                   1913: sub inst_userrules {
1.923     raeburn  1914:     my ($udom,$check) = @_;
1.912     raeburn  1915:     my (%ruleshash,@ruleorder);
                   1916:     if ($udom ne '') {
                   1917:         my $homeserver=&domain($udom,'primary');
                   1918:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1919:             my $response;
                   1920:             if ($check eq 'id') {
                   1921:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1922:                                  $homeserver);
1.943     raeburn  1923:             } elsif ($check eq 'email') {
                   1924:                 $response=&reply('instemailrules:'.&escape($udom),
                   1925:                                  $homeserver);
1.923     raeburn  1926:             } else {
                   1927:                 $response=&reply('instuserrules:'.&escape($udom),
                   1928:                                  $homeserver);
                   1929:             }
1.912     raeburn  1930:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1931:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1932:                 ($response ne 'no_such_host')) {
                   1933:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1934:                 my @pairs=split(/\&/,$hashitems);
                   1935:                 foreach my $item (@pairs) {
                   1936:                     my ($key,$value)=split(/=/,$item,2);
                   1937:                     $key = &unescape($key);
                   1938:                     next if ($key =~ /^error: 2 /);
                   1939:                     $ruleshash{$key}=&thaw_unescape($value);
                   1940:                 }
                   1941:                 my @esc_order = split(/\&/,$orderitems);
                   1942:                 foreach my $item (@esc_order) {
                   1943:                     push(@ruleorder,&unescape($item));
                   1944:                 }
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return (\%ruleshash,\@ruleorder);
                   1949: }
                   1950: 
1.976     raeburn  1951: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1952: 
                   1953: sub get_domain_defaults {
                   1954:     my ($domain) = @_;
                   1955:     my $cachetime = 60*60*24;
                   1956:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1957:     if (defined($cached)) {
                   1958:         if (ref($result) eq 'HASH') {
                   1959:             return %{$result};
                   1960:         }
                   1961:     }
                   1962:     my %domdefaults;
                   1963:     my %domconfig =
1.989     raeburn  1964:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1965:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1966:                                   'coursedefaults','usersessions',
                   1967:                                   'requestauthor'],$domain);
1.943     raeburn  1968:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1969:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1970:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1971:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1972:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1973:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1974:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1975:     } else {
                   1976:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1977:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1978:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1979:     }
1.976     raeburn  1980:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1981:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1982:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1983:         } else {
                   1984:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1985:         } 
1.1172.2.6  raeburn  1986:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1987:         foreach my $item (@usertools) {
                   1988:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1989:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1990:             }
                   1991:         }
                   1992:     }
1.985     raeburn  1993:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1994:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1995:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1996:         }
                   1997:     }
1.1172.2.9  raeburn  1998:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   1999:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2000:     }
1.989     raeburn  2001:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2002:         foreach my $item ('inststatustypes','inststatusorder') {
                   2003:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2004:         }
                   2005:     }
1.1047    raeburn  2006:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2007:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2008:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2009:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2010:         }
                   2011:     }
1.1073    raeburn  2012:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2013:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2014:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2015:         }
                   2016:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2017:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2018:         }
                   2019:     }
1.943     raeburn  2020:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2021:                                   $cachetime);
                   2022:     return %domdefaults;
                   2023: }
                   2024: 
1.344     www      2025: # --------------------------------------------------- Assign a key to a student
                   2026: 
                   2027: sub assign_access_key {
1.364     www      2028: #
                   2029: # a valid key looks like uname:udom#comments
                   2030: # comments are being appended
                   2031: #
1.498     www      2032:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2033:     $kdom=
1.620     albertel 2034:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2035:     $knum=
1.620     albertel 2036:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2037:     $cdom=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2039:     $cnum=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2041:     $udom=$env{'user.name'} unless (defined($udom));
                   2042:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2043:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2044:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2045:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2046:                                                   # assigned to this person
                   2047:                                                   # - this should not happen,
1.345     www      2048:                                                   # unless something went wrong
                   2049:                                                   # the first time around
                   2050: # ready to assign
1.364     www      2051:         $logentry=$1.'; '.$logentry;
1.496     www      2052:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2053:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2054: # key now belongs to user
1.346     www      2055: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2056:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2057:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2058:                 return 'ok';
                   2059:             } else {
                   2060:                 return 
                   2061:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2062: 	    }
                   2063:         } else {
                   2064:             return 'error: Could not assign key, try again later.';
                   2065:         }
1.364     www      2066:     } elsif (!$existing{$ckey}) {
1.345     www      2067: # the key does not exist
                   2068: 	return 'error: The key does not exist';
                   2069:     } else {
                   2070: # the key is somebody else's
                   2071: 	return 'error: The key is already in use';
                   2072:     }
1.344     www      2073: }
                   2074: 
1.364     www      2075: # ------------------------------------------ put an additional comment on a key
                   2076: 
                   2077: sub comment_access_key {
                   2078: #
                   2079: # a valid key looks like uname:udom#comments
                   2080: # comments are being appended
                   2081: #
                   2082:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2083:     $cdom=
1.620     albertel 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2085:     $cnum=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2087:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2088:     if ($existing{$ckey}) {
                   2089:         $existing{$ckey}.='; '.$logentry;
                   2090: # ready to assign
1.367     www      2091:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2092:                                                  $cdom,$cnum) eq 'ok') {
                   2093: 	    return 'ok';
                   2094:         } else {
                   2095: 	    return 'error: Count not store comment.';
                   2096:         }
                   2097:     } else {
                   2098: # the key does not exist
                   2099: 	return 'error: The key does not exist';
                   2100:     }
                   2101: }
                   2102: 
1.344     www      2103: # ------------------------------------------------------ Generate a set of keys
                   2104: 
                   2105: sub generate_access_keys {
1.364     www      2106:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2107:     $cdom=
1.620     albertel 2108:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2109:     $cnum=
1.620     albertel 2110:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2111:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2112:     unless (($cdom) && ($cnum)) { return 0; }
                   2113:     if ($number>10000) { return 0; }
                   2114:     sleep(2); # make sure don't get same seed twice
                   2115:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2116:     my $total=0;
                   2117:     for (my $i=1;$i<=$number;$i++) {
                   2118:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2119:                   sprintf("%lx",int(100000*rand)).'-'.
                   2120:                   sprintf("%lx",int(100000*rand));
                   2121:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2122:        $newkey=~s/0/h/g; # and also 0 and O
                   2123:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2124:        if ($existing{$newkey}) {
                   2125:            $i--;
                   2126:        } else {
1.364     www      2127: 	  if (&put('accesskeys',
                   2128:               { $newkey => '# generated '.localtime().
1.620     albertel 2129:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2130:                            '; '.$logentry },
                   2131: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2132:               $total++;
                   2133: 	  }
                   2134:        }
                   2135:     }
1.620     albertel 2136:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2137:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2138:     return $total;
                   2139: }
                   2140: 
                   2141: # ------------------------------------------------------- Validate an accesskey
                   2142: 
                   2143: sub validate_access_key {
                   2144:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2145:     $cdom=
1.620     albertel 2146:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2147:     $cnum=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2149:     $udom=$env{'user.domain'} unless (defined($udom));
                   2150:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2151:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2152:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2153: }
                   2154: 
                   2155: # ------------------------------------- Find the section of student in a course
1.652     albertel 2156: sub devalidate_getsection_cache {
                   2157:     my ($udom,$unam,$courseid)=@_;
                   2158:     my $hashid="$udom:$unam:$courseid";
                   2159:     &devalidate_cache_new('getsection',$hashid);
                   2160: }
1.298     matthew  2161: 
1.815     albertel 2162: sub courseid_to_courseurl {
                   2163:     my ($courseid) = @_;
                   2164:     #already url style courseid
                   2165:     return $courseid if ($courseid =~ m{^/});
                   2166: 
                   2167:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2168: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2169: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2170: 	return "/$cdom/$cnum";
                   2171:     }
                   2172: 
                   2173:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2174:     if (exists($courseinfo{'num'})) {
                   2175: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2176:     }
                   2177: 
                   2178:     return undef;
                   2179: }
                   2180: 
1.298     matthew  2181: sub getsection {
                   2182:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2183:     my $cachetime=1800;
1.551     albertel 2184: 
                   2185:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2186:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2187:     if (defined($cached)) { return $result; }
                   2188: 
1.298     matthew  2189:     my %Pending; 
                   2190:     my %Expired;
                   2191:     #
                   2192:     # Each role can either have not started yet (pending), be active, 
                   2193:     #    or have expired.
                   2194:     #
                   2195:     # If there is an active role, we are done.
                   2196:     #
                   2197:     # If there is more than one role which has not started yet, 
                   2198:     #     choose the one which will start sooner
                   2199:     # If there is one role which has not started yet, return it.
                   2200:     #
                   2201:     # If there is more than one expired role, choose the one which ended last.
                   2202:     # If there is a role which has expired, return it.
                   2203:     #
1.815     albertel 2204:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2205:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2206:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2207:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2208:         my $section=$1;
                   2209:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2210:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2211:         my $now=time;
1.548     albertel 2212:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2213:             $Expired{$end}=$section;
                   2214:             next;
                   2215:         }
1.548     albertel 2216:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2217:             $Pending{$start}=$section;
                   2218:             next;
                   2219:         }
1.599     albertel 2220:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2221:     }
                   2222:     #
                   2223:     # Presumedly there will be few matching roles from the above
                   2224:     # loop and the sorting time will be negligible.
                   2225:     if (scalar(keys(%Pending))) {
                   2226:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2228:     } 
                   2229:     if (scalar(keys(%Expired))) {
                   2230:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2231:         my $time = pop(@sorted);
1.599     albertel 2232:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2233:     }
1.599     albertel 2234:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2235: }
1.70      www      2236: 
1.599     albertel 2237: sub save_cache {
                   2238:     &purge_remembered();
1.722     albertel 2239:     #&Apache::loncommon::validate_page();
1.620     albertel 2240:     undef(%env);
1.780     albertel 2241:     undef($env_loaded);
1.599     albertel 2242: }
1.452     albertel 2243: 
1.599     albertel 2244: my $to_remember=-1;
                   2245: my %remembered;
                   2246: my %accessed;
                   2247: my $kicks=0;
                   2248: my $hits=0;
1.849     albertel 2249: sub make_key {
                   2250:     my ($name,$id) = @_;
1.872     albertel 2251:     if (length($id) > 65 
                   2252: 	&& length(&escape($id)) > 200) {
                   2253: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2254:     }
1.849     albertel 2255:     return &escape($name.':'.$id);
                   2256: }
                   2257: 
1.599     albertel 2258: sub devalidate_cache_new {
                   2259:     my ($name,$id,$debug) = @_;
                   2260:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2261:     $id=&make_key($name,$id);
1.599     albertel 2262:     $memcache->delete($id);
                   2263:     delete($remembered{$id});
                   2264:     delete($accessed{$id});
                   2265: }
                   2266: 
                   2267: sub is_cached_new {
                   2268:     my ($name,$id,$debug) = @_;
1.849     albertel 2269:     $id=&make_key($name,$id);
1.599     albertel 2270:     if (exists($remembered{$id})) {
1.1133    foxr     2271: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2272: 	$accessed{$id}=[&gettimeofday()];
                   2273: 	$hits++;
                   2274: 	return ($remembered{$id},1);
                   2275:     }
                   2276:     my $value = $memcache->get($id);
                   2277:     if (!(defined($value))) {
                   2278: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2279: 	return (undef,undef);
1.416     albertel 2280:     }
1.599     albertel 2281:     if ($value eq '__undef__') {
                   2282: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2283: 	$value=undef;
                   2284:     }
                   2285:     &make_room($id,$value,$debug);
                   2286:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2287:     return ($value,1);
                   2288: }
                   2289: 
                   2290: sub do_cache_new {
                   2291:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2292:     $id=&make_key($name,$id);
1.599     albertel 2293:     my $setvalue=$value;
                   2294:     if (!defined($setvalue)) {
                   2295: 	$setvalue='__undef__';
                   2296:     }
1.623     albertel 2297:     if (!defined($time) ) {
                   2298: 	$time=600;
                   2299:     }
1.599     albertel 2300:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2301:     my $result = $memcache->set($id,$setvalue,$time);
                   2302:     if (! $result) {
1.872     albertel 2303: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2304: 	$memcache->disconnect_all();
1.872     albertel 2305:     }
1.600     albertel 2306:     # need to make a copy of $value
1.919     albertel 2307:     &make_room($id,$value,$debug);
1.599     albertel 2308:     return $value;
                   2309: }
                   2310: 
                   2311: sub make_room {
                   2312:     my ($id,$value,$debug)=@_;
1.919     albertel 2313: 
                   2314:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2315:                                     : $value;
1.599     albertel 2316:     if ($to_remember<0) { return; }
                   2317:     $accessed{$id}=[&gettimeofday()];
                   2318:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2319:     my $to_kick;
                   2320:     my $max_time=0;
                   2321:     foreach my $other (keys(%accessed)) {
                   2322: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2323: 	    $to_kick=$other;
                   2324: 	    $max_time=&tv_interval($accessed{$other});
                   2325: 	}
                   2326:     }
                   2327:     delete($remembered{$to_kick});
                   2328:     delete($accessed{$to_kick});
                   2329:     $kicks++;
                   2330:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2331:     return;
                   2332: }
                   2333: 
1.599     albertel 2334: sub purge_remembered {
1.604     albertel 2335:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2336:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2337:     undef(%remembered);
                   2338:     undef(%accessed);
1.428     albertel 2339: }
1.70      www      2340: # ------------------------------------- Read an entry from a user's environment
                   2341: 
                   2342: sub userenvironment {
                   2343:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2344:     my $items;
                   2345:     foreach my $item (@what) {
                   2346:         $items.=&escape($item).'&';
                   2347:     }
                   2348:     $items=~s/\&$//;
1.70      www      2349:     my %returnhash=();
1.1009    raeburn  2350:     my $uhome = &homeserver($unam,$udom);
                   2351:     unless ($uhome eq 'no_host') {
                   2352:         my @answer=split(/\&/, 
                   2353:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2354:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2355:             return %returnhash;
                   2356:         }
1.1009    raeburn  2357:         my $i;
                   2358:         for ($i=0;$i<=$#what;$i++) {
                   2359: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2360:         }
1.70      www      2361:     }
                   2362:     return %returnhash;
1.1       albertel 2363: }
                   2364: 
1.617     albertel 2365: # ---------------------------------------------------------- Get a studentphoto
                   2366: sub studentphoto {
                   2367:     my ($udom,$unam,$ext) = @_;
                   2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2369:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2370:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2371:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2372:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2373:             } else {
                   2374:                 my ($result,$perm_reqd)=
1.707     albertel 2375: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2376:                 if ($result eq 'ok') {
                   2377:                     if (!($perm_reqd eq 'yes')) {
                   2378:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2379:                     }
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:     } else {
                   2384:         my ($result,$perm_reqd) = 
1.707     albertel 2385: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2386:         if ($result eq 'ok') {
                   2387:             if (!($perm_reqd eq 'yes')) {
                   2388:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2389:             }
                   2390:         }
                   2391:     }
                   2392:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2393: }
                   2394: 
                   2395: sub retrievestudentphoto {
                   2396:     my ($udom,$unam,$ext,$type) = @_;
                   2397:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2398:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2399:     if ($ret eq 'ok') {
                   2400:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2401:         if ($type eq 'thumbnail') {
                   2402:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2403:         }
                   2404:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2405:         return $tokenurl;
                   2406:     } else {
                   2407:         if ($type eq 'thumbnail') {
                   2408:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2409:         } else { 
                   2410:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2411:         }
1.617     albertel 2412:     }
                   2413: }
                   2414: 
1.263     www      2415: # -------------------------------------------------------------------- New chat
                   2416: 
                   2417: sub chatsend {
1.724     raeburn  2418:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2419:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2421:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2422:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2423: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2424: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2425: }
                   2426: 
                   2427: # ------------------------------------------ Find current version of a resource
                   2428: 
                   2429: sub getversion {
                   2430:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2431:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2432:     return &currentversion(&filelocation('',$fname));
                   2433: }
                   2434: 
                   2435: sub currentversion {
                   2436:     my $fname=shift;
                   2437:     my $author=$fname;
                   2438:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2439:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2440:     my $home=&homeserver($uname,$udom);
1.292     www      2441:     if ($home eq 'no_host') { 
                   2442:         return -1; 
                   2443:     }
1.1112    www      2444:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2445:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2446: 	return -1;
                   2447:     }
1.1112    www      2448:     return $answer;
1.263     www      2449: }
                   2450: 
1.1111    www      2451: #
                   2452: # Return special version number of resource if set by override, empty otherwise
                   2453: #
                   2454: sub usedversion {
                   2455:     my $fname=shift;
                   2456:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2457:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2458:     if ($urlversion) { return $urlversion; }
                   2459:     return '';
                   2460: }
                   2461: 
1.1       albertel 2462: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2463: 
1.1       albertel 2464: sub subscribe {
                   2465:     my $fname=shift;
1.761     raeburn  2466:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2467:     $fname=~s/[\n\r]//g;
1.1       albertel 2468:     my $author=$fname;
                   2469:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2470:     my ($udom,$uname)=split(/\//,$author);
                   2471:     my $home=homeserver($uname,$udom);
1.335     albertel 2472:     if ($home eq 'no_host') {
                   2473:         return 'not_found';
1.1       albertel 2474:     }
                   2475:     my $answer=reply("sub:$fname",$home);
1.64      www      2476:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2477: 	$answer.=' by '.$home;
                   2478:     }
1.1       albertel 2479:     return $answer;
                   2480: }
                   2481:     
1.8       www      2482: # -------------------------------------------------------------- Replicate file
                   2483: 
                   2484: sub repcopy {
                   2485:     my $filename=shift;
1.23      www      2486:     $filename=~s/\/+/\//g;
1.1142    raeburn  2487:     my $londocroot = $perlvar{'lonDocRoot'};
                   2488:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2489:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2490:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2491: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2492: 	return &repcopy_userfile($filename);
                   2493:     }
1.532     albertel 2494:     $filename=~s/[\n\r]//g;
1.8       www      2495:     my $transname="$filename.in.transfer";
1.828     www      2496: # FIXME: this should flock
1.607     raeburn  2497:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2498:     my $remoteurl=subscribe($filename);
1.64      www      2499:     if ($remoteurl =~ /^con_lost by/) {
                   2500: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2501:            return 'unavailable';
1.8       www      2502:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2503: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2504: 	   return 'not_found';
1.64      www      2505:     } elsif ($remoteurl =~ /^rejected by/) {
                   2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2507:            return 'forbidden';
1.20      www      2508:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2509:            return 'ok';
1.8       www      2510:     } else {
1.290     www      2511:         my $author=$filename;
                   2512:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:         my ($udom,$uname)=split(/\//,$author);
                   2514:         my $home=homeserver($uname,$udom);
                   2515:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2516:            my @parts=split(/\//,$filename);
                   2517:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2518:            if ($path ne "$londocroot/res") {
1.8       www      2519:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2520: 	       return 'bad_request';
1.8       www      2521:            }
                   2522:            my $count;
                   2523:            for ($count=5;$count<$#parts;$count++) {
                   2524:                $path.="/$parts[$count]";
                   2525:                if ((-e $path)!=1) {
                   2526: 		   mkdir($path,0777);
                   2527:                }
                   2528:            }
                   2529:            my $ua=new LWP::UserAgent;
                   2530:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2531:            my $response=$ua->request($request,$transname);
                   2532:            if ($response->is_error()) {
                   2533: 	       unlink($transname);
                   2534:                my $message=$response->status_line;
1.672     albertel 2535:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2536:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2537:                return 'unavailable';
1.8       www      2538:            } else {
1.16      www      2539: 	       if ($remoteurl!~/\.meta$/) {
                   2540:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2541:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2542:                   if ($mresponse->is_error()) {
                   2543: 		      unlink($filename.'.meta');
                   2544:                       &logthis(
1.672     albertel 2545:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2546:                   }
                   2547: 	       }
1.8       www      2548:                rename($transname,$filename);
1.607     raeburn  2549:                return 'ok';
1.8       www      2550:            }
1.290     www      2551:        }
1.8       www      2552:     }
1.330     www      2553: }
                   2554: 
                   2555: # ------------------------------------------------ Get server side include body
                   2556: sub ssi_body {
1.381     albertel 2557:     my ($filelink,%form)=@_;
1.606     matthew  2558:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2559:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2560:     }
1.953     www      2561:     my $output='';
                   2562:     my $response;
1.980     raeburn  2563:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2564:        ($output,$response)=&externalssi($filelink);
1.953     www      2565:     } else {
1.1004    droeschl 2566:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2567:        $filelink .= 'inhibitmenu=yes';
1.953     www      2568:        ($output,$response)=&ssi($filelink,%form);
                   2569:     }
1.778     albertel 2570:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2571:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2572:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2573:     if (wantarray) {
                   2574:         return ($output, $response);
                   2575:     } else {
                   2576:         return $output;
                   2577:     }
1.8       www      2578: }
                   2579: 
1.15      www      2580: # --------------------------------------------------------- Server Side Include
                   2581: 
1.782     albertel 2582: sub absolute_url {
                   2583:     my ($host_name) = @_;
                   2584:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2585:     if ($host_name eq '') {
                   2586: 	$host_name = $ENV{'SERVER_NAME'};
                   2587:     }
                   2588:     return $protocol.$host_name;
                   2589: }
                   2590: 
1.942     foxr     2591: #
                   2592: #   Server side include.
                   2593: # Parameters:
                   2594: #  fn     Possibly encrypted resource name/id.
                   2595: #  form   Hash that describes how the rendering should be done
                   2596: #         and other things.
1.944     foxr     2597: # Returns:
1.950     raeburn  2598: #   Scalar context: The content of the response.
                   2599: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2600: #     
1.15      www      2601: sub ssi {
                   2602: 
1.944     foxr     2603:     my ($fn,%form)=@_;
1.15      www      2604:     my $ua=new LWP::UserAgent;
1.23      www      2605:     my $request;
1.711     albertel 2606: 
                   2607:     $form{'no_update_last_known'}=1;
1.895     albertel 2608:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2609:     if (%form) {
1.782     albertel 2610:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2611:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2612:     } else {
1.782     albertel 2613:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2614:     }
                   2615: 
1.15      www      2616:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2617:     my $response= $ua->request($request);
1.944     foxr     2618:     if (wantarray) {
1.1172.2.3  raeburn  2619: 	return ($response->content, $response);
1.944     foxr     2620:     } else {
1.1172.2.3  raeburn  2621: 	return $response->content;
1.942     foxr     2622:     }
1.324     www      2623: }
                   2624: 
                   2625: sub externalssi {
                   2626:     my ($url)=@_;
                   2627:     my $ua=new LWP::UserAgent;
                   2628:     my $request=new HTTP::Request('GET',$url);
                   2629:     my $response=$ua->request($request);
1.954     raeburn  2630:     if (wantarray) {
                   2631:         return ($response->content, $response);
                   2632:     } else {
                   2633:         return $response->content;
                   2634:     }
1.15      www      2635: }
1.254     www      2636: 
1.492     albertel 2637: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2638: 
                   2639: sub allowuploaded {
                   2640:     my ($srcurl,$url)=@_;
                   2641:     $url=&clutter(&declutter($url));
                   2642:     my $dir=$url;
                   2643:     $dir=~s/\/[^\/]+$//;
                   2644:     my %httpref=();
                   2645:     my $httpurl=&hreflocation('',$url);
                   2646:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2647:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2648: }
1.477     raeburn  2649: 
1.1172.2.13  raeburn  2650: #
                   2651: # Determine if the current user should be able to edit a particular resource,
                   2652: # when viewing in course context.
                   2653: # (a) When viewing resource used to determine if "Edit" item is included in
                   2654: #     Functions.
                   2655: # (b) When displaying folder contents in course editor, used to determine if
                   2656: #     "Edit" link will be displayed alongside resource.
                   2657: #
                   2658: #  input: six args -- filename (decluttered), course number, course domain,
                   2659: #                   url, symb (if registered) and group (if this is a group
                   2660: #                   item -- e.g., bulletin board, group page etc.).
                   2661: #  output: array of five scalars --
                   2662: #          $cfile -- url for file editing if editable on current server
                   2663: #          $home -- homeserver of resource (i.e., for author if published,
                   2664: #                                           or course if uploaded.).
                   2665: #          $switchserver --  1 if server switch will be needed.
                   2666: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2667: #          $forceview -- 1 if icon/link should be to go to view mode
                   2668: #
                   2669: 
                   2670: sub can_edit_resource {
                   2671:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2672:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2673: #
                   2674: # For aboutme pages user can only edit his/her own.
                   2675: #
                   2676:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2677:         my ($sdom,$sname) = ($1,$2);
                   2678:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2679:             $home = $env{'user.home'};
                   2680:             $cfile = $resurl;
                   2681:             if ($env{'form.forceedit'}) {
                   2682:                 $forceview = 1;
                   2683:             } else {
                   2684:                 $forceedit = 1;
                   2685:             }
                   2686:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2687:         } else {
                   2688:             return;
                   2689:         }
                   2690:     }
                   2691: 
                   2692:     if ($env{'request.course.id'}) {
                   2693:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2694:         if ($group ne '') {
                   2695: # if this is a group homepage or group bulletin board, check group privs
                   2696:             my $allowed = 0;
                   2697:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2698:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2699:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2700:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2701:                     $allowed = 1;
                   2702:                 }
                   2703:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2704:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2705:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2706:                     $allowed = 1;
                   2707:                 }
                   2708:             }
                   2709:             if ($allowed) {
                   2710:                 $home=&homeserver($cnum,$cdom);
                   2711:                 if ($env{'form.forceedit'}) {
                   2712:                     $forceview = 1;
                   2713:                 } else {
                   2714:                     $forceedit = 1;
                   2715:                 }
                   2716:                 $cfile = $resurl;
                   2717:             } else {
                   2718:                 return;
                   2719:             }
                   2720:         } else {
1.1172.2.15  raeburn  2721:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2722:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2723:                     return;
                   2724:                 }
                   2725:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2726: #
                   2727: # No edit allowed where CC has switched to student role.
                   2728: #
                   2729:                 return;
                   2730:             }
                   2731:         }
                   2732:     }
                   2733: 
                   2734:     if ($file ne '') {
                   2735:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2736:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2737:                 $uploaded = 1;
                   2738:                 $incourse = 1;
                   2739:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2740:                     $cfile = &hreflocation('',$file);
                   2741:                     if ($env{'form.forceedit'}) {
                   2742:                         $forceview = 1;
                   2743:                     } else {
                   2744:                         $forceedit = 1;
                   2745:                     }
                   2746:                 }
                   2747:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2748:                 $incourse = 1;
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2756:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2757:                     $incourse = 1;
                   2758:                     if ($env{'form.forceedit'}) {
                   2759:                         $forceview = 1;
                   2760:                     } else {
                   2761:                         $forceedit = 1;
                   2762:                     }
                   2763:                     $cfile = $resurl;
                   2764:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2765:                     $incourse = 1;
                   2766:                     $cfile = $resurl.'/smpedit';
                   2767:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2768:                     $incourse = 1;
                   2769:                     if ($env{'form.forceedit'}) {
                   2770:                         $forceview = 1;
                   2771:                     } else {
                   2772:                         $forceedit = 1;
                   2773:                     }
                   2774:                     $cfile = $resurl;
1.1172.2.15  raeburn  2775:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2776:                     $incourse = 1;
                   2777:                     if ($env{'form.forceedit'}) {
                   2778:                         $forceview = 1;
                   2779:                     } else {
                   2780:                         $forceedit = 1;
                   2781:                     }
                   2782:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2783:                 }
                   2784:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2785:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2786:                 if (&is_on_map($template)) {
                   2787:                     $incourse = 1;
                   2788:                     $forceview = 1;
                   2789:                     $cfile = $template;
                   2790:                 }
                   2791:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2792:                     $incourse = 1;
                   2793:                     if ($env{'form.forceedit'}) {
                   2794:                         $forceview = 1;
                   2795:                     } else {
                   2796:                         $forceedit = 1;
                   2797:                     }
                   2798:                     $cfile = $resurl;
                   2799:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2800:                 $incourse = 1;
                   2801:                 $forceview = 1;
                   2802:                 if ($symb) {
                   2803:                     my ($map,$id,$res)=&decode_symb($symb);
                   2804:                     $env{'request.symb'} = $symb;
                   2805:                     $cfile = &clutter($res);
                   2806:                 } else {
                   2807:                     $cfile = $env{'form.suppurl'};
                   2808:                     $cfile =~ s{^http://}{};
                   2809:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2810:                 }
                   2811:             }
                   2812:         }
                   2813:         if ($uploaded || $incourse) {
                   2814:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2815:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2816:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2817:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2818:             # Check that the user has permission to edit this resource
                   2819:             my $setpriv = 1;
                   2820:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2821:             if (defined($cfudom)) {
                   2822:                 $home=&homeserver($cfuname,$cfudom);
                   2823:                 $cfile=$file;
                   2824:             }
                   2825:         }
                   2826:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2827:             (($home ne '') && ($home ne 'no_host'))) {
                   2828:             my @ids=&current_machine_ids();
                   2829:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2830:                 $switchserver=1;
                   2831:             }
                   2832:         }
                   2833:     }
                   2834:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2835: }
                   2836: 
                   2837: sub is_course_upload {
                   2838:     my ($file,$cnum,$cdom) = @_;
                   2839:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2840:     $uploadpath =~ s{^\/}{};
                   2841:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2842:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2843:         return 1;
                   2844:     }
                   2845:     return;
                   2846: }
                   2847: 
                   2848: sub in_course {
                   2849:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2850:     if ($hideprivileged) {
                   2851:         my $skipuser;
                   2852:         if (&privileged($uname,$udom)) {
                   2853:             $skipuser = 1;
                   2854:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2855:             if ($coursehash{'nothideprivileged'}) {
                   2856:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2857:                     my $user;
                   2858:                     if ($item =~ /:/) {
                   2859:                         $user = $item;
                   2860:                     } else {
                   2861:                         $user = join(':',split(/[\@]/,$item));
                   2862:                     }
                   2863:                     if ($user eq $uname.':'.$udom) {
                   2864:                         undef($skipuser);
                   2865:                         last;
                   2866:                     }
                   2867:                 }
                   2868:             }
                   2869:             if ($skipuser) {
                   2870:                 return 0;
                   2871:             }
                   2872:         }
                   2873:     }
                   2874:     $type ||= 'any';
                   2875:     if (!defined($cdom) || !defined($cnum)) {
                   2876:         my $cid  = $env{'request.course.id'};
                   2877:         $cdom = $env{'course.'.$cid.'.domain'};
                   2878:         $cnum = $env{'course.'.$cid.'.num'};
                   2879:     }
                   2880:     my $typesref;
                   2881:     if (($type eq 'any') || ($type eq 'all')) {
                   2882:         $typesref = ['active','previous','future'];
                   2883:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2884:         $typesref = [$type];
                   2885:     }
                   2886:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2887:                               $typesref,undef,[$cdom]);
                   2888:     my ($tmp) = keys(%roles);
                   2889:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2890:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2891:     if (@course_roles > 0) {
                   2892:         return 1;
                   2893:     }
                   2894:     return 0;
                   2895: }
                   2896: 
1.478     albertel 2897: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2898: # input: action, courseID, current domain, intended
1.637     raeburn  2899: #        path to file, source of file, instruction to parse file for objects,
                   2900: #        ref to hash for embedded objects,
                   2901: #        ref to hash for codebase of java objects.
1.1095    raeburn  2902: #        reference to scalar to accommodate mime type determined
                   2903: #          from File::MMagic if $parser = parse.
1.637     raeburn  2904: #
1.485     raeburn  2905: # output: url to file (if action was uploaddoc), 
                   2906: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2907: #
1.478     albertel 2908: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2909: # course.
1.477     raeburn  2910: #
1.478     albertel 2911: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2912: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2913: #          course's home server.
1.477     raeburn  2914: #
1.478     albertel 2915: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2916: #          be copied from $source (current location) to 
                   2917: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2918: #         and will then be copied to
                   2919: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2920: #         course's home server.
1.485     raeburn  2921: #
1.481     raeburn  2922: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2923: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2924: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2925: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2926: #         in course's home server.
1.637     raeburn  2927: #
1.477     raeburn  2928: 
                   2929: sub process_coursefile {
1.1095    raeburn  2930:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2931:         $mimetype)=@_;
1.477     raeburn  2932:     my $fetchresult;
1.638     albertel 2933:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2934:     if ($action eq 'propagate') {
1.638     albertel 2935:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2936: 			     $home);
1.481     raeburn  2937:     } else {
1.477     raeburn  2938:         my $fpath = '';
                   2939:         my $fname = $file;
1.478     albertel 2940:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2941:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2942:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2943:         if ($action eq 'copy') {
                   2944:             if ($source eq '') {
                   2945:                 $fetchresult = 'no source file';
                   2946:                 return $fetchresult;
                   2947:             } else {
                   2948:                 my $destination = $filepath.'/'.$fname;
                   2949:                 rename($source,$destination);
                   2950:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2951:                                  $home);
1.481     raeburn  2952:             }
                   2953:         } elsif ($action eq 'uploaddoc') {
                   2954:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2955:             print $fh $env{'form.'.$source};
1.481     raeburn  2956:             close($fh);
1.637     raeburn  2957:             if ($parser eq 'parse') {
1.1024    raeburn  2958:                 my $mm = new File::MMagic;
1.1095    raeburn  2959:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2960:                 if ($type eq 'text/html') {
1.1024    raeburn  2961:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2962:                     unless ($parse_result eq 'ok') {
                   2963:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2964:                     }
1.637     raeburn  2965:                 }
1.1095    raeburn  2966:                 if (ref($mimetype)) {
                   2967:                     $$mimetype = $type;
                   2968:                 } 
1.637     raeburn  2969:             }
1.477     raeburn  2970:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2971:                                  $home);
1.481     raeburn  2972:             if ($fetchresult eq 'ok') {
                   2973:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2974:             } else {
                   2975:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2976:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2977:                 return '/adm/notfound.html';
                   2978:             }
1.477     raeburn  2979:         }
                   2980:     }
1.485     raeburn  2981:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2982:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2983:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2984:     }
                   2985:     return $fetchresult;
                   2986: }
                   2987: 
1.637     raeburn  2988: sub build_filepath {
                   2989:     my ($fpath) = @_;
                   2990:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2991:     unless ($fpath eq '') {
                   2992:         my @parts=split('/',$fpath);
                   2993:         foreach my $part (@parts) {
                   2994:             $filepath.= '/'.$part;
                   2995:             if ((-e $filepath)!=1) {
                   2996:                 mkdir($filepath,0777);
                   2997:             }
                   2998:         }
                   2999:     }
                   3000:     return $filepath;
                   3001: }
                   3002: 
                   3003: sub store_edited_file {
1.638     albertel 3004:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3005:     my $file = $primary_url;
                   3006:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3007:     my $fpath = '';
                   3008:     my $fname = $file;
                   3009:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3010:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3011:     my $filepath = &build_filepath($fpath);
                   3012:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3013:     print $fh $content;
                   3014:     close($fh);
1.638     albertel 3015:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3016:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3017: 			  $home);
1.637     raeburn  3018:     if ($$fetchresult eq 'ok') {
                   3019:         return '/uploaded/'.$fpath.'/'.$fname;
                   3020:     } else {
1.638     albertel 3021:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3022: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3023:         return '/adm/notfound.html';
                   3024:     }
                   3025: }
                   3026: 
1.531     albertel 3027: sub clean_filename {
1.831     albertel 3028:     my ($fname,$args)=@_;
1.315     www      3029: # Replace Windows backslashes by forward slashes
1.257     www      3030:     $fname=~s/\\/\//g;
1.831     albertel 3031:     if (!$args->{'keep_path'}) {
                   3032:         # Get rid of everything but the actual filename
                   3033: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3034:     }
1.315     www      3035: # Replace spaces by underscores
                   3036:     $fname=~s/\s+/\_/g;
                   3037: # Replace all other weird characters by nothing
1.831     albertel 3038:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3039: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3040: # numbers
                   3041:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3042:     return $fname;
                   3043: }
1.1051    raeburn  3044: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3045: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3046: # image with the same aspect ratio as the original, but with dimensions which do 
                   3047: # not exceed $resizewidth and $resizeheight.
                   3048:  
1.984     neumanie 3049: sub resizeImage {
1.1051    raeburn  3050:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3051:     my $ima = Image::Magick->new;
                   3052:     my $resized;
                   3053:     if (-e $img_path) {
                   3054:         $ima->Read($img_path);
                   3055:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3056:             my $width = $ima->Get('width');
                   3057:             my $height = $ima->Get('height');
                   3058:             if ($width > $resizewidth) {
                   3059: 	        my $factor = $width/$resizewidth;
                   3060:                 my $newheight = $height/$factor;
                   3061:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3062:                 $resized = 1;
                   3063:             }
                   3064:         }
                   3065:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3066:             my $width = $ima->Get('width');
                   3067:             my $height = $ima->Get('height');
                   3068:             if ($height > $resizeheight) {
                   3069:                 my $factor = $height/$resizeheight;
                   3070:                 my $newwidth = $width/$factor;
                   3071:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3072:                 $resized = 1;
                   3073:             }
                   3074:         }
                   3075:         if ($resized) {
                   3076:             $ima->Write($img_path);
                   3077:         }
                   3078:     }
                   3079:     return;
1.977     amueller 3080: }
                   3081: 
1.608     albertel 3082: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3083: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3084: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3085: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3086: #                                    canceloverwrite, or ''. 
                   3087: #                   if 'coursedoc': upload to the current course
                   3088: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3089: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3090: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3091: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3092: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3093: #        $allfiles - reference to hash for embedded objects
                   3094: #        $codebase - reference to hash for codebase of java objects
                   3095: #        $desuname - username for permanent storage of uploaded file
                   3096: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3097: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3098: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3099: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3100: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3101: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3102: #                    from File::MMagic.
1.858     raeburn  3103: # 
1.686     albertel 3104: # output: url of file in userspace, or error: <message> 
                   3105: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3106: 
1.531     albertel 3107: sub userfileupload {
1.1090    raeburn  3108:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3109:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3110:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3111:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3112:     $fname=&clean_filename($fname);
1.1090    raeburn  3113:     # See if there is anything left
1.257     www      3114:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3115:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3116:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3117:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3118:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3119:         my $now = time;
1.1090    raeburn  3120:         my $filepath;
1.1095    raeburn  3121:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3122:              $filepath = 'tmp/helprequests/'.$now;
                   3123:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3124:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3125:                          '_'.$env{'user.domain'}.'/pending';
                   3126:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3127:             my ($docuname,$docudom);
                   3128:             if ($destudom) {
                   3129:                 $docudom = $destudom;
                   3130:             } else {
                   3131:                 $docudom = $env{'user.domain'};
                   3132:             }
                   3133:             if ($destuname) {
                   3134:                 $docuname = $destuname;
                   3135:             } else {
                   3136:                 $docuname = $env{'user.name'};
                   3137:             }
                   3138:             if (exists($env{'form.group'})) {
                   3139:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3140:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3141:             }
                   3142:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3143:             if ($context eq 'canceloverwrite') {
                   3144:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3145:                 if (-e  $tempfile) {
                   3146:                     my @info = stat($tempfile);
                   3147:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3148:                         unlink($tempfile);
                   3149:                     }
                   3150:                 }
                   3151:                 return;
1.523     raeburn  3152:             }
                   3153:         }
1.1090    raeburn  3154:         # Create the directory if not present
1.741     raeburn  3155:         my @parts=split(/\//,$filepath);
                   3156:         my $fullpath = $perlvar{'lonDaemons'};
                   3157:         for (my $i=0;$i<@parts;$i++) {
                   3158:             $fullpath .= '/'.$parts[$i];
                   3159:             if ((-e $fullpath)!=1) {
                   3160:                 mkdir($fullpath,0777);
                   3161:             }
                   3162:         }
                   3163:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3164:         print $fh $env{'form.'.$formname};
                   3165:         close($fh);
1.1090    raeburn  3166:         if ($context eq 'existingfile') {
                   3167:             my @info = stat($fullpath.'/'.$fname);
                   3168:             return ($fullpath.'/'.$fname,$info[9]);
                   3169:         } else {
                   3170:             return $fullpath.'/'.$fname;
                   3171:         }
1.523     raeburn  3172:     }
1.995     raeburn  3173:     if ($subdir eq 'scantron') {
                   3174:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3175:     } else {
1.995     raeburn  3176:         $fname="$subdir/$fname";
                   3177:     }
1.1090    raeburn  3178:     if ($context eq 'coursedoc') {
1.638     albertel 3179: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3180: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3181:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3182:             return &finishuserfileupload($docuname,$docudom,
                   3183: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3184: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3185:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3186:         } else {
1.620     albertel 3187:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3188:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3189: 				       $fname,$formname,$parser,
1.1095    raeburn  3190: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3191:         }
1.719     banghart 3192:     } elsif (defined($destuname)) {
                   3193:         my $docuname=$destuname;
                   3194:         my $docudom=$destudom;
1.860     raeburn  3195: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3196: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3197:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3198:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3199:     } else {
1.638     albertel 3200:         my $docuname=$env{'user.name'};
                   3201:         my $docudom=$env{'user.domain'};
1.714     raeburn  3202:         if (exists($env{'form.group'})) {
                   3203:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3204:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3205:         }
1.860     raeburn  3206: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3207: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3208:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3209:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3210:     }
1.271     www      3211: }
                   3212: 
                   3213: sub finishuserfileupload {
1.860     raeburn  3214:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3215:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3216:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3217:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3218:   
1.860     raeburn  3219:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3220:     $file=$fname;
                   3221:     if ($fname=~m|/|) {
                   3222:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3223: 	$path.=$fnamepath.'/';
                   3224:     }
1.259     www      3225:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3226:     my $count;
                   3227:     for ($count=4;$count<=$#parts;$count++) {
                   3228:         $filepath.="/$parts[$count]";
                   3229:         if ((-e $filepath)!=1) {
                   3230: 	    mkdir($filepath,0777);
                   3231:         }
                   3232:     }
1.984     neumanie 3233: 
1.258     www      3234: # Save the file
                   3235:     {
1.701     albertel 3236: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3237: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3238: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3239: 	    return '/adm/notfound.html';
                   3240: 	}
1.1090    raeburn  3241:         if ($context eq 'overwrite') {
1.1117    foxr     3242:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3243:             my $target = $filepath.'/'.$file;
                   3244:             if (-e $source) {
                   3245:                 my @info = stat($source);
                   3246:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3247:                     unless (&File::Copy::move($source,$target)) {
                   3248:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3249:                         return "Moving from $source failed";
                   3250:                     }
                   3251:                 } else {
                   3252:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3253:                 }
                   3254:             } else {
                   3255:                 return "Temporary file: $source missing";
                   3256:             }
                   3257:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3258: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3259: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3260: 	    return '/adm/notfound.html';
                   3261: 	}
1.570     albertel 3262: 	close(FH);
1.1051    raeburn  3263:         if ($resizewidth && $resizeheight) {
                   3264:             my $mm = new File::MMagic;
                   3265:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3266:             if ($mime_type =~ m{^image/}) {
                   3267: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3268:             }  
1.977     amueller 3269: 	}
1.258     www      3270:     }
1.1152    raeburn  3271:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3272:         if (ref($mimetype)) {
                   3273:             if ($$mimetype eq '') {
                   3274:                 my $mm = new File::MMagic;
                   3275:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3276:                 $$mimetype = $type;
                   3277:             }
                   3278:         }
                   3279:     }
1.637     raeburn  3280:     if ($parser eq 'parse') {
1.1152    raeburn  3281:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3282:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3283:                                                        $allfiles,$codebase);
                   3284:             unless ($parse_result eq 'ok') {
                   3285:                 &logthis('Failed to parse '.$filepath.$file.
                   3286: 	   	         ' for embedded media: '.$parse_result); 
                   3287:             }
1.637     raeburn  3288:         }
                   3289:     }
1.860     raeburn  3290:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3291:         my $input = $filepath.'/'.$file;
                   3292:         my $output = $filepath.'/'.'tn-'.$file;
                   3293:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3294:         system("convert -sample $thumbsize $input $output");
                   3295:         if (-e $filepath.'/'.'tn-'.$file) {
                   3296:             $fetchthumb  = 1; 
                   3297:         }
                   3298:     }
1.858     raeburn  3299:  
1.259     www      3300: # Notify homeserver to grep it
                   3301: #
1.984     neumanie 3302:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3303:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3304:     if ($fetchresult eq 'ok') {
1.860     raeburn  3305:         if ($fetchthumb) {
                   3306:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3307:             if ($thumbresult ne 'ok') {
                   3308:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3309:                          $docuhome.': '.$thumbresult);
                   3310:             }
                   3311:         }
1.259     www      3312: #
1.258     www      3313: # Return the URL to it
1.494     albertel 3314:         return '/uploaded/'.$path.$file;
1.263     www      3315:     } else {
1.494     albertel 3316:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3317: 		 ': '.$fetchresult);
1.263     www      3318:         return '/adm/notfound.html';
1.858     raeburn  3319:     }
1.493     albertel 3320: }
                   3321: 
1.637     raeburn  3322: sub extract_embedded_items {
1.961     raeburn  3323:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3324:     my @state = ();
1.1164    raeburn  3325:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3326:     my %javafiles = (
                   3327:                       codebase => '',
                   3328:                       code => '',
                   3329:                       archive => ''
                   3330:                     );
                   3331:     my %mediafiles = (
                   3332:                       src => '',
                   3333:                       movie => '',
                   3334:                      );
1.648     raeburn  3335:     my $p;
                   3336:     if ($content) {
                   3337:         $p = HTML::LCParser->new($content);
                   3338:     } else {
1.961     raeburn  3339:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3340:     }
1.641     albertel 3341:     while (my $t=$p->get_token()) {
1.640     albertel 3342: 	if ($t->[0] eq 'S') {
                   3343: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3344: 	    push(@state, $tagname);
1.648     raeburn  3345:             if (lc($tagname) eq 'allow') {
                   3346:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3347:             }
1.640     albertel 3348: 	    if (lc($tagname) eq 'img') {
                   3349: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3350: 	    }
1.886     albertel 3351: 	    if (lc($tagname) eq 'a') {
                   3352: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3353: 	    }
1.645     raeburn  3354:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3355:                 my $src;
1.645     raeburn  3356:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3357:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3358:                 } else {
1.1164    raeburn  3359:                     if ($attr->{'src'} ne '') {
                   3360:                         $src = $attr->{'src'};
                   3361:                         &add_filetype($allfiles,$src,'src');
                   3362:                     }
                   3363:                 }
                   3364:                 my $text = $p->get_trimmed_text();
                   3365:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3366:                     my @swfargs = split(/,/,$1);
                   3367:                     foreach my $item (@swfargs) {
                   3368:                         $item =~ s/["']//g;
                   3369:                         $item =~ s/^\s+//;
                   3370:                         $item =~ s/\s+$//;
                   3371:                     }
                   3372:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3373:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3374:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3375:                         } else {
                   3376:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3377:                         }
                   3378:                     }
1.645     raeburn  3379:                 }
                   3380:             }
                   3381:             if (lc($tagname) eq 'link') {
                   3382:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3383:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3384:                 }
                   3385:             }
1.640     albertel 3386: 	    if (lc($tagname) eq 'object' ||
                   3387: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3388: 		foreach my $item (keys(%javafiles)) {
                   3389: 		    $javafiles{$item} = '';
                   3390: 		}
1.1164    raeburn  3391:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3392:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3393:                 }
1.640     albertel 3394: 	    }
                   3395: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3396: 		my $name = lc($attr->{'name'});
                   3397: 		foreach my $item (keys(%javafiles)) {
                   3398: 		    if ($name eq $item) {
                   3399: 			$javafiles{$item} = $attr->{'value'};
                   3400: 			last;
                   3401: 		    }
                   3402: 		}
1.1164    raeburn  3403:                 my $pathfrom;
1.640     albertel 3404: 		foreach my $item (keys(%mediafiles)) {
                   3405: 		    if ($name eq $item) {
1.1164    raeburn  3406:                         $pathfrom = $attr->{'value'};
                   3407:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3408: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3409: 			last;
                   3410: 		    }
                   3411: 		}
1.1164    raeburn  3412:                 if ($name eq 'flashvars') {
                   3413:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3414:                 }
                   3415:                 if ($pathfrom ne '') {
                   3416:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3417:                                          $pathfrom);
                   3418:                 }
1.640     albertel 3419: 	    }
                   3420: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3421: 		foreach my $item (keys(%javafiles)) {
                   3422: 		    if ($attr->{$item}) {
                   3423: 			$javafiles{$item} = $attr->{$item};
                   3424: 			last;
                   3425: 		    }
                   3426: 		}
                   3427: 		foreach my $item (keys(%mediafiles)) {
                   3428: 		    if ($attr->{$item}) {
                   3429: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3430: 			last;
                   3431: 		    }
                   3432: 		}
1.1164    raeburn  3433:                 if (lc($tagname) eq 'embed') {
                   3434:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3435:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3436:                                              $attr->{'src'});
                   3437:                     }
                   3438:                 }
1.640     albertel 3439: 	    }
1.1164    raeburn  3440:             if ($t->[4] =~ m{/>$}) {
                   3441:                 pop(@state);  
                   3442:             }
1.640     albertel 3443: 	} elsif ($t->[0] eq 'E') {
                   3444: 	    my ($tagname) = ($t->[1]);
                   3445: 	    if ($javafiles{'codebase'} ne '') {
                   3446: 		$javafiles{'codebase'} .= '/';
                   3447: 	    }  
                   3448: 	    if (lc($tagname) eq 'applet' ||
                   3449: 		lc($tagname) eq 'object' ||
                   3450: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3451: 		) {
                   3452: 		foreach my $item (keys(%javafiles)) {
                   3453: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3454: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3455: 			&add_filetype($allfiles,$file,$item);
                   3456: 		    }
                   3457: 		}
                   3458: 	    } 
                   3459: 	    pop @state;
                   3460: 	}
                   3461:     }
1.1164    raeburn  3462:     foreach my $id (sort(keys(%flashvars))) {
                   3463:         if ($shockwave{$id} ne '') {
                   3464:             my @pairs = split(/\&/,$flashvars{$id});
                   3465:             foreach my $pair (@pairs) {
                   3466:                 my ($key,$value) = split(/\=/,$pair);
                   3467:                 if ($key eq 'thumb') {
                   3468:                     &add_filetype($allfiles,$value,$key);
                   3469:                 } elsif ($key eq 'content') {
                   3470:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3471:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3472:                     if ($ext ne '') {
                   3473:                         &add_filetype($allfiles,$path.$value,$ext);
                   3474:                     }
                   3475:                 }
                   3476:             }
                   3477:         }
                   3478:     }
1.637     raeburn  3479:     return 'ok';
                   3480: }
                   3481: 
1.639     albertel 3482: sub add_filetype {
                   3483:     my ($allfiles,$file,$type)=@_;
                   3484:     if (exists($allfiles->{$file})) {
                   3485: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3486: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3487: 	}
                   3488:     } else {
                   3489: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3490:     }
                   3491: }
                   3492: 
1.1164    raeburn  3493: sub embedded_dependency {
                   3494:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3495:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3496:         if (($identifier ne '') &&
                   3497:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3498:             ($pathfrom ne '')) {
                   3499:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3500:             foreach my $dep (@{$related->{$identifier}}) {
                   3501:                 &add_filetype($allfiles,$path.$dep,'object');
                   3502:             }
                   3503:         }
                   3504:     }
                   3505:     return;
                   3506: }
                   3507: 
1.493     albertel 3508: sub removeuploadedurl {
1.984     neumanie 3509:     my ($url)=@_;	
                   3510:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3511:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3512: }
                   3513: 
                   3514: sub removeuserfile {
                   3515:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3516:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3517:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3518:     if ($result eq 'ok') {	
1.798     raeburn  3519:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3520:             my $metafile = $fname.'.meta';
                   3521:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3522: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3523:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3524:             my $sqlresult = 
1.823     albertel 3525:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3526:                                         'portfolio_metadata',$group,
                   3527:                                         'delete');
1.798     raeburn  3528:         }
                   3529:     }
                   3530:     return $result;
1.257     www      3531: }
1.15      www      3532: 
1.530     albertel 3533: sub mkdiruserfile {
                   3534:     my ($docuname,$docudom,$dir)=@_;
                   3535:     my $home=&homeserver($docuname,$docudom);
                   3536:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3537: }
                   3538: 
1.531     albertel 3539: sub renameuserfile {
                   3540:     my ($docuname,$docudom,$old,$new)=@_;
                   3541:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3542:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3543:                         &escape("$old").':'.&escape("$new"),$home);
                   3544:     if ($result eq 'ok') {
                   3545:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3546:             my $oldmeta = $old.'.meta';
                   3547:             my $newmeta = $new.'.meta';
                   3548:             my $metaresult = 
                   3549:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3550: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3551:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3552:             my $sqlresult = 
1.823     albertel 3553:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3554:                                         'portfolio_metadata',$group,
                   3555:                                         'delete');
1.798     raeburn  3556:         }
                   3557:     }
                   3558:     return $result;
1.531     albertel 3559: }
                   3560: 
1.14      www      3561: # ------------------------------------------------------------------------- Log
                   3562: 
                   3563: sub log {
                   3564:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3565:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3566: }
                   3567: 
                   3568: # ------------------------------------------------------------------ Course Log
1.352     www      3569: #
                   3570: # This routine flushes several buffers of non-mission-critical nature
                   3571: #
1.157     www      3572: 
                   3573: sub flushcourselogs {
1.352     www      3574:     &logthis('Flushing log buffers');
                   3575: #
                   3576: # course logs
                   3577: # This is a log of all transactions in a course, which can be used
                   3578: # for data mining purposes
                   3579: #
                   3580: # It also collects the courseid database, which lists last transaction
                   3581: # times and course titles for all courseids
                   3582: #
                   3583:     my %courseidbuffer=();
1.921     raeburn  3584:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3585:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3586: 		          &escape($courselogs{$crsid}),
                   3587: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3588: 	    delete $courselogs{$crsid};
                   3589:         } else {
                   3590:             &logthis('Failed to flush log buffer for '.$crsid);
                   3591:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3592:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3593:                         " exceeded maximum size, deleting.</font>");
                   3594:                delete $courselogs{$crsid};
                   3595:             }
1.352     www      3596:         }
1.920     raeburn  3597:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3598:             'description' => $coursedescrbuf{$crsid},
                   3599:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3600:             'type'        => $coursetypebuf{$crsid},
                   3601:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3602:         };
1.191     harris41 3603:     }
1.352     www      3604: #
                   3605: # Write course id database (reverse lookup) to homeserver of courses 
                   3606: # Is used in pickcourse
                   3607: #
1.840     albertel 3608:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3609:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3610:                                     $courseidbuffer{$crs_home},
                   3611:                                     $crs_home,'timeonly');
1.352     www      3612:     }
                   3613: #
                   3614: # File accesses
                   3615: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3616: #
1.449     matthew  3617:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3618:         if ($entry =~ /___count$/) {
                   3619:             my ($dom,$name);
1.807     albertel 3620:             ($dom,$name,undef)=
1.811     albertel 3621: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3622:             if (! defined($dom) || $dom eq '' || 
                   3623:                 ! defined($name) || $name eq '') {
1.620     albertel 3624:                 my $cid = $env{'request.course.id'};
                   3625:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3626:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3627:             }
1.450     matthew  3628:             my $value = $accesshash{$entry};
                   3629:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3630:             my %temphash=($url => $value);
1.449     matthew  3631:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3632:             if ($result eq 'ok') {
                   3633:                 delete $accesshash{$entry};
                   3634:             }
                   3635:         } else {
1.811     albertel 3636:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3637:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3638:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3639:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3640:                 delete $accesshash{$entry};
                   3641:             }
1.185     www      3642:         }
1.191     harris41 3643:     }
1.352     www      3644: #
                   3645: # Roles
                   3646: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3647: #
1.800     albertel 3648:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3649:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3650: 	    split(/\:/,$entry);
                   3651:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3652:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3653:                 $rudom,$runame) eq 'ok') {
                   3654: 	    delete $userrolehash{$entry};
                   3655:         }
                   3656:     }
1.662     raeburn  3657: #
                   3658: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3659: #
                   3660:     my %domrolebuffer = ();
1.1000    raeburn  3661:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3662:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3663:         if ($domrolebuffer{$rudom}) {
                   3664:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3665:                       '='.&escape($domainrolehash{$entry});
                   3666:         } else {
                   3667:             $domrolebuffer{$rudom}.=&escape($entry).
                   3668:                       '='.&escape($domainrolehash{$entry});
                   3669:         }
                   3670:         delete $domainrolehash{$entry};
                   3671:     }
                   3672:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3673: 	my %servers = &get_servers($dom,'library');
                   3674: 	foreach my $tryserver (keys(%servers)) {
                   3675: 	    unless (&reply('domroleput:'.$dom.':'.
                   3676: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3677: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3678: 	    }
1.662     raeburn  3679:         }
                   3680:     }
1.186     www      3681:     $dumpcount++;
1.157     www      3682: }
                   3683: 
                   3684: sub courselog {
                   3685:     my $what=shift;
1.158     www      3686:     $what=time.':'.$what;
1.620     albertel 3687:     unless ($env{'request.course.id'}) { return ''; }
                   3688:     $coursedombuf{$env{'request.course.id'}}=
                   3689:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3690:     $coursenumbuf{$env{'request.course.id'}}=
                   3691:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3692:     $coursehombuf{$env{'request.course.id'}}=
                   3693:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3694:     $coursedescrbuf{$env{'request.course.id'}}=
                   3695:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3696:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3697:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3698:     $courseownerbuf{$env{'request.course.id'}}=
                   3699:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3700:     $coursetypebuf{$env{'request.course.id'}}=
                   3701:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3702:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3703: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3704:     } else {
1.620     albertel 3705: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3706:     }
1.620     albertel 3707:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3708: 	&flushcourselogs();
                   3709:     }
1.158     www      3710: }
                   3711: 
                   3712: sub courseacclog {
                   3713:     my $fnsymb=shift;
1.620     albertel 3714:     unless ($env{'request.course.id'}) { return ''; }
                   3715:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3716:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3717:         $what.=':POST';
1.583     matthew  3718:         # FIXME: Probably ought to escape things....
1.800     albertel 3719: 	foreach my $key (keys(%env)) {
                   3720:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3721:                 my $formitem = $1;
                   3722:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3723:                     $what.=':'.$formitem.'='.$env{$key};
                   3724:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3725:                     $what.=':'.$formitem.'='.$env{$key};
                   3726:                 }
1.158     www      3727:             }
1.191     harris41 3728:         }
1.583     matthew  3729:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3730:         # FIXME: We should not be depending on a form parameter that someone
                   3731:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3732:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3733:             $what.= ':POST';
                   3734:             # FIXME: Probably ought to escape things....
                   3735:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3736:                                  'crsdiscuss') {
1.620     albertel 3737:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3738:             }
                   3739:         }
1.158     www      3740:     }
                   3741:     &courselog($what);
1.149     www      3742: }
                   3743: 
1.185     www      3744: sub countacc {
                   3745:     my $url=&declutter(shift);
1.458     matthew  3746:     return if (! defined($url) || $url eq '');
1.620     albertel 3747:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3748: #
                   3749: # Mark that this url was used in this course
                   3750: #
1.620     albertel 3751:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3752: #
                   3753: # Increase the access count for this resource in this child process
                   3754: #
1.281     www      3755:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3756:     $accesshash{$key}++;
1.185     www      3757: }
1.349     www      3758: 
1.361     www      3759: sub linklog {
                   3760:     my ($from,$to)=@_;
                   3761:     $from=&declutter($from);
                   3762:     $to=&declutter($to);
                   3763:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3764:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3765: }
1.1160    www      3766: 
                   3767: sub statslog {
                   3768:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3769:     if ($users<2) { return; }
                   3770:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3771:             'course'       => $env{'request.course.id'},
                   3772:             'sections'     => '"all"',
                   3773:             'num_students' => $users,
                   3774:             'part'         => $part,
                   3775:             'symb'         => $symb,
                   3776:             'mean_tries'   => $av_attempts,
                   3777:             'deg_of_diff'  => $degdiff});
                   3778:     foreach my $key (keys(%dynstore)) {
                   3779:         $accesshash{$key}=$dynstore{$key};
                   3780:     }
                   3781: }
1.361     www      3782:   
1.349     www      3783: sub userrolelog {
                   3784:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3785:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3786:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3787:        $userrolehash
                   3788:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3789:                     =$tend.':'.$tstart;
1.662     raeburn  3790:     }
1.1169    droeschl 3791:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3792:        $userrolehash
                   3793:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3794:                     =$tend.':'.$tstart;
                   3795:     }
1.1169    droeschl 3796:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3797:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3798:        $domainrolehash
                   3799:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3800:                     = $tend.':'.$tstart;
                   3801:     }
1.351     www      3802: }
                   3803: 
1.957     raeburn  3804: sub courserolelog {
                   3805:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3806:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3807:         my $cdom = $1;
                   3808:         my $cnum = $2;
                   3809:         my $sec = $3;
                   3810:         my $namespace = 'rolelog';
                   3811:         my %storehash = (
                   3812:                            role    => $trole,
                   3813:                            start   => $tstart,
                   3814:                            end     => $tend,
                   3815:                            selfenroll => $selfenroll,
                   3816:                            context    => $context,
                   3817:                         );
                   3818:         if ($trole eq 'gr') {
                   3819:             $namespace = 'groupslog';
                   3820:             $storehash{'group'} = $sec;
                   3821:         } else {
                   3822:             $storehash{'section'} = $sec;
                   3823:         }
                   3824:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3825:                    $domain,$cnum,$cdom);
                   3826:         if (($trole ne 'st') || ($sec ne '')) {
                   3827:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3828:         }
                   3829:     }
                   3830:     return;
                   3831: }
                   3832: 
1.1172.2.9  raeburn  3833: sub domainrolelog {
                   3834:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3835:     if ($area =~ m{^/($match_domain)/$}) {
                   3836:         my $cdom = $1;
                   3837:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3838:         my $namespace = 'rolelog';
                   3839:         my %storehash = (
                   3840:                            role    => $trole,
                   3841:                            start   => $tstart,
                   3842:                            end     => $tend,
                   3843:                            context => $context,
                   3844:                         );
                   3845:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3846:                    $domain,$domconfiguser,$cdom);
                   3847:     }
                   3848:     return;
                   3849: 
                   3850: }
                   3851: 
                   3852: sub coauthorrolelog {
                   3853:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3854:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3855:         my $audom = $1;
                   3856:         my $auname = $2;
                   3857:         my $namespace = 'rolelog';
                   3858:         my %storehash = (
                   3859:                            role    => $trole,
                   3860:                            start   => $tstart,
                   3861:                            end     => $tend,
                   3862:                            context => $context,
                   3863:                         );
                   3864:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3865:                    $domain,$auname,$audom);
                   3866:     }
                   3867:     return;
                   3868: }
                   3869: 
1.351     www      3870: sub get_course_adv_roles {
1.948     raeburn  3871:     my ($cid,$codes) = @_;
1.620     albertel 3872:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3873:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3874:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3875:     my %nothide=();
1.800     albertel 3876:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3877:         if ($user !~ /:/) {
                   3878: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3879:         } else {
                   3880:             $nothide{$user}=1;
                   3881:         }
1.470     www      3882:     }
1.351     www      3883:     my %returnhash=();
                   3884:     my %dumphash=
                   3885:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3886:     my $now=time;
1.997     raeburn  3887:     my %privileged;
1.1000    raeburn  3888:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3889: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3890:         if (($tstart) && ($tstart<0)) { next; }
                   3891:         if (($tend) && ($tend<$now)) { next; }
                   3892:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3893:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3894: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3895:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3896:             my %dompersonnel =
1.998     raeburn  3897:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3898:             $privileged{$domain} = {};
                   3899:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3900:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3901:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3902:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3903:                         $privileged{$udom}{$uname} = 1;
                   3904:                     }
                   3905:                 }
                   3906:             }
                   3907:         }
                   3908:         if ((exists($privileged{$domain}{$username})) && 
                   3909:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3910: 	if ($role eq 'cr') { next; }
1.948     raeburn  3911:         if ($codes) {
                   3912:             if ($section) { $role .= ':'.$section; }
                   3913:             if ($returnhash{$role}) {
                   3914:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3915:             } else {
                   3916:                 $returnhash{$role}=$username.':'.$domain;
                   3917:             }
1.351     www      3918:         } else {
1.988     raeburn  3919:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3920:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3921:             if ($returnhash{$key}) {
                   3922: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3923:             } else {
                   3924:                 $returnhash{$key}=$username.':'.$domain;
                   3925:             }
1.351     www      3926:         }
1.948     raeburn  3927:     }
1.400     www      3928:     return %returnhash;
                   3929: }
                   3930: 
                   3931: sub get_my_roles {
1.937     raeburn  3932:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3933:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3934:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3935:     my (%dumphash,%nothide);
1.1086    raeburn  3936:     if ($context eq 'userroles') {
1.1166    raeburn  3937:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3938:     } else {
                   3939:         %dumphash=
1.400     www      3940:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3941:         if ($hidepriv) {
                   3942:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3943:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3944:                 if ($user !~ /:/) {
                   3945:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3946:                 } else {
                   3947:                     $nothide{$user} = 1;
                   3948:                 }
                   3949:             }
                   3950:         }
1.858     raeburn  3951:     }
1.400     www      3952:     my %returnhash=();
                   3953:     my $now=time;
1.999     raeburn  3954:     my %privileged;
1.800     albertel 3955:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3956:         my ($role,$tend,$tstart);
                   3957:         if ($context eq 'userroles') {
1.1149    raeburn  3958:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3959: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3960:         } else {
                   3961:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3962:         }
1.400     www      3963:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3964:         my $status = 'active';
1.939     raeburn  3965:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3966:             $status = 'previous';
                   3967:         } 
                   3968:         if (($tstart) && ($now<$tstart)) {
                   3969:             $status = 'future';
                   3970:         }
                   3971:         if (ref($types) eq 'ARRAY') {
                   3972:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3973:                 next;
                   3974:             } 
                   3975:         } else {
                   3976:             if ($status ne 'active') {
                   3977:                 next;
                   3978:             }
                   3979:         }
1.867     raeburn  3980:         my ($rolecode,$username,$domain,$section,$area);
                   3981:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3982:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3983:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3984:         } else {
                   3985:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3986:         }
1.832     raeburn  3987:         if (ref($roledoms) eq 'ARRAY') {
                   3988:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3989:                 next;
                   3990:             }
                   3991:         }
                   3992:         if (ref($roles) eq 'ARRAY') {
                   3993:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3994:                 if ($role =~ /^cr\//) {
                   3995:                     if (!grep(/^cr$/,@{$roles})) {
                   3996:                         next;
                   3997:                     }
1.1104    raeburn  3998:                 } elsif ($role =~ /^gr\//) {
                   3999:                     if (!grep(/^gr$/,@{$roles})) {
                   4000:                         next;
                   4001:                     }
1.922     raeburn  4002:                 } else {
                   4003:                     next;
                   4004:                 }
1.832     raeburn  4005:             }
1.867     raeburn  4006:         }
1.937     raeburn  4007:         if ($hidepriv) {
1.999     raeburn  4008:             if ($context eq 'userroles') {
                   4009:                 if ((&privileged($username,$domain)) &&
                   4010:                     (!$nothide{$username.':'.$domain})) {
                   4011:                     next;
                   4012:                 }
                   4013:             } else {
                   4014:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4015:                     my %dompersonnel =
                   4016:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4017:                     $privileged{$domain} = {};
                   4018:                     if (keys(%dompersonnel)) {
                   4019:                         foreach my $server (keys(%dompersonnel)) {
                   4020:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4021:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4022:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4023:                                     $privileged{$udom}{$uname} = $trole;
                   4024:                                 }
                   4025:                             }
                   4026:                         }
                   4027:                     }
                   4028:                 }
                   4029:                 if (exists($privileged{$domain}{$username})) {
                   4030:                     if (!$nothide{$username.':'.$domain}) {
                   4031:                         next;
                   4032:                     }
                   4033:                 }
1.937     raeburn  4034:             }
                   4035:         }
1.933     raeburn  4036:         if ($withsec) {
                   4037:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4038:                 $tstart.':'.$tend;
                   4039:         } else {
                   4040:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4041:         }
1.832     raeburn  4042:     }
1.373     www      4043:     return %returnhash;
1.399     www      4044: }
                   4045: 
                   4046: # ----------------------------------------------------- Frontpage Announcements
                   4047: #
                   4048: #
                   4049: 
                   4050: sub postannounce {
                   4051:     my ($server,$text)=@_;
1.844     albertel 4052:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4053:     unless ($text=~/\w/) { $text=''; }
                   4054:     return &reply('setannounce:'.&escape($text),$server);
                   4055: }
                   4056: 
                   4057: sub getannounce {
1.448     albertel 4058: 
                   4059:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4060: 	my $announcement='';
1.800     albertel 4061: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4062: 	close($fh);
1.399     www      4063: 	if ($announcement=~/\w/) { 
                   4064: 	    return 
                   4065:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4066:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4067: 	} else {
                   4068: 	    return '';
                   4069: 	}
                   4070:     } else {
                   4071: 	return '';
                   4072:     }
1.351     www      4073: }
1.353     www      4074: 
                   4075: # ---------------------------------------------------------- Course ID routines
                   4076: # Deal with domain's nohist_courseid.db files
                   4077: #
                   4078: 
                   4079: sub courseidput {
1.921     raeburn  4080:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4081:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4082:     my $outcome;
                   4083:     if ($caller eq 'timeonly') {
                   4084:         my $cids = '';
                   4085:         foreach my $item (keys(%$storehash)) {
                   4086:             $cids.=&escape($item).'&';
                   4087:         }
                   4088:         $cids=~s/\&$//;
                   4089:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4090:                           $coursehome);       
                   4091:     } else {
                   4092:         my $items = '';
                   4093:         foreach my $item (keys(%$storehash)) {
                   4094:             $items.= &escape($item).'='.
                   4095:                      &freeze_escape($$storehash{$item}).'&';
                   4096:         }
                   4097:         $items=~s/\&$//;
                   4098:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4099:                           $coursehome);
1.918     raeburn  4100:     }
                   4101:     if ($outcome eq 'unknown_cmd') {
                   4102:         my $what;
                   4103:         foreach my $cid (keys(%$storehash)) {
                   4104:             $what .= &escape($cid).'=';
1.921     raeburn  4105:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4106:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4107:             }
                   4108:             $what =~ s/\:$/&/;
                   4109:         }
                   4110:         $what =~ s/\&$//;  
                   4111:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4112:     } else {
                   4113:         return $outcome;
                   4114:     }
1.353     www      4115: }
                   4116: 
                   4117: sub courseiddump {
1.921     raeburn  4118:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4119:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4120:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4121:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4122:     my $as_hash = 1;
                   4123:     my %returnhash;
                   4124:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4125:     my %libserv = &all_library();
                   4126:     foreach my $tryserver (keys(%libserv)) {
                   4127:         if ( (  $hostidflag == 1 
                   4128: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4129: 	     || (!defined($hostidflag)) ) {
                   4130: 
1.918     raeburn  4131: 	    if (($domfilter eq '') ||
                   4132: 		(&host_domain($tryserver) eq $domfilter)) {
                   4133:                 my $rep = 
                   4134:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4135:                          $sincefilter.':'.&escape($descfilter).':'.
                   4136:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   4137:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  4138:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  4139:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  4140:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  4141:                          &escape($cc_clone).':'.$cloneonly.':'.
                   4142:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  4143:                          &escape($creationcontext).':'.$domcloner,
                   4144:                          $tryserver);
1.918     raeburn  4145:                 my @pairs=split(/\&/,$rep);
                   4146:                 foreach my $item (@pairs) {
                   4147:                     my ($key,$value)=split(/\=/,$item,2);
                   4148:                     $key = &unescape($key);
                   4149:                     next if ($key =~ /^error: 2 /);
                   4150:                     my $result = &thaw_unescape($value);
                   4151:                     if (ref($result) eq 'HASH') {
                   4152:                         $returnhash{$key}=$result;
                   4153:                     } else {
1.921     raeburn  4154:                         my @responses = split(/:/,$value);
                   4155:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4156:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4157:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4158:                         }
1.1008    raeburn  4159:                     }
1.353     www      4160:                 }
                   4161:             }
                   4162:         }
                   4163:     }
                   4164:     return %returnhash;
                   4165: }
                   4166: 
1.1055    raeburn  4167: sub courselastaccess {
                   4168:     my ($cdom,$cnum,$hostidref) = @_;
                   4169:     my %returnhash;
                   4170:     if ($cdom && $cnum) {
                   4171:         my $chome = &homeserver($cnum,$cdom);
                   4172:         if ($chome ne 'no_host') {
                   4173:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4174:             &extract_lastaccess(\%returnhash,$rep);
                   4175:         }
                   4176:     } else {
                   4177:         if (!$cdom) { $cdom=''; }
                   4178:         my %libserv = &all_library();
                   4179:         foreach my $tryserver (keys(%libserv)) {
                   4180:             if (ref($hostidref) eq 'ARRAY') {
                   4181:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4182:             } 
                   4183:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4184:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4185:                 &extract_lastaccess(\%returnhash,$rep);
                   4186:             }
                   4187:         }
                   4188:     }
                   4189:     return %returnhash;
                   4190: }
                   4191: 
                   4192: sub extract_lastaccess {
                   4193:     my ($returnhash,$rep) = @_;
                   4194:     if (ref($returnhash) eq 'HASH') {
                   4195:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4196:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4197:                  $rep eq '') {
                   4198:             my @pairs=split(/\&/,$rep);
                   4199:             foreach my $item (@pairs) {
                   4200:                 my ($key,$value)=split(/\=/,$item,2);
                   4201:                 $key = &unescape($key);
                   4202:                 next if ($key =~ /^error: 2 /);
                   4203:                 $returnhash->{$key} = &thaw_unescape($value);
                   4204:             }
                   4205:         }
                   4206:     }
                   4207:     return;
                   4208: }
                   4209: 
1.658     raeburn  4210: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4211: 
                   4212: sub dcmailput {
1.685     raeburn  4213:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4214:     my $status = &Apache::lonnet::critical(
1.740     www      4215:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4216:        &escape($message),$server);
1.662     raeburn  4217:     return $status;
                   4218: }
                   4219: 
1.658     raeburn  4220: sub dcmaildump {
                   4221:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4222:     my %returnhash=();
1.846     albertel 4223: 
                   4224:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4225:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4226:                                                          &escape($enddate).':';
                   4227: 	my @esc_senders=map { &escape($_)} @$senders;
                   4228: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4229: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4230:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4231:             if (($key) && ($value)) {
                   4232:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4233:             }
                   4234:         }
                   4235:     }
                   4236:     return %returnhash;
                   4237: }
1.662     raeburn  4238: # ---------------------------------------------------------- Domain roles
                   4239: 
                   4240: sub get_domain_roles {
                   4241:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4242:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4243:         $startdate = '.';
                   4244:     }
1.1018    raeburn  4245:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4246:         $enddate = '.';
                   4247:     }
1.922     raeburn  4248:     my $rolelist;
                   4249:     if (ref($roles) eq 'ARRAY') {
                   4250:         $rolelist = join(':',@{$roles});
                   4251:     }
1.662     raeburn  4252:     my %personnel = ();
1.841     albertel 4253: 
                   4254:     my %servers = &get_servers($dom,'library');
                   4255:     foreach my $tryserver (keys(%servers)) {
                   4256: 	%{$personnel{$tryserver}}=();
                   4257: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4258: 					    &escape($startdate).':'.
                   4259: 					    &escape($enddate).':'.
                   4260: 					    &escape($rolelist), $tryserver))) {
                   4261: 	    my ($key,$value) = split(/\=/,$line,2);
                   4262: 	    if (($key) && ($value)) {
                   4263: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4264: 	    }
                   4265: 	}
1.662     raeburn  4266:     }
                   4267:     return %personnel;
                   4268: }
1.658     raeburn  4269: 
1.1057    www      4270: # ----------------------------------------------------------- Interval timing 
1.149     www      4271: 
1.1153    www      4272: {
                   4273: # Caches needed for speedup of navmaps
                   4274: # We don't want to cache this for very long at all (5 seconds at most)
                   4275: # 
                   4276: # The user for whom we cache
                   4277: my $cachedkey='';
                   4278: # The cached times for this user
                   4279: my %cachedtimes=();
                   4280: # When this was last done
                   4281: my $cachedtime=();
                   4282: 
                   4283: sub load_all_first_access {
1.1154    raeburn  4284:     my ($uname,$udom)=@_;
1.1156    www      4285:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4286:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4287:         return;
                   4288:     }
                   4289:     $cachedtime=time;
                   4290:     $cachedkey=$uname.':'.$udom;
                   4291:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4292: }
                   4293: 
1.504     albertel 4294: sub get_first_access {
1.1162    raeburn  4295:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4296:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4297:     if ($argsymb) { $symb=$argsymb; }
                   4298:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4299:     if ($argmap) { $map = $argmap; }
1.926     albertel 4300:     if ($type eq 'course') {
                   4301: 	$res='course';
                   4302:     } elsif ($type eq 'map') {
1.588     albertel 4303: 	$res=&symbread($map);
                   4304:     } else {
                   4305: 	$res=$symb;
                   4306:     }
1.1153    www      4307:     &load_all_first_access($uname,$udom);
                   4308:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4309: }
                   4310: 
                   4311: sub set_first_access {
1.1162    raeburn  4312:     my ($type,$interval)=@_;
1.790     albertel 4313:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4314:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4315:     if ($type eq 'course') {
                   4316: 	$res='course';
                   4317:     } elsif ($type eq 'map') {
1.588     albertel 4318: 	$res=&symbread($map);
                   4319:     } else {
                   4320: 	$res=$symb;
                   4321:     }
1.1153    www      4322:     $cachedkey='';
1.1162    raeburn  4323:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4324:     if (!$firstaccess) {
1.1162    raeburn  4325:         my $start = time;
                   4326: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4327:                           $udom,$uname);
                   4328:         if ($putres eq 'ok') {
                   4329:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4330:                  $udom,$uname); 
                   4331:             &appenv(
                   4332:                      {
                   4333:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4334:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4335:                      }
                   4336:                   );
                   4337:         }
                   4338:         return $putres;
1.505     albertel 4339:     }
                   4340:     return 'already_set';
1.504     albertel 4341: }
1.1153    www      4342: }
1.110     www      4343: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4344: 
                   4345: sub expirespread {
                   4346:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4347:     my $cid=$env{'request.course.id'}; 
1.110     www      4348:     if ($cid) {
                   4349:        my $now=time;
                   4350:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4351:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4352:                             $env{'course.'.$cid.'.num'}.
1.110     www      4353: 	        	    ':nohist_expirationdates:'.
                   4354:                             &escape($key).'='.$now,
1.620     albertel 4355:                             $env{'course.'.$cid.'.home'})
1.110     www      4356:     }
                   4357:     return 'ok';
1.14      www      4358: }
                   4359: 
1.109     www      4360: # ----------------------------------------------------- Devalidate Spreadsheets
                   4361: 
                   4362: sub devalidate {
1.325     www      4363:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4364:     my $cid=$env{'request.course.id'}; 
1.109     www      4365:     if ($cid) {
1.391     matthew  4366:         # delete the stored spreadsheets for
                   4367:         # - the student level sheet of this user in course's homespace
                   4368:         # - the assessment level sheet for this resource 
                   4369:         #   for this user in user's homespace
1.553     albertel 4370: 	# - current conditional state info
1.325     www      4371: 	my $key=$uname.':'.$udom.':';
1.109     www      4372:         my $status=
1.299     matthew  4373: 	    &del('nohist_calculatedsheets',
1.391     matthew  4374: 		 [$key.'studentcalc:'],
1.620     albertel 4375: 		 $env{'course.'.$cid.'.domain'},
                   4376: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4377: 		.' '.
                   4378: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4379: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4380:         unless ($status eq 'ok ok') {
                   4381:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4382:                     $uname.' at '.$udom.' for '.
1.109     www      4383: 		    $symb.': '.$status);
1.133     albertel 4384:         }
1.553     albertel 4385: 	&delenv('user.state.'.$cid);
1.109     www      4386:     }
                   4387: }
                   4388: 
1.265     albertel 4389: sub get_scalar {
                   4390:     my ($string,$end) = @_;
                   4391:     my $value;
                   4392:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4393: 	$value = $1;
                   4394:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4395: 	$value = $1;
                   4396:     }
                   4397:     return &unescape($value);
                   4398: }
                   4399: 
                   4400: sub array2str {
                   4401:   my (@array) = @_;
                   4402:   my $result=&arrayref2str(\@array);
                   4403:   $result=~s/^__ARRAY_REF__//;
                   4404:   $result=~s/__END_ARRAY_REF__$//;
                   4405:   return $result;
                   4406: }
                   4407: 
1.204     albertel 4408: sub arrayref2str {
                   4409:   my ($arrayref) = @_;
1.265     albertel 4410:   my $result='__ARRAY_REF__';
1.204     albertel 4411:   foreach my $elem (@$arrayref) {
1.265     albertel 4412:     if(ref($elem) eq 'ARRAY') {
                   4413:       $result.=&arrayref2str($elem).'&';
                   4414:     } elsif(ref($elem) eq 'HASH') {
                   4415:       $result.=&hashref2str($elem).'&';
                   4416:     } elsif(ref($elem)) {
                   4417:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4418:     } else {
                   4419:       $result.=&escape($elem).'&';
                   4420:     }
                   4421:   }
                   4422:   $result=~s/\&$//;
1.265     albertel 4423:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4424:   return $result;
                   4425: }
                   4426: 
1.168     albertel 4427: sub hash2str {
1.204     albertel 4428:   my (%hash) = @_;
                   4429:   my $result=&hashref2str(\%hash);
1.265     albertel 4430:   $result=~s/^__HASH_REF__//;
                   4431:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4432:   return $result;
                   4433: }
                   4434: 
                   4435: sub hashref2str {
                   4436:   my ($hashref)=@_;
1.265     albertel 4437:   my $result='__HASH_REF__';
1.800     albertel 4438:   foreach my $key (sort(keys(%$hashref))) {
                   4439:     if (ref($key) eq 'ARRAY') {
                   4440:       $result.=&arrayref2str($key).'=';
                   4441:     } elsif (ref($key) eq 'HASH') {
                   4442:       $result.=&hashref2str($key).'=';
                   4443:     } elsif (ref($key)) {
1.265     albertel 4444:       $result.='=';
1.800     albertel 4445:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4446:     } else {
1.1132    raeburn  4447: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4448:     }
                   4449: 
1.800     albertel 4450:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4451:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4452:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4453:       $result.=&hashref2str($hashref->{$key}).'&';
                   4454:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4455:        $result.='&';
1.800     albertel 4456:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4457:     } else {
1.800     albertel 4458:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4459:     }
                   4460:   }
1.168     albertel 4461:   $result=~s/\&$//;
1.265     albertel 4462:   $result .= '__END_HASH_REF__';
1.168     albertel 4463:   return $result;
                   4464: }
                   4465: 
                   4466: sub str2hash {
1.265     albertel 4467:     my ($string)=@_;
                   4468:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4469:     return %$hash;
                   4470: }
                   4471: 
                   4472: sub str2hashref {
1.168     albertel 4473:   my ($string) = @_;
1.265     albertel 4474: 
                   4475:   my %hash;
                   4476: 
                   4477:   if($string !~ /^__HASH_REF__/) {
                   4478:       if (! ($string eq '' || !defined($string))) {
                   4479: 	  $hash{'error'}='Not hash reference';
                   4480:       }
                   4481:       return (\%hash, $string);
                   4482:   }
                   4483: 
                   4484:   $string =~ s/^__HASH_REF__//;
                   4485: 
                   4486:   while($string !~ /^__END_HASH_REF__/) {
                   4487:       #key
                   4488:       my $key='';
                   4489:       if($string =~ /^__HASH_REF__/) {
                   4490:           ($key, $string)=&str2hashref($string);
                   4491:           if(defined($key->{'error'})) {
                   4492:               $hash{'error'}='Bad data';
                   4493:               return (\%hash, $string);
                   4494:           }
                   4495:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4496:           ($key, $string)=&str2arrayref($string);
                   4497:           if($key->[0] eq 'Array reference error') {
                   4498:               $hash{'error'}='Bad data';
                   4499:               return (\%hash, $string);
                   4500:           }
                   4501:       } else {
                   4502:           $string =~ s/^(.*?)=//;
1.267     albertel 4503: 	  $key=&unescape($1);
1.265     albertel 4504:       }
                   4505:       $string =~ s/^=//;
                   4506: 
                   4507:       #value
                   4508:       my $value='';
                   4509:       if($string =~ /^__HASH_REF__/) {
                   4510:           ($value, $string)=&str2hashref($string);
                   4511:           if(defined($value->{'error'})) {
                   4512:               $hash{'error'}='Bad data';
                   4513:               return (\%hash, $string);
                   4514:           }
                   4515:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4516:           ($value, $string)=&str2arrayref($string);
                   4517:           if($value->[0] eq 'Array reference error') {
                   4518:               $hash{'error'}='Bad data';
                   4519:               return (\%hash, $string);
                   4520:           }
                   4521:       } else {
                   4522: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4523:       }
                   4524:       $string =~ s/^&//;
                   4525: 
                   4526:       $hash{$key}=$value;
1.204     albertel 4527:   }
1.265     albertel 4528: 
                   4529:   $string =~ s/^__END_HASH_REF__//;
                   4530: 
                   4531:   return (\%hash, $string);
1.204     albertel 4532: }
                   4533: 
                   4534: sub str2array {
1.265     albertel 4535:     my ($string)=@_;
                   4536:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4537:     return @$array;
                   4538: }
                   4539: 
                   4540: sub str2arrayref {
1.204     albertel 4541:   my ($string) = @_;
1.265     albertel 4542:   my @array;
                   4543: 
                   4544:   if($string !~ /^__ARRAY_REF__/) {
                   4545:       if (! ($string eq '' || !defined($string))) {
                   4546: 	  $array[0]='Array reference error';
                   4547:       }
                   4548:       return (\@array, $string);
                   4549:   }
                   4550: 
                   4551:   $string =~ s/^__ARRAY_REF__//;
                   4552: 
                   4553:   while($string !~ /^__END_ARRAY_REF__/) {
                   4554:       my $value='';
                   4555:       if($string =~ /^__HASH_REF__/) {
                   4556:           ($value, $string)=&str2hashref($string);
                   4557:           if(defined($value->{'error'})) {
                   4558:               $array[0] ='Array reference error';
                   4559:               return (\@array, $string);
                   4560:           }
                   4561:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4562:           ($value, $string)=&str2arrayref($string);
                   4563:           if($value->[0] eq 'Array reference error') {
                   4564:               $array[0] ='Array reference error';
                   4565:               return (\@array, $string);
                   4566:           }
                   4567:       } else {
                   4568: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4569:       }
                   4570:       $string =~ s/^&//;
                   4571: 
                   4572:       push(@array, $value);
1.191     harris41 4573:   }
1.265     albertel 4574: 
                   4575:   $string =~ s/^__END_ARRAY_REF__//;
                   4576: 
                   4577:   return (\@array, $string);
1.168     albertel 4578: }
                   4579: 
1.167     albertel 4580: # -------------------------------------------------------------------Temp Store
                   4581: 
1.168     albertel 4582: sub tmpreset {
                   4583:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4584:   if (!$symb) {
                   4585:     $symb=&symbread();
1.620     albertel 4586:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4587:   }
                   4588:   $symb=escape($symb);
                   4589: 
1.620     albertel 4590:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4591:   $namespace=~s/\//\_/g;
                   4592:   $namespace=~s/\W//g;
                   4593: 
1.620     albertel 4594:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4595:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4596:   if ($domain eq 'public' && $stuname eq 'public') {
                   4597:       $stuname=$ENV{'REMOTE_ADDR'};
                   4598:   }
1.1117    foxr     4599:   my $path=LONCAPA::tempdir();
1.168     albertel 4600:   my %hash;
                   4601:   if (tie(%hash,'GDBM_File',
                   4602: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4603: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4604:     foreach my $key (keys(%hash)) {
1.180     albertel 4605:       if ($key=~ /:$symb/) {
1.168     albertel 4606: 	delete($hash{$key});
                   4607:       }
                   4608:     }
                   4609:   }
                   4610: }
                   4611: 
1.167     albertel 4612: sub tmpstore {
1.168     albertel 4613:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4614: 
                   4615:   if (!$symb) {
                   4616:     $symb=&symbread();
1.620     albertel 4617:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4618:   }
                   4619:   $symb=escape($symb);
                   4620: 
                   4621:   if (!$namespace) {
                   4622:     # I don't think we would ever want to store this for a course.
                   4623:     # it seems this will only be used if we don't have a course.
1.620     albertel 4624:     #$namespace=$env{'request.course.id'};
1.168     albertel 4625:     #if (!$namespace) {
1.620     albertel 4626:       $namespace=$env{'request.state'};
1.168     albertel 4627:     #}
                   4628:   }
                   4629:   $namespace=~s/\//\_/g;
                   4630:   $namespace=~s/\W//g;
1.620     albertel 4631:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4632:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4633:   if ($domain eq 'public' && $stuname eq 'public') {
                   4634:       $stuname=$ENV{'REMOTE_ADDR'};
                   4635:   }
1.168     albertel 4636:   my $now=time;
                   4637:   my %hash;
1.1117    foxr     4638:   my $path=LONCAPA::tempdir();
1.168     albertel 4639:   if (tie(%hash,'GDBM_File',
                   4640: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4641: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4642:     $hash{"version:$symb"}++;
                   4643:     my $version=$hash{"version:$symb"};
                   4644:     my $allkeys=''; 
                   4645:     foreach my $key (keys(%$storehash)) {
                   4646:       $allkeys.=$key.':';
1.591     albertel 4647:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4648:     }
                   4649:     $hash{"$version:$symb:timestamp"}=$now;
                   4650:     $allkeys.='timestamp';
                   4651:     $hash{"$version:keys:$symb"}=$allkeys;
                   4652:     if (untie(%hash)) {
                   4653:       return 'ok';
                   4654:     } else {
                   4655:       return "error:$!";
                   4656:     }
                   4657:   } else {
                   4658:     return "error:$!";
                   4659:   }
                   4660: }
1.167     albertel 4661: 
1.168     albertel 4662: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4663: 
1.168     albertel 4664: sub tmprestore {
                   4665:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4666: 
1.168     albertel 4667:   if (!$symb) {
                   4668:     $symb=&symbread();
1.620     albertel 4669:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4670:   }
                   4671:   $symb=escape($symb);
                   4672: 
1.620     albertel 4673:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4674: 
1.620     albertel 4675:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4676:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4677:   if ($domain eq 'public' && $stuname eq 'public') {
                   4678:       $stuname=$ENV{'REMOTE_ADDR'};
                   4679:   }
1.168     albertel 4680:   my %returnhash;
                   4681:   $namespace=~s/\//\_/g;
                   4682:   $namespace=~s/\W//g;
                   4683:   my %hash;
1.1117    foxr     4684:   my $path=LONCAPA::tempdir();
1.168     albertel 4685:   if (tie(%hash,'GDBM_File',
                   4686: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4687: 	  &GDBM_READER(),0640)) {
1.168     albertel 4688:     my $version=$hash{"version:$symb"};
                   4689:     $returnhash{'version'}=$version;
                   4690:     my $scope;
                   4691:     for ($scope=1;$scope<=$version;$scope++) {
                   4692:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4693:       my @keys=split(/:/,$vkeys);
                   4694:       my $key;
                   4695:       $returnhash{"$scope:keys"}=$vkeys;
                   4696:       foreach $key (@keys) {
1.591     albertel 4697: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4698: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4699:       }
                   4700:     }
1.168     albertel 4701:     if (!(untie(%hash))) {
                   4702:       return "error:$!";
                   4703:     }
                   4704:   } else {
                   4705:     return "error:$!";
                   4706:   }
                   4707:   return %returnhash;
1.167     albertel 4708: }
                   4709: 
1.9       www      4710: # ----------------------------------------------------------------------- Store
                   4711: 
                   4712: sub store {
1.124     www      4713:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4714:     my $home='';
                   4715: 
1.168     albertel 4716:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4717: 
1.213     www      4718:     $symb=&symbclean($symb);
1.122     albertel 4719:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4720: 
1.620     albertel 4721:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4722:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4723: 
                   4724:     &devalidate($symb,$stuname,$domain);
1.109     www      4725: 
                   4726:     $symb=escape($symb);
1.187     www      4727:     if (!$namespace) { 
1.620     albertel 4728:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4729:           return ''; 
                   4730:        } 
                   4731:     }
1.620     albertel 4732:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4733: 
                   4734:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4735:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4736: 
1.12      www      4737:     my $namevalue='';
1.800     albertel 4738:     foreach my $key (keys(%$storehash)) {
                   4739:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4740:     }
1.12      www      4741:     $namevalue=~s/\&$//;
1.187     www      4742:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4743:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4744: }
                   4745: 
1.47      www      4746: # -------------------------------------------------------------- Critical Store
                   4747: 
                   4748: sub cstore {
1.124     www      4749:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4750:     my $home='';
                   4751: 
1.168     albertel 4752:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4753: 
1.213     www      4754:     $symb=&symbclean($symb);
1.122     albertel 4755:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4756: 
1.620     albertel 4757:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4758:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4759: 
                   4760:     &devalidate($symb,$stuname,$domain);
1.109     www      4761: 
                   4762:     $symb=escape($symb);
1.187     www      4763:     if (!$namespace) { 
1.620     albertel 4764:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4765:           return ''; 
                   4766:        } 
                   4767:     }
1.620     albertel 4768:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4769: 
                   4770:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4771:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4772: 
1.47      www      4773:     my $namevalue='';
1.800     albertel 4774:     foreach my $key (keys(%$storehash)) {
                   4775:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4776:     }
1.47      www      4777:     $namevalue=~s/\&$//;
1.187     www      4778:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4779:     return critical
                   4780:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4781: }
                   4782: 
1.9       www      4783: # --------------------------------------------------------------------- Restore
                   4784: 
                   4785: sub restore {
1.124     www      4786:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4787:     my $home='';
                   4788: 
1.168     albertel 4789:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4790: 
1.122     albertel 4791:     if (!$symb) {
                   4792:       unless ($symb=escape(&symbread())) { return ''; }
                   4793:     } else {
1.213     www      4794:       $symb=&escape(&symbclean($symb));
1.122     albertel 4795:     }
1.188     www      4796:     if (!$namespace) { 
1.620     albertel 4797:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4798:           return ''; 
                   4799:        } 
                   4800:     }
1.620     albertel 4801:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4802:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4803:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4804:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4805: 
1.12      www      4806:     my %returnhash=();
1.800     albertel 4807:     foreach my $line (split(/\&/,$answer)) {
                   4808: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4809:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4810:     }
1.75      www      4811:     my $version;
                   4812:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4813:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4814:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4815:        }
1.75      www      4816:     }
1.13      www      4817:     return %returnhash;
1.34      www      4818: }
                   4819: 
                   4820: # ---------------------------------------------------------- Course Description
1.1118    foxr     4821: #
                   4822: #  
1.34      www      4823: 
                   4824: sub coursedescription {
1.731     albertel 4825:     my ($courseid,$args)=@_;
1.34      www      4826:     $courseid=~s/^\///;
1.49      www      4827:     $courseid=~s/\_/\//g;
1.34      www      4828:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4829:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4830:     my $normalid=$cdomain.'_'.$cnum;
                   4831:     # need to always cache even if we get errors otherwise we keep 
                   4832:     # trying and trying and trying to get the course description.
                   4833:     my %envhash=();
                   4834:     my %returnhash=();
1.731     albertel 4835:     
                   4836:     my $expiretime=600;
                   4837:     if ($env{'request.course.id'} eq $normalid) {
                   4838: 	$expiretime=120;
                   4839:     }
                   4840: 
                   4841:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4842:     if (!$args->{'freshen_cache'}
                   4843: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4844: 	foreach my $key (keys(%env)) {
                   4845: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4846: 	    my ($setting) = $1;
                   4847: 	    $returnhash{$setting} = $env{$key};
                   4848: 	}
                   4849: 	return %returnhash;
                   4850:     }
                   4851: 
1.1118    foxr     4852:     # get the data again
                   4853: 
1.731     albertel 4854:     if (!$args->{'one_time'}) {
                   4855: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4856:     }
1.811     albertel 4857: 
1.34      www      4858:     if ($chome ne 'no_host') {
1.302     albertel 4859:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4860:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4861: 	   my $username = $env{'user.name'}; # Defult username
                   4862: 	   if(defined $args->{'user'}) {
                   4863: 	       $username = $args->{'user'};
                   4864: 	   }
1.129     albertel 4865:            $returnhash{'home'}= $chome;
                   4866: 	   $returnhash{'domain'} = $cdomain;
                   4867: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4868:            if (!defined($returnhash{'type'})) {
                   4869:                $returnhash{'type'} = 'Course';
                   4870:            }
1.130     albertel 4871:            while (my ($name,$value) = each %returnhash) {
1.53      www      4872:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4873:            }
1.270     www      4874:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4875:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4876: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4877:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4878:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4879:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4880:        }
                   4881:     }
1.731     albertel 4882:     if (!$args->{'one_time'}) {
1.949     raeburn  4883: 	&appenv(\%envhash);
1.731     albertel 4884:     }
1.302     albertel 4885:     return %returnhash;
1.461     www      4886: }
                   4887: 
1.1080    raeburn  4888: sub update_released_required {
                   4889:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4890:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4891:         $cid = $env{'request.course.id'};
                   4892:         $cdom = $env{'course.'.$cid.'.domain'};
                   4893:         $cnum = $env{'course.'.$cid.'.num'};
                   4894:         $chome = $env{'course.'.$cid.'.home'};
                   4895:     }
                   4896:     if ($needsrelease) {
                   4897:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4898:         my $needsupdate;
                   4899:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4900:             $needsupdate = 1;
                   4901:         } else {
                   4902:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4903:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4904:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4905:                 $needsupdate = 1;
                   4906:             }
                   4907:         }
                   4908:         if ($needsupdate) {
                   4909:             my %needshash = (
                   4910:                              'internal.releaserequired' => $needsrelease,
                   4911:                             );
                   4912:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4913:             if ($putresult eq 'ok') {
                   4914:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4915:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4916:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4917:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4918:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4919:                 }
                   4920:             }
                   4921:         }
                   4922:     }
                   4923:     return;
                   4924: }
                   4925: 
1.461     www      4926: # -------------------------------------------------See if a user is privileged
                   4927: 
                   4928: sub privileged {
                   4929:     my ($username,$domain)=@_;
1.1170    droeschl 4930: 
                   4931:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4932:     my $now = time;
                   4933: 
                   4934:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4935:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4936:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4937:                 return 1 unless ($tend && $tend < $now) 
                   4938:                     or ($tstart && $tstart > $now);
                   4939:             }
1.461     www      4940: 	}
1.1170    droeschl 4941: 
1.461     www      4942:     return 0;
1.9       www      4943: }
1.1       albertel 4944: 
1.103     harris41 4945: # -------------------------------------------------------- Get user privileges
1.11      www      4946: 
                   4947: sub rolesinit {
1.1169    droeschl 4948:     my ($domain, $username) = @_;
                   4949:     my %userroles = ('user.login.time' => time);
                   4950:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4951: 
                   4952:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4953:     # also, blocking can be triggered by an activating timer
                   4954:     # it's saved in the user's %env.
                   4955:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4956:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4957:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4958:         %timerintchk, %timerintenv);
                   4959: 
1.1162    raeburn  4960:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4961:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4962:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4963:     }
1.1169    droeschl 4964: 
1.1162    raeburn  4965:     foreach my $key (keys(%timerinterval)) {
                   4966:         my ($cid,$rest) = split(/\0/,$key);
                   4967:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4968:     }
1.1169    droeschl 4969: 
1.11      www      4970:     my %allroles=();
1.1162    raeburn  4971:     my %allgroups=();
1.11      www      4972: 
1.1169    droeschl 4973:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4974:         my $role = $rolesdump{$area};
                   4975:         $area =~ s/\_\w\w$//;
                   4976: 
                   4977:         my ($trole, $tend, $tstart, $group_privs);
                   4978: 
                   4979:         if ($role =~ /^cr/) {
                   4980:         # Custom role, defined by a user 
                   4981:         # e.g., user.role.cr/msu/smith/mynewrole
                   4982:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4983:                 $trole = $1;
                   4984:                 ($tend, $tstart) = split('_', $2);
                   4985:             } else {
                   4986:                 $trole = $role;
                   4987:             }
                   4988:         } elsif ($role =~ m|^gr/|) {
                   4989:         # Role of member in a group, defined within a course/community
                   4990:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4991:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4992:             next if $tstart eq '-1';
                   4993:             ($trole, $group_privs) = split(/\//, $trole);
                   4994:             $group_privs = &unescape($group_privs);
                   4995:         } else {
                   4996:         # Just a normal role, defined in roles.tab
                   4997:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4998:         }
                   4999: 
                   5000:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5001:                  $username);
                   5002:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5003: 
                   5004:         # role expired or not available yet?
                   5005:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5006:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5007: 
                   5008:         next if $area eq '' or $trole eq '';
                   5009: 
                   5010:         my $spec = "$trole.$area";
                   5011:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5012: 
                   5013:         if ($trole =~ /^cr\//) {
                   5014:         # Custom role, defined by a user
                   5015:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5016:         } elsif ($trole eq 'gr') {
                   5017:         # Role of a member in a group, defined within a course/community
                   5018:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5019:             next;
                   5020:         } else {
                   5021:         # Normal role, defined in roles.tab
                   5022:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5023:         }
                   5024: 
                   5025:         my $cid = $tdomain.'_'.$trest;
                   5026:         unless ($firstaccchk{$cid}) {
                   5027:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5028:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5029:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5030:                         $coursetimerstarts{$cid}{$item}; 
                   5031:                 }
                   5032:             }
                   5033:             $firstaccchk{$cid} = 1;
                   5034:         }
                   5035:         unless ($timerintchk{$cid}) {
                   5036:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5037:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5038:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5039:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5040:                 }
1.12      www      5041:             }
1.1169    droeschl 5042:             $timerintchk{$cid} = 1;
1.191     harris41 5043:         }
1.11      www      5044:     }
1.1169    droeschl 5045: 
                   5046:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5047:         \%allroles, \%allgroups);
                   5048:     $env{'user.adv'} = $userroles{'user.adv'};
                   5049: 
1.1162    raeburn  5050:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5051: }
                   5052: 
1.567     raeburn  5053: sub set_arearole {
1.1172.2.19  raeburn  5054:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5055:     unless ($nolog) {
1.567     raeburn  5056: # log the associated role with the area
1.1172.2.19  raeburn  5057:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5058:     }
1.743     albertel 5059:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5060: }
                   5061: 
                   5062: sub custom_roleprivs {
                   5063:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5064:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5065:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5066:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5067:         my ($rdummy,$roledef)=
                   5068:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5069:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5070:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5071:             if (defined($syspriv)) {
1.1043    raeburn  5072:                 if ($trest =~ /^$match_community$/) {
                   5073:                     $syspriv =~ s/bre\&S//; 
                   5074:                 }
1.567     raeburn  5075:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5076:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5077:             }
                   5078:             if ($tdomain ne '') {
                   5079:                 if (defined($dompriv)) {
                   5080:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5081:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5082:                 }
                   5083:                 if (($trest ne '') && (defined($coursepriv))) {
                   5084:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5085:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5086:                 }
                   5087:             }
                   5088:         }
                   5089:     }
                   5090: }
                   5091: 
1.678     raeburn  5092: sub group_roleprivs {
                   5093:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5094:     my $access = 1;
                   5095:     my $now = time;
                   5096:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5097:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5098:     if ($access) {
1.811     albertel 5099:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5100:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5101:     }
                   5102: }
1.567     raeburn  5103: 
                   5104: sub standard_roleprivs {
                   5105:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5106:     if (defined($pr{$trole.':s'})) {
                   5107:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5108:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5109:     }
                   5110:     if ($tdomain ne '') {
                   5111:         if (defined($pr{$trole.':d'})) {
                   5112:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5113:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5114:         }
                   5115:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5116:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5117:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5118:         }
                   5119:     }
                   5120: }
                   5121: 
                   5122: sub set_userprivs {
1.1064    raeburn  5123:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5124:     my $author=0;
                   5125:     my $adv=0;
1.678     raeburn  5126:     my %grouproles = ();
                   5127:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5128:         my @groupkeys; 
1.1000    raeburn  5129:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5130:             push(@groupkeys,$role);
                   5131:         }
                   5132:         if (ref($groups_roles) eq 'HASH') {
                   5133:             foreach my $key (keys(%{$groups_roles})) {
                   5134:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5135:                     push(@groupkeys,$key);
                   5136:                 }
                   5137:             }
                   5138:         }
                   5139:         if (@groupkeys > 0) {
                   5140:             foreach my $role (@groupkeys) {
                   5141:                 my ($trole,$area,$sec,$extendedarea);
                   5142:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5143:                     $trole = $1;
                   5144:                     $area = $2;
                   5145:                     $sec = $3;
                   5146:                     $extendedarea = $area.$sec;
                   5147:                     if (exists($$allgroups{$area})) {
                   5148:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5149:                             my $spec = $trole.'.'.$extendedarea;
                   5150:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5151:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5152:                         }
1.678     raeburn  5153:                     }
                   5154:                 }
                   5155:             }
                   5156:         }
                   5157:     }
1.800     albertel 5158:     foreach my $group (keys(%grouproles)) {
                   5159:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5160:     }
1.800     albertel 5161:     foreach my $role (keys(%{$allroles})) {
                   5162:         my %thesepriv;
1.941     raeburn  5163:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5164:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5165:             if ($item ne '') {
                   5166:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5167:                 if ($restrictions eq '') {
                   5168:                     $thesepriv{$privilege}='F';
                   5169:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5170:                     $thesepriv{$privilege}.=$restrictions;
                   5171:                 }
                   5172:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5173:             }
                   5174:         }
                   5175:         my $thesestr='';
1.1104    raeburn  5176:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5177: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5178: 	}
                   5179:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5180:     }
                   5181:     return ($author,$adv);
                   5182: }
                   5183: 
1.994     raeburn  5184: sub role_status {
1.1104    raeburn  5185:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5186:     my @pwhere = ();
                   5187:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5188:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5189:         unless (!defined($$role) || $$role eq '') {
                   5190:             $$where=join('.',@pwhere);
                   5191:             $$trolecode=$$role.'.'.$$where;
                   5192:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5193:             $$tstatus='is';
1.1104    raeburn  5194:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5195:                 $$tstatus='future';
1.1034    raeburn  5196:                 if ($$tstart<$now) {
                   5197:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5198:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5199:                             my (%allroles,%allgroups,$group_privs,
                   5200:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5201:                             my %userroles = (
                   5202:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5203:                             );
1.1064    raeburn  5204:                             @rolecodes = ('cm'); 
1.1002    raeburn  5205:                             my $spec=$$role.'.'.$$where;
                   5206:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5207:                             if ($$role =~ /^cr\//) {
                   5208:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5209:                                 push(@rolecodes,'cr');
1.1002    raeburn  5210:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5211:                                 push(@rolecodes,$$role);
1.1002    raeburn  5212:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5213:                                                     $env{'user.name'});
1.1064    raeburn  5214:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5215:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5216:                                 $group_privs = &unescape($group_privs);
                   5217:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5218:                                 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  5219:                                 &get_groups_roles($tdomain,$trest,
                   5220:                                                   \%course_roles,\@rolecodes,
                   5221:                                                   \%groups_roles);
1.1002    raeburn  5222:                             } else {
1.1064    raeburn  5223:                                 push(@rolecodes,$$role);
1.1002    raeburn  5224:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5225:                             }
1.1064    raeburn  5226:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5227:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5228:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5229:                         }
                   5230:                     }
1.1034    raeburn  5231:                     $$tstatus = 'is';
1.1002    raeburn  5232:                 }
1.994     raeburn  5233:             }
                   5234:             if ($$tend) {
1.1104    raeburn  5235:                 if ($$tend<$update) {
1.994     raeburn  5236:                     $$tstatus='expired';
                   5237:                 } elsif ($$tend<$now) {
                   5238:                     $$tstatus='will_not';
                   5239:                 }
                   5240:             }
                   5241:         }
                   5242:     }
                   5243: }
                   5244: 
1.1104    raeburn  5245: sub get_groups_roles {
                   5246:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5247:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5248:                   (ref($rolecodes) eq 'ARRAY') && 
                   5249:                   (ref($groups_roles) eq 'HASH')); 
                   5250:     if (keys(%{$cdom_courseroles}) > 0) {
                   5251:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5252:         if ($cdom ne '' && $cnum ne '') {
                   5253:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5254:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5255:                     my $crsrole = $1;
                   5256:                     my $crssec = $2;
                   5257:                     if ($crsrole =~ /^cr/) {
                   5258:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5259:                             push(@{$rolecodes},'cr');
                   5260:                         }
                   5261:                     } else {
                   5262:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5263:                             push(@{$rolecodes},$crsrole);
                   5264:                         }
                   5265:                     }
                   5266:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5267:                     if ($crssec ne '') {
                   5268:                         $rolekey .= "/$crssec";
                   5269:                     }
                   5270:                     $rolekey .= './';
                   5271:                     $groups_roles->{$rolekey} = $rolecodes;
                   5272:                 }
                   5273:             }
                   5274:         }
                   5275:     }
                   5276:     return;
                   5277: }
                   5278: 
                   5279: sub delete_env_groupprivs {
                   5280:     my ($where,$courseroles,$possroles) = @_;
                   5281:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5282:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5283:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5284:         %{$courseroles->{$udom}} =
                   5285:             &get_my_roles('','','userroles',['active'],
                   5286:                           $possroles,[$udom],1);
                   5287:     }
                   5288:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5289:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5290:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5291:             my $area = '/'.$cdom.'/'.$cnum;
                   5292:             my $privkey = "user.priv.$crsrole.$area";
                   5293:             if ($crssec ne '') {
                   5294:                 $privkey .= '/'.$crssec;
                   5295:             }
                   5296:             $privkey .= ".$area/$group";
                   5297:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5298:         }
                   5299:     }
                   5300:     return;
                   5301: }
                   5302: 
1.994     raeburn  5303: sub check_adhoc_privs {
1.1104    raeburn  5304:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5305:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5306:     my $setprivs;
1.994     raeburn  5307:     if ($env{$cckey}) {
                   5308:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5309:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5310:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5311:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5312:             $setprivs = 1;
1.994     raeburn  5313:         }
                   5314:     } else {
1.1088    raeburn  5315:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5316:         $setprivs = 1;
1.994     raeburn  5317:     }
1.1172.2.9  raeburn  5318:     return $setprivs;
1.994     raeburn  5319: }
                   5320: 
                   5321: sub set_adhoc_privileges {
                   5322: # role can be cc or ca
1.1088    raeburn  5323:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5324:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5325:     my $spec = $role.'.'.$area;
                   5326:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5327:                                   $env{'user.name'},1);
1.994     raeburn  5328:     my %ccrole = ();
                   5329:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5330:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5331:     &appenv(\%userroles,[$role,'cm']);
                   5332:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5333:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5334:         &appenv( {'request.role'        => $spec,
                   5335:                   'request.role.domain' => $dcdom,
                   5336:                   'request.course.sec'  => ''
                   5337:                  }
                   5338:                );
                   5339:         my $tadv=0;
                   5340:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5341:         &appenv({'request.role.adv'    => $tadv});
                   5342:     }
1.994     raeburn  5343: }
                   5344: 
1.12      www      5345: # --------------------------------------------------------------- get interface
                   5346: 
                   5347: sub get {
1.131     albertel 5348:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5349:    my $items='';
1.800     albertel 5350:    foreach my $item (@$storearr) {
                   5351:        $items.=&escape($item).'&';
1.191     harris41 5352:    }
1.12      www      5353:    $items=~s/\&$//;
1.620     albertel 5354:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5355:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5356:    my $uhome=&homeserver($uname,$udomain);
                   5357: 
1.133     albertel 5358:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5359:    my @pairs=split(/\&/,$rep);
1.273     albertel 5360:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5361:      return @pairs;
                   5362:    }
1.15      www      5363:    my %returnhash=();
1.42      www      5364:    my $i=0;
1.800     albertel 5365:    foreach my $item (@$storearr) {
                   5366:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5367:       $i++;
1.191     harris41 5368:    }
1.15      www      5369:    return %returnhash;
1.27      www      5370: }
                   5371: 
                   5372: # --------------------------------------------------------------- del interface
                   5373: 
                   5374: sub del {
1.133     albertel 5375:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5376:    my $items='';
1.800     albertel 5377:    foreach my $item (@$storearr) {
                   5378:        $items.=&escape($item).'&';
1.191     harris41 5379:    }
1.984     neumanie 5380: 
1.27      www      5381:    $items=~s/\&$//;
1.620     albertel 5382:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5383:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5384:    my $uhome=&homeserver($uname,$udomain);
                   5385:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5386: }
                   5387: 
                   5388: # -------------------------------------------------------------- dump interface
                   5389: 
                   5390: sub dump {
1.1166    raeburn  5391:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5392:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5393:     if (!$uname) { $uname=$env{'user.name'}; }
                   5394:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5395: 
1.755     albertel 5396:     if ($regexp) {
                   5397: 	$regexp=&escape($regexp);
                   5398:     } else {
                   5399: 	$regexp='.';
                   5400:     }
1.1166    raeburn  5401:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5402:     my @pairs=split(/\&/,$rep);
                   5403:     my %returnhash=();
1.1098    foxr     5404:     if (!($rep =~ /^error/ )) {
                   5405: 	foreach my $item (@pairs) {
                   5406: 	    my ($key,$value)=split(/=/,$item,2);
                   5407: 	    $key = &unescape($key);
                   5408: 	    next if ($key =~ /^error: 2 /);
                   5409: 	    $returnhash{$key}=&thaw_unescape($value);
                   5410: 	}
1.755     albertel 5411:     }
                   5412:     return %returnhash;
1.407     www      5413: }
                   5414: 
1.1098    foxr     5415: 
1.717     albertel 5416: # --------------------------------------------------------- dumpstore interface
                   5417: 
                   5418: sub dumpstore {
                   5419:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5420:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5421:    if (!$uname) { $uname=$env{'user.name'}; }
                   5422:    my $uhome=&homeserver($uname,$udomain);
                   5423:    if ($regexp) {
                   5424:        $regexp=&escape($regexp);
                   5425:    } else {
                   5426:        $regexp='.';
                   5427:    }
                   5428:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5429:    my @pairs=split(/\&/,$rep);
                   5430:    my %returnhash=();
                   5431:    foreach my $item (@pairs) {
                   5432:        my ($key,$value)=split(/=/,$item,2);
                   5433:        next if ($key =~ /^error: 2 /);
                   5434:        $returnhash{$key}=&thaw_unescape($value);
                   5435:    }
                   5436:    return %returnhash;
1.717     albertel 5437: }
                   5438: 
1.407     www      5439: # -------------------------------------------------------------- keys interface
                   5440: 
                   5441: sub getkeys {
                   5442:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5443:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5444:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5445:    my $uhome=&homeserver($uname,$udomain);
                   5446:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5447:    my @keyarray=();
1.800     albertel 5448:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5449:       next if ($key =~ /^error: 2 /);
1.800     albertel 5450:       push(@keyarray,&unescape($key));
1.407     www      5451:    }
                   5452:    return @keyarray;
1.318     matthew  5453: }
                   5454: 
1.319     matthew  5455: # --------------------------------------------------------------- currentdump
                   5456: sub currentdump {
1.328     matthew  5457:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5458:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5459:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5460:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5461:    my $uhome = &homeserver($sname,$sdom);
                   5462:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5463:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5464:    #
1.318     matthew  5465:    my %returnhash=();
1.319     matthew  5466:    #
                   5467:    if ($rep eq "unknown_cmd") { 
                   5468:        # an old lond will not know currentdump
                   5469:        # Do a dump and make it look like a currentdump
1.822     albertel 5470:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5471:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5472:        my %hash = @tmp;
                   5473:        @tmp=();
1.424     matthew  5474:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5475:    } else {
                   5476:        my @pairs=split(/\&/,$rep);
1.800     albertel 5477:        foreach my $pair (@pairs) {
                   5478:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5479:            my ($symb,$param) = split(/:/,$key);
                   5480:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5481:                                                         &thaw_unescape($value);
1.319     matthew  5482:        }
1.191     harris41 5483:    }
1.12      www      5484:    return %returnhash;
1.424     matthew  5485: }
                   5486: 
                   5487: sub convert_dump_to_currentdump{
                   5488:     my %hash = %{shift()};
                   5489:     my %returnhash;
                   5490:     # Code ripped from lond, essentially.  The only difference
                   5491:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5492:     # we might run in to problems with parameter names =~ /^v\./
                   5493:     while (my ($key,$value) = each(%hash)) {
                   5494:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5495: 	$symb  = &unescape($symb);
                   5496: 	$param = &unescape($param);
1.424     matthew  5497:         next if ($v eq 'version' || $symb eq 'keys');
                   5498:         next if (exists($returnhash{$symb}) &&
                   5499:                  exists($returnhash{$symb}->{$param}) &&
                   5500:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5501:         $returnhash{$symb}->{$param}=$value;
                   5502:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5503:     }
                   5504:     #
                   5505:     # Remove all of the keys in the hashes which keep track of
                   5506:     # the version of the parameter.
                   5507:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5508:         # use a foreach because we are going to delete from the hash.
                   5509:         foreach my $key (keys(%$param_hash)) {
                   5510:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5511:         }
                   5512:     }
                   5513:     return \%returnhash;
1.12      www      5514: }
                   5515: 
1.627     albertel 5516: # ------------------------------------------------------ critical inc interface
                   5517: 
                   5518: sub cinc {
                   5519:     return &inc(@_,'critical');
                   5520: }
                   5521: 
1.449     matthew  5522: # --------------------------------------------------------------- inc interface
                   5523: 
                   5524: sub inc {
1.627     albertel 5525:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5526:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5527:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5528:     my $uhome=&homeserver($uname,$udomain);
                   5529:     my $items='';
                   5530:     if (! ref($store)) {
                   5531:         # got a single value, so use that instead
                   5532:         $items = &escape($store).'=&';
                   5533:     } elsif (ref($store) eq 'SCALAR') {
                   5534:         $items = &escape($$store).'=&';        
                   5535:     } elsif (ref($store) eq 'ARRAY') {
                   5536:         $items = join('=&',map {&escape($_);} @{$store});
                   5537:     } elsif (ref($store) eq 'HASH') {
                   5538:         while (my($key,$value) = each(%{$store})) {
                   5539:             $items.= &escape($key).'='.&escape($value).'&';
                   5540:         }
                   5541:     }
                   5542:     $items=~s/\&$//;
1.627     albertel 5543:     if ($critical) {
                   5544: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5545:     } else {
                   5546: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5547:     }
1.449     matthew  5548: }
                   5549: 
1.12      www      5550: # --------------------------------------------------------------- put interface
                   5551: 
                   5552: sub put {
1.134     albertel 5553:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5554:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5555:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5556:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5557:    my $items='';
1.800     albertel 5558:    foreach my $item (keys(%$storehash)) {
                   5559:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5560:    }
1.12      www      5561:    $items=~s/\&$//;
1.134     albertel 5562:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5563: }
                   5564: 
1.631     albertel 5565: # ------------------------------------------------------------ newput interface
                   5566: 
                   5567: sub newput {
                   5568:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5569:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5570:    if (!$uname) { $uname=$env{'user.name'}; }
                   5571:    my $uhome=&homeserver($uname,$udomain);
                   5572:    my $items='';
                   5573:    foreach my $key (keys(%$storehash)) {
                   5574:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5575:    }
                   5576:    $items=~s/\&$//;
                   5577:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5578: }
                   5579: 
                   5580: # ---------------------------------------------------------  putstore interface
                   5581: 
1.524     raeburn  5582: sub putstore {
1.715     albertel 5583:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5584:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5585:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5586:    my $uhome=&homeserver($uname,$udomain);
                   5587:    my $items='';
1.715     albertel 5588:    foreach my $key (keys(%$storehash)) {
                   5589:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5590:    }
1.715     albertel 5591:    $items=~s/\&$//;
1.716     albertel 5592:    my $esc_symb=&escape($symb);
                   5593:    my $esc_v=&escape($version);
1.715     albertel 5594:    my $reply =
1.716     albertel 5595:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5596: 	      $uhome);
                   5597:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5598:        # gfall back to way things use to be done
1.715     albertel 5599:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5600: 			    $uname);
1.524     raeburn  5601:    }
1.715     albertel 5602:    return $reply;
                   5603: }
                   5604: 
                   5605: sub old_putstore {
1.716     albertel 5606:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5607:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5608:     if (!$uname) { $uname=$env{'user.name'}; }
                   5609:     my $uhome=&homeserver($uname,$udomain);
                   5610:     my %newstorehash;
1.800     albertel 5611:     foreach my $item (keys(%$storehash)) {
                   5612: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5613: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5614:     }
                   5615:     my $items='';
                   5616:     my %allitems = ();
1.800     albertel 5617:     foreach my $item (keys(%newstorehash)) {
                   5618: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5619: 	    my $key = $1.':keys:'.$2;
                   5620: 	    $allitems{$key} .= $3.':';
                   5621: 	}
1.800     albertel 5622: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5623:     }
1.800     albertel 5624:     foreach my $item (keys(%allitems)) {
                   5625: 	$allitems{$item} =~ s/\:$//;
                   5626: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5627:     }
                   5628:     $items=~s/\&$//;
                   5629:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5630: }
                   5631: 
1.47      www      5632: # ------------------------------------------------------ critical put interface
                   5633: 
                   5634: sub cput {
1.134     albertel 5635:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5636:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5637:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5638:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5639:    my $items='';
1.800     albertel 5640:    foreach my $item (keys(%$storehash)) {
                   5641:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5642:    }
1.47      www      5643:    $items=~s/\&$//;
1.134     albertel 5644:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5645: }
                   5646: 
                   5647: # -------------------------------------------------------------- eget interface
                   5648: 
                   5649: sub eget {
1.133     albertel 5650:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5651:    my $items='';
1.800     albertel 5652:    foreach my $item (@$storearr) {
                   5653:        $items.=&escape($item).'&';
1.191     harris41 5654:    }
1.12      www      5655:    $items=~s/\&$//;
1.620     albertel 5656:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5657:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5658:    my $uhome=&homeserver($uname,$udomain);
                   5659:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5660:    my @pairs=split(/\&/,$rep);
                   5661:    my %returnhash=();
1.42      www      5662:    my $i=0;
1.800     albertel 5663:    foreach my $item (@$storearr) {
                   5664:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5665:       $i++;
1.191     harris41 5666:    }
1.12      www      5667:    return %returnhash;
                   5668: }
                   5669: 
1.667     albertel 5670: # ------------------------------------------------------------ tmpput interface
                   5671: sub tmpput {
1.802     raeburn  5672:     my ($storehash,$server,$context)=@_;
1.667     albertel 5673:     my $items='';
1.800     albertel 5674:     foreach my $item (keys(%$storehash)) {
                   5675: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5676:     }
                   5677:     $items=~s/\&$//;
1.802     raeburn  5678:     if (defined($context)) {
                   5679:         $items .= ':'.&escape($context);
                   5680:     }
1.667     albertel 5681:     return &reply("tmpput:$items",$server);
                   5682: }
                   5683: 
                   5684: # ------------------------------------------------------------ tmpget interface
                   5685: sub tmpget {
1.688     albertel 5686:     my ($token,$server)=@_;
                   5687:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5688:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5689:     my %returnhash;
                   5690:     foreach my $item (split(/\&/,$rep)) {
                   5691: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5692:         next if ($key =~ /^error: 2 /);
1.667     albertel 5693: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5694:     }
                   5695:     return %returnhash;
                   5696: }
                   5697: 
1.1113    raeburn  5698: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5699: sub tmpdel {
                   5700:     my ($token,$server)=@_;
                   5701:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5702:     return &reply("tmpdel:$token",$server);
                   5703: }
                   5704: 
1.1172.2.13  raeburn  5705: # ------------------------------------------------------------ get_timebased_id
                   5706: 
                   5707: sub get_timebased_id {
                   5708:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5709:         $maxtries) = @_;
                   5710:     my ($newid,$error,$dellock);
                   5711:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5712:         return ('','ok','invalid call to get suffix');
                   5713:     }
                   5714: 
                   5715: # set defaults for any optional args for which values were not supplied
                   5716:     if ($who eq '') {
                   5717:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5718:     }
                   5719:     if (!$locktries) {
                   5720:         $locktries = 3;
                   5721:     }
                   5722:     if (!$maxtries) {
                   5723:         $maxtries = 10;
                   5724:     }
                   5725: 
                   5726:     if (($cdom eq '') || ($cnum eq '')) {
                   5727:         if ($env{'request.course.id'}) {
                   5728:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5729:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5730:         }
                   5731:         if (($cdom eq '') || ($cnum eq '')) {
                   5732:             return ('','ok','call to get suffix not in course context');
                   5733:         }
                   5734:     }
                   5735: 
                   5736: # construct locking item
                   5737:     my $lockhash = {
                   5738:                       $prefix."\0".'locked_'.$keyid => $who,
                   5739:                    };
                   5740:     my $tries = 0;
                   5741: 
                   5742: # attempt to get lock on nohist_$namespace file
                   5743:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5744:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5745:         $tries ++;
                   5746:         sleep 1;
                   5747:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5748:     }
                   5749: 
                   5750: # attempt to get unique identifier, based on current timestamp
                   5751:     if ($gotlock eq 'ok') {
                   5752:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5753:         my $id = time;
                   5754:         $newid = $id;
                   5755:         my $idtries = 0;
                   5756:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5757:             if ($idtype eq 'concat') {
                   5758:                 $newid = $id.$idtries;
                   5759:             } else {
                   5760:                 $newid ++;
                   5761:             }
                   5762:             $idtries ++;
                   5763:         }
                   5764:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5765:             my %new_item =  (
                   5766:                               $prefix."\0".$newid => $who,
                   5767:                             );
                   5768:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5769:                                                  $cdom,$cnum);
                   5770:             if ($putresult ne 'ok') {
                   5771:                 undef($newid);
                   5772:                 $error = 'error saving new item: '.$putresult;
                   5773:             }
                   5774:         } else {
                   5775:              $error = ('error: no unique suffix available for the new item ');
                   5776:         }
                   5777: #  remove lock
                   5778:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5779:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5780:     } else {
                   5781:         $error = "error: could not obtain lockfile\n";
                   5782:         $dellock = 'ok';
                   5783:     }
                   5784:     return ($newid,$dellock,$error);
                   5785: }
                   5786: 
1.765     albertel 5787: # -------------------------------------------------- portfolio access checking
                   5788: 
                   5789: sub portfolio_access {
1.766     albertel 5790:     my ($requrl) = @_;
1.765     albertel 5791:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5792:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5793:     if ($result) {
                   5794:         my %setters;
                   5795:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5796:             my ($startblock,$endblock) =
                   5797:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5798:             if ($startblock && $endblock) {
                   5799:                 return 'B';
                   5800:             }
                   5801:         } else {
                   5802:             my ($startblock,$endblock) =
                   5803:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5804:             if ($startblock && $endblock) {
                   5805:                 return 'B';
                   5806:             }
                   5807:         }
                   5808:     }
1.765     albertel 5809:     if ($result eq 'ok') {
1.766     albertel 5810:        return 'F';
1.765     albertel 5811:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5812:        return 'A';
1.765     albertel 5813:     }
1.766     albertel 5814:     return '';
1.765     albertel 5815: }
                   5816: 
                   5817: sub get_portfolio_access {
1.767     albertel 5818:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5819: 
                   5820:     if (!ref($access_hash)) {
                   5821: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5822: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5823: 						   $file_name);
                   5824: 	$access_hash = $access_controls{$file_name};
                   5825:     }
                   5826: 
1.765     albertel 5827:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5828:     my $now = time;
                   5829:     if (ref($access_hash) eq 'HASH') {
                   5830:         foreach my $key (keys(%{$access_hash})) {
                   5831:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5832:             if ($start > $now) {
                   5833:                 next;
                   5834:             }
                   5835:             if ($end && $end<$now) {
                   5836:                 next;
                   5837:             }
                   5838:             if ($scope eq 'public') {
                   5839:                 $public = $key;
                   5840:                 last;
                   5841:             } elsif ($scope eq 'guest') {
                   5842:                 $guest = $key;
                   5843:             } elsif ($scope eq 'domains') {
                   5844:                 push(@domains,$key);
                   5845:             } elsif ($scope eq 'users') {
                   5846:                 push(@users,$key);
                   5847:             } elsif ($scope eq 'course') {
                   5848:                 push(@courses,$key);
                   5849:             } elsif ($scope eq 'group') {
                   5850:                 push(@groups,$key);
                   5851:             }
                   5852:         }
                   5853:         if ($public) {
                   5854:             return 'ok';
                   5855:         }
                   5856:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5857:             if ($guest) {
                   5858:                 return $guest;
                   5859:             }
                   5860:         } else {
                   5861:             if (@domains > 0) {
                   5862:                 foreach my $domkey (@domains) {
                   5863:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5864:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5865:                             return 'ok';
                   5866:                         }
                   5867:                     }
                   5868:                 }
                   5869:             }
                   5870:             if (@users > 0) {
                   5871:                 foreach my $userkey (@users) {
1.865     raeburn  5872:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5873:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5874:                             if (ref($item) eq 'HASH') {
                   5875:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5876:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5877:                                     return 'ok';
                   5878:                                 }
                   5879:                             }
                   5880:                         }
                   5881:                     } 
1.765     albertel 5882:                 }
                   5883:             }
                   5884:             my %roleshash;
                   5885:             my @courses_and_groups = @courses;
                   5886:             push(@courses_and_groups,@groups); 
                   5887:             if (@courses_and_groups > 0) {
                   5888:                 my (%allgroups,%allroles); 
                   5889:                 my ($start,$end,$role,$sec,$group);
                   5890:                 foreach my $envkey (%env) {
1.1060    raeburn  5891:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5892:                         my $cid = $2.'_'.$3; 
                   5893:                         if ($1 eq 'gr') {
                   5894:                             $group = $4;
                   5895:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5896:                         } else {
                   5897:                             if ($4 eq '') {
                   5898:                                 $sec = 'none';
                   5899:                             } else {
                   5900:                                 $sec = $4;
                   5901:                             }
                   5902:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5903:                         }
1.811     albertel 5904:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5905:                         my $cid = $2.'_'.$3;
                   5906:                         if ($4 eq '') {
                   5907:                             $sec = 'none';
                   5908:                         } else {
                   5909:                             $sec = $4;
                   5910:                         }
                   5911:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5912:                     }
                   5913:                 }
                   5914:                 if (keys(%allroles) == 0) {
                   5915:                     return;
                   5916:                 }
                   5917:                 foreach my $key (@courses_and_groups) {
                   5918:                     my %content = %{$$access_hash{$key}};
                   5919:                     my $cnum = $content{'number'};
                   5920:                     my $cdom = $content{'domain'};
                   5921:                     my $cid = $cdom.'_'.$cnum;
                   5922:                     if (!exists($allroles{$cid})) {
                   5923:                         next;
                   5924:                     }    
                   5925:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5926:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5927:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5928:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5929:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5930:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5931:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5932:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5933:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5934:                                         if (grep/^all$/,@sections) {
                   5935:                                             return 'ok';
                   5936:                                         } else {
                   5937:                                             if (grep/^$sec$/,@sections) {
                   5938:                                                 return 'ok';
                   5939:                                             }
                   5940:                                         }
                   5941:                                     }
                   5942:                                 }
                   5943:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5944:                                     if (grep/^none$/,@groups) {
                   5945:                                         return 'ok';
                   5946:                                     }
                   5947:                                 } else {
                   5948:                                     if (grep/^all$/,@groups) {
                   5949:                                         return 'ok';
                   5950:                                     } 
                   5951:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5952:                                         if (grep/^$group$/,@groups) {
                   5953:                                             return 'ok';
                   5954:                                         }
                   5955:                                     }
                   5956:                                 } 
                   5957:                             }
                   5958:                         }
                   5959:                     }
                   5960:                 }
                   5961:             }
                   5962:             if ($guest) {
                   5963:                 return $guest;
                   5964:             }
                   5965:         }
                   5966:     }
                   5967:     return;
                   5968: }
                   5969: 
                   5970: sub course_group_datechecker {
                   5971:     my ($dates,$now,$status) = @_;
                   5972:     my ($start,$end) = split(/\./,$dates);
                   5973:     if (!$start && !$end) {
                   5974:         return 'ok';
                   5975:     }
                   5976:     if (grep/^active$/,@{$status}) {
                   5977:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5978:             return 'ok';
                   5979:         }
                   5980:     }
                   5981:     if (grep/^previous$/,@{$status}) {
                   5982:         if ($end > $now ) {
                   5983:             return 'ok';
                   5984:         }
                   5985:     }
                   5986:     if (grep/^future$/,@{$status}) {
                   5987:         if ($start > $now) {
                   5988:             return 'ok';
                   5989:         }
                   5990:     }
                   5991:     return; 
                   5992: }
                   5993: 
                   5994: sub parse_portfolio_url {
                   5995:     my ($url) = @_;
                   5996: 
                   5997:     my ($type,$udom,$unum,$group,$file_name);
                   5998:     
1.823     albertel 5999:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6000: 	$type = 1;
                   6001:         $udom = $1;
                   6002:         $unum = $2;
                   6003:         $file_name = $3;
1.823     albertel 6004:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6005: 	$type = 2;
                   6006:         $udom = $1;
                   6007:         $unum = $2;
                   6008:         $group = $3;
                   6009:         $file_name = $3.'/'.$4;
                   6010:     }
                   6011:     if (wantarray) {
                   6012: 	return ($type,$udom,$unum,$file_name,$group);
                   6013:     }
                   6014:     return $type;
                   6015: }
                   6016: 
                   6017: sub is_portfolio_url {
                   6018:     my ($url) = @_;
                   6019:     return scalar(&parse_portfolio_url($url));
                   6020: }
                   6021: 
1.798     raeburn  6022: sub is_portfolio_file {
                   6023:     my ($file) = @_;
1.820     raeburn  6024:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6025:         return 1;
                   6026:     }
                   6027:     return;
                   6028: }
                   6029: 
1.976     raeburn  6030: sub usertools_access {
1.1084    raeburn  6031:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6032:     my ($access,%tools);
                   6033:     if ($context eq '') {
                   6034:         $context = 'tools';
                   6035:     }
                   6036:     if ($context eq 'requestcourses') {
                   6037:         %tools = (
                   6038:                       official   => 1,
                   6039:                       unofficial => 1,
1.1006    raeburn  6040:                       community  => 1,
1.985     raeburn  6041:                  );
1.1172.2.9  raeburn  6042:     } elsif ($context eq 'requestauthor') {
                   6043:         %tools = (
                   6044:                       requestauthor => 1,
                   6045:                  );
1.985     raeburn  6046:     } else {
                   6047:         %tools = (
                   6048:                       aboutme   => 1,
                   6049:                       blog      => 1,
1.1172.2.6  raeburn  6050:                       webdav    => 1,
1.985     raeburn  6051:                       portfolio => 1,
                   6052:                  );
                   6053:     }
1.976     raeburn  6054:     return if (!defined($tools{$tool}));
                   6055: 
                   6056:     if ((!defined($udom)) || (!defined($uname))) {
                   6057:         $udom = $env{'user.domain'};
                   6058:         $uname = $env{'user.name'};
                   6059:     }
                   6060: 
1.978     raeburn  6061:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6062:         if ($action ne 'reload') {
1.985     raeburn  6063:             if ($context eq 'requestcourses') {
                   6064:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6065:             } elsif ($context eq 'requestauthor') {
                   6066:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6067:             } else {
                   6068:                 return $env{'environment.availabletools.'.$tool};
                   6069:             }
                   6070:         }
1.976     raeburn  6071:     }
                   6072: 
1.1172.2.9  raeburn  6073:     my ($toolstatus,$inststatus,$envkey);
                   6074:     if ($context eq 'requestauthor') {
                   6075:         $envkey = $context;
                   6076:     } else {
                   6077:         $envkey = $context.'.'.$tool;
                   6078:     }
1.976     raeburn  6079: 
1.985     raeburn  6080:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6081:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6082:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6083:         $inststatus = $env{'environment.inststatus'};
                   6084:     } else {
1.1084    raeburn  6085:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6086:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6087:             $inststatus = $userenvref->{'inststatus'};
                   6088:         } else {
1.1172.2.9  raeburn  6089:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6090:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6091:             $inststatus = $userenv{'inststatus'};
                   6092:         }
1.976     raeburn  6093:     }
                   6094: 
                   6095:     if ($toolstatus ne '') {
                   6096:         if ($toolstatus) {
                   6097:             $access = 1;
                   6098:         } else {
                   6099:             $access = 0;
                   6100:         }
                   6101:         return $access;
                   6102:     }
                   6103: 
1.1084    raeburn  6104:     my ($is_adv,%domdef);
                   6105:     if (ref($is_advref) eq 'HASH') {
                   6106:         $is_adv = $is_advref->{'is_adv'};
                   6107:     } else {
                   6108:         $is_adv = &is_advanced_user($udom,$uname);
                   6109:     }
                   6110:     if (ref($domdefref) eq 'HASH') {
                   6111:         %domdef = %{$domdefref};
                   6112:     } else {
                   6113:         %domdef = &get_domain_defaults($udom);
                   6114:     }
1.976     raeburn  6115:     if (ref($domdef{$tool}) eq 'HASH') {
                   6116:         if ($is_adv) {
                   6117:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6118:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6119:                     $access = 1;
                   6120:                 } else {
                   6121:                     $access = 0;
                   6122:                 }
                   6123:                 return $access;
                   6124:             }
                   6125:         }
                   6126:         if ($inststatus ne '') {
                   6127:             my ($hasaccess,$hasnoaccess);
                   6128:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6129:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6130:                     if ($domdef{$tool}{$affiliation}) {
                   6131:                         $hasaccess = 1;
                   6132:                     } else {
                   6133:                         $hasnoaccess = 1;
                   6134:                     }
                   6135:                 }
                   6136:             }
                   6137:             if ($hasaccess || $hasnoaccess) {
                   6138:                 if ($hasaccess) {
                   6139:                     $access = 1;
                   6140:                 } elsif ($hasnoaccess) {
                   6141:                     $access = 0; 
                   6142:                 }
                   6143:                 return $access;
                   6144:             }
                   6145:         } else {
                   6146:             if ($domdef{$tool}{'default'} ne '') {
                   6147:                 if ($domdef{$tool}{'default'}) {
                   6148:                     $access = 1;
                   6149:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6150:                     $access = 0;
                   6151:                 }
                   6152:                 return $access;
                   6153:             }
                   6154:         }
                   6155:     } else {
1.1172.2.6  raeburn  6156:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6157:             $access = 1;
                   6158:         } else {
                   6159:             $access = 0;
                   6160:         }
1.976     raeburn  6161:         return $access;
                   6162:     }
                   6163: }
                   6164: 
1.1050    raeburn  6165: sub is_course_owner {
                   6166:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6167:     if (($udom eq '') || ($uname eq '')) {
                   6168:         $udom = $env{'user.domain'};
                   6169:         $uname = $env{'user.name'};
                   6170:     }
                   6171:     unless (($udom eq '') || ($uname eq '')) {
                   6172:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6173:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6174:                 return 1;
                   6175:             } else {
                   6176:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6177:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6178:                     return 1;
                   6179:                 }
                   6180:             }
                   6181:         }
                   6182:     }
                   6183:     return;
                   6184: }
                   6185: 
1.976     raeburn  6186: sub is_advanced_user {
                   6187:     my ($udom,$uname) = @_;
1.1085    raeburn  6188:     if ($udom ne '' && $uname ne '') {
                   6189:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6190:             if (wantarray) {
                   6191:                 return ($env{'user.adv'},$env{'user.author'});
                   6192:             } else {
                   6193:                 return $env{'user.adv'};
                   6194:             }
1.1085    raeburn  6195:         }
                   6196:     }
1.976     raeburn  6197:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6198:     my %allroles;
1.1128    raeburn  6199:     my ($is_adv,$is_author);
1.976     raeburn  6200:     foreach my $role (keys(%roleshash)) {
                   6201:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6202:         my $area = '/'.$tdomain.'/'.$trest;
                   6203:         if ($sec ne '') {
                   6204:             $area .= '/'.$sec;
                   6205:         }
                   6206:         if (($area ne '') && ($trole ne '')) {
                   6207:             my $spec=$trole.'.'.$area;
                   6208:             if ($trole =~ /^cr\//) {
                   6209:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6210:             } elsif ($trole ne 'gr') {
                   6211:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6212:             }
1.1128    raeburn  6213:             if ($trole eq 'au') {
                   6214:                 $is_author = 1;
                   6215:             }
1.976     raeburn  6216:         }
                   6217:     }
                   6218:     foreach my $role (keys(%allroles)) {
                   6219:         last if ($is_adv);
                   6220:         foreach my $item (split(/:/,$allroles{$role})) {
                   6221:             if ($item ne '') {
                   6222:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6223:                 if ($privilege eq 'adv') {
                   6224:                     $is_adv = 1;
                   6225:                     last;
                   6226:                 }
                   6227:             }
                   6228:         }
                   6229:     }
1.1128    raeburn  6230:     if (wantarray) {
                   6231:         return ($is_adv,$is_author);
                   6232:     }
1.976     raeburn  6233:     return $is_adv;
                   6234: }
1.798     raeburn  6235: 
1.1035    raeburn  6236: sub check_can_request {
1.1036    raeburn  6237:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6238:     my $canreq = 0;
                   6239:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6240:     my @options = ('approval','validate','autolimit');
                   6241:     my $optregex = join('|',@options);
                   6242:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6243:         foreach my $type (@{$types}) {
                   6244:             if (&usertools_access($env{'user.name'},
                   6245:                                   $env{'user.domain'},
                   6246:                                   $type,undef,'requestcourses')) {
                   6247:                 $canreq ++;
1.1036    raeburn  6248:                 if (ref($request_domains) eq 'HASH') {
                   6249:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6250:                 }
1.1035    raeburn  6251:                 if ($dom eq $env{'user.domain'}) {
                   6252:                     $can_request->{$type} = 1;
                   6253:                 }
                   6254:             }
                   6255:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6256:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6257:                 if (@curr > 0) {
1.1036    raeburn  6258:                     foreach my $item (@curr) {
                   6259:                         if (ref($request_domains) eq 'HASH') {
                   6260:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6261:                             if ($otherdom ne '') {
                   6262:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6263:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6264:                                         push(@{$request_domains->{$type}},$otherdom);
                   6265:                                     }
                   6266:                                 } else {
                   6267:                                     push(@{$request_domains->{$type}},$otherdom);
                   6268:                                 }
                   6269:                             }
                   6270:                         }
                   6271:                     }
                   6272:                     unless($dom eq $env{'user.domain'}) {
                   6273:                         $canreq ++;
1.1035    raeburn  6274:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6275:                             $can_request->{$type} = 1;
                   6276:                         }
                   6277:                     }
                   6278:                 }
                   6279:             }
                   6280:         }
                   6281:     }
                   6282:     return $canreq;
                   6283: }
                   6284: 
1.341     www      6285: # ---------------------------------------------- Custom access rule evaluation
                   6286: 
                   6287: sub customaccess {
                   6288:     my ($priv,$uri)=@_;
1.807     albertel 6289:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6290:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6291:     $udom = &LONCAPA::clean_domain($udom);
                   6292:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6293:     my $access=0;
1.800     albertel 6294:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6295: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6296: 	if ($type eq 'user') {
                   6297: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6298: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6299: 		if ($tdom) {
                   6300: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6301: 		}
1.896     albertel 6302: 		if ($tuname) {
                   6303: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6304: 		}
                   6305: 		$access=($effect eq 'allow');
                   6306: 		last;
                   6307: 	    }
                   6308: 	} else {
                   6309: 	    if ($role) {
                   6310: 		if ($role ne $urole) { next; }
                   6311: 	    }
                   6312: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6313: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6314: 		if ($tdom) {
                   6315: 		    if ($tdom ne $udom) { next; }
                   6316: 		}
                   6317: 		if ($tcrs) {
                   6318: 		    if ($tcrs ne $ucrs) { next; }
                   6319: 		}
                   6320: 		if ($tsec) {
                   6321: 		    if ($tsec ne $usec) { next; }
                   6322: 		}
                   6323: 		$access=($effect eq 'allow');
                   6324: 		last;
                   6325: 	    }
                   6326: 	    if ($realm eq '' && $role eq '') {
                   6327: 		$access=($effect eq 'allow');
                   6328: 	    }
1.402     bowersj2 6329: 	}
1.341     www      6330:     }
                   6331:     return $access;
                   6332: }
                   6333: 
1.103     harris41 6334: # ------------------------------------------------- Check for a user privilege
1.12      www      6335: 
                   6336: sub allowed {
1.810     raeburn  6337:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6338:     my $ver_orguri=$uri;
1.439     www      6339:     $uri=&deversion($uri);
1.152     www      6340:     my $orguri=$uri;
1.52      www      6341:     $uri=&declutter($uri);
1.809     raeburn  6342: 
1.810     raeburn  6343:     if ($priv eq 'evb') {
                   6344: # Evade communication block restrictions for specified role in a course
                   6345:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6346:             return $1;
                   6347:         } else {
                   6348:             return;
                   6349:         }
                   6350:     }
                   6351: 
1.620     albertel 6352:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6353: # Free bre access to adm and meta resources
1.775     albertel 6354:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6355: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6356: 	&& ($priv eq 'bre')) {
1.14      www      6357: 	return 'F';
1.159     www      6358:     }
                   6359: 
1.545     banghart 6360: # Free bre access to user's own portfolio contents
1.714     raeburn  6361:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6362:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6363: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6364:         my %setters;
                   6365:         my ($startblock,$endblock) = 
                   6366:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6367:         if ($startblock && $endblock) {
                   6368:             return 'B';
                   6369:         } else {
                   6370:             return 'F';
                   6371:         }
1.545     banghart 6372:     }
                   6373: 
1.762     raeburn  6374: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6375:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6376:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6377:         if (exists($env{'request.course.id'})) {
                   6378:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6379:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6380:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6381:                 my $courseprivid=$env{'request.course.id'};
                   6382:                 $courseprivid=~s/\_/\//;
                   6383:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6384:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6385:                     return $1; 
1.762     raeburn  6386:                 } else {
                   6387:                     if ($env{'request.course.sec'}) {
                   6388:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6389:                     }
                   6390:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6391:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6392:                         return $2;
                   6393:                     }
1.714     raeburn  6394:                 }
                   6395:             }
                   6396:         }
                   6397:     }
                   6398: 
1.159     www      6399: # Free bre to public access
                   6400: 
                   6401:     if ($priv eq 'bre') {
1.238     www      6402:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6403: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6404:            return 'F'; 
                   6405:         }
1.238     www      6406:         if ($copyright eq 'priv') {
                   6407:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6408: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6409: 		return '';
                   6410:             }
                   6411:         }
                   6412:         if ($copyright eq 'domain') {
                   6413:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6414: 	    unless (($env{'user.domain'} eq $1) ||
                   6415:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6416: 		return '';
                   6417:             }
1.262     matthew  6418:         }
1.620     albertel 6419:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6420:             # Library role, so allow browsing of resources in this domain.
                   6421:             return 'F';
1.238     www      6422:         }
1.341     www      6423:         if ($copyright eq 'custom') {
                   6424: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6425:         }
1.14      www      6426:     }
1.264     matthew  6427:     # Domain coordinator is trying to create a course
1.620     albertel 6428:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6429:         # uri is the requested domain in this case.
                   6430:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6431:         # a role of dc for the domain in question.
1.620     albertel 6432:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6433:     }
1.29      www      6434: 
1.52      www      6435:     my $thisallowed='';
                   6436:     my $statecond=0;
                   6437:     my $courseprivid='';
                   6438: 
1.1039    raeburn  6439:     my $ownaccess;
1.1043    raeburn  6440:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6441:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6442:         if ($uri eq '') {
                   6443:             $ownaccess = 1;
                   6444:         } else {
                   6445:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6446:                 my $udom = $env{'user.domain'};
                   6447:                 my $uname = $env{'user.name'};
                   6448:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6449:                     $ownaccess = 1;
1.1040    raeburn  6450:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6451:                     unless ($uri =~ m{\.\./}) {
                   6452:                         $ownaccess = 1;
                   6453:                     }
                   6454:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6455:                     my $now = time;
                   6456:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6457:                         my $adom = $1;
                   6458:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6459:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6460:                                 my ($start,$end) = split('.',$env{$key});
                   6461:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6462:                                     $ownaccess = 1;
                   6463:                                     last;
                   6464:                                 }
                   6465:                             }
                   6466:                         }
                   6467:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6468:                         my $adom = $1;
                   6469:                         my $aname = $2;
1.1042    raeburn  6470:                         foreach my $role ('ca','aa') { 
                   6471:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6472:                                 my ($start,$end) =
                   6473:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6474:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6475:                                     $ownaccess = 1;
                   6476:                                     last;
                   6477:                                 }
1.1039    raeburn  6478:                             }
                   6479:                         }
                   6480:                     }
                   6481:                 }
                   6482:             }
                   6483:         }
                   6484:     }
                   6485: 
1.52      www      6486: # Course
                   6487: 
1.620     albertel 6488:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6489:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6490:             $thisallowed.=$1;
                   6491:         }
1.52      www      6492:     }
1.29      www      6493: 
1.52      www      6494: # Domain
                   6495: 
1.620     albertel 6496:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6497:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6498:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6499:             $thisallowed.=$1;
                   6500:         }
1.12      www      6501:     }
1.52      www      6502: 
1.1141    raeburn  6503: # User who is not author or co-author might still be able to edit
                   6504: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6505:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6506:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6507:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6508:             $thisallowed.=$1;
                   6509:         }
                   6510:     }
                   6511: 
1.52      www      6512: # Course: uri itself is a course
1.66      www      6513:     my $courseuri=$uri;
                   6514:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6515:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6516: 
1.620     albertel 6517:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6518:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6519:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6520:             $thisallowed.=$1;
                   6521:         }
1.12      www      6522:     }
1.29      www      6523: 
1.665     albertel 6524: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6525: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6526:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6527: 	$thisallowed='';
1.671     raeburn  6528:         my ($match)=&is_on_map($uri);
                   6529:         if ($match) {
                   6530:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6531:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6532:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6533:                 if (@blockers > 0) {
                   6534:                     $thisallowed = 'B';
                   6535:                 } else {
                   6536:                     $thisallowed.=$1;
                   6537:                 }
1.671     raeburn  6538:             }
                   6539:         } else {
1.705     albertel 6540:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6541:             if ($refuri) {
                   6542:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6543:                     $thisallowed='F';
1.671     raeburn  6544:                 } else {
                   6545:                     $refuri=&declutter($refuri);
                   6546:                     my ($match) = &is_on_map($refuri);
                   6547:                     if ($match) {
1.1162    raeburn  6548:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6549:                         if (@blockers > 0) {
                   6550:                             $thisallowed = 'B';
                   6551:                         } else {
                   6552:                             $thisallowed='F';
                   6553:                         }
1.671     raeburn  6554:                     }
1.669     raeburn  6555:                 }
1.671     raeburn  6556:             }
                   6557:         }
1.314     www      6558:     }
1.492     albertel 6559: 
1.766     albertel 6560:     if ($priv eq 'bre'
                   6561: 	&& $thisallowed ne 'F' 
                   6562: 	&& $thisallowed ne '2'
                   6563: 	&& &is_portfolio_url($uri)) {
                   6564: 	$thisallowed = &portfolio_access($uri);
                   6565:     }
                   6566:     
1.52      www      6567: # Full access at system, domain or course-wide level? Exit.
1.29      www      6568:     if ($thisallowed=~/F/) {
                   6569: 	return 'F';
                   6570:     }
                   6571: 
1.52      www      6572: # If this is generating or modifying users, exit with special codes
1.29      www      6573: 
1.643     www      6574:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6575: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6576: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6577: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6578: 	    unless ($auname) { return $thisallowed; }
                   6579: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6580: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6581: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6582: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6583: 	}
1.52      www      6584: 	return $thisallowed;
                   6585:     }
                   6586: #
1.103     harris41 6587: # Gathered so far: system, domain and course wide privileges
1.52      www      6588: #
                   6589: # Course: See if uri or referer is an individual resource that is part of 
                   6590: # the course
                   6591: 
1.620     albertel 6592:     if ($env{'request.course.id'}) {
1.232     www      6593: 
1.620     albertel 6594:        $courseprivid=$env{'request.course.id'};
                   6595:        if ($env{'request.course.sec'}) {
                   6596:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6597:        }
                   6598:        $courseprivid=~s/\_/\//;
                   6599:        my $checkreferer=1;
1.232     www      6600:        my ($match,$cond)=&is_on_map($uri);
                   6601:        if ($match) {
                   6602:            $statecond=$cond;
1.620     albertel 6603:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6604:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6605:                my $value = $1;
                   6606:                if ($priv eq 'bre') {
                   6607:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6608:                    if (@blockers > 0) {
                   6609:                        $thisallowed = 'B';
                   6610:                    } else {
                   6611:                        $thisallowed.=$value;
                   6612:                    }
                   6613:                } else {
                   6614:                    $thisallowed.=$value;
                   6615:                }
1.52      www      6616:                $checkreferer=0;
                   6617:            }
1.29      www      6618:        }
1.83      www      6619:        
1.148     www      6620:        if ($checkreferer) {
1.620     albertel 6621: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6622:             unless ($refuri) {
1.800     albertel 6623:                 foreach my $key (keys(%env)) {
                   6624: 		    if ($key=~/^httpref\..*\*/) {
                   6625: 			my $pattern=$key;
1.156     www      6626:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6627:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6628:                         $pattern=~s/\//\\\//g;
1.152     www      6629:                         if ($orguri=~/$pattern/) {
1.800     albertel 6630: 			    $refuri=$env{$key};
1.148     www      6631:                         }
                   6632:                     }
1.191     harris41 6633:                 }
1.148     www      6634:             }
1.232     www      6635: 
1.148     www      6636:          if ($refuri) { 
1.152     www      6637: 	  $refuri=&declutter($refuri);
1.232     www      6638:           my ($match,$cond)=&is_on_map($refuri);
                   6639:             if ($match) {
                   6640:               my $refstatecond=$cond;
1.620     albertel 6641:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6642:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6643:                   my $value = $1;
                   6644:                   if ($priv eq 'bre') {
                   6645:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6646:                       if (@blockers > 0) {
                   6647:                           $thisallowed = 'B';
                   6648:                       } else {
                   6649:                           $thisallowed.=$value;
                   6650:                       }
                   6651:                   } else {
                   6652:                       $thisallowed.=$value;
                   6653:                   }
1.53      www      6654:                   $uri=$refuri;
                   6655:                   $statecond=$refstatecond;
1.52      www      6656:               }
                   6657:           }
1.148     www      6658:         }
1.29      www      6659:        }
1.52      www      6660:    }
1.29      www      6661: 
1.52      www      6662: #
1.103     harris41 6663: # Gathered now: all privileges that could apply, and condition number
1.52      www      6664: # 
                   6665: #
                   6666: # Full or no access?
                   6667: #
1.29      www      6668: 
1.52      www      6669:     if ($thisallowed=~/F/) {
                   6670: 	return 'F';
                   6671:     }
1.29      www      6672: 
1.52      www      6673:     unless ($thisallowed) {
                   6674:         return '';
                   6675:     }
1.29      www      6676: 
1.52      www      6677: # Restrictions exist, deal with them
                   6678: #
                   6679: #   C:according to course preferences
                   6680: #   R:according to resource settings
                   6681: #   L:unless locked
                   6682: #   X:according to user session state
                   6683: #
                   6684: 
                   6685: # Possibly locked functionality, check all courses
1.54      www      6686: # Locks might take effect only after 10 minutes cache expiration for other
                   6687: # courses, and 2 minutes for current course
1.52      www      6688: 
                   6689:     my $envkey;
                   6690:     if ($thisallowed=~/L/) {
1.1000    raeburn  6691:         foreach $envkey (keys(%env)) {
1.54      www      6692:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6693:                my $courseid=$2;
                   6694:                my $roleid=$1.'.'.$2;
1.92      www      6695:                $courseid=~s/^\///;
1.54      www      6696:                my $expiretime=600;
1.620     albertel 6697:                if ($env{'request.role'} eq $roleid) {
1.54      www      6698: 		  $expiretime=120;
                   6699:                }
                   6700: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6701:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6702:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6703: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6704:                }
1.620     albertel 6705:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6706:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6707: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6708:                        &log($env{'user.domain'},$env{'user.name'},
                   6709:                             $env{'user.home'},
1.57      www      6710:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6711:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6712:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6713: 		       return '';
                   6714:                    }
                   6715:                }
1.620     albertel 6716:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6717:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6718: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6719:                        &log($env{'user.domain'},$env{'user.name'},
                   6720:                             $env{'user.home'},
1.57      www      6721:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6722:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6723:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6724: 		       return '';
                   6725:                    }
                   6726:                }
                   6727: 	   }
1.29      www      6728:        }
1.52      www      6729:     }
                   6730:    
                   6731: #
                   6732: # Rest of the restrictions depend on selected course
                   6733: #
                   6734: 
1.620     albertel 6735:     unless ($env{'request.course.id'}) {
1.766     albertel 6736: 	if ($thisallowed eq 'A') {
                   6737: 	    return 'A';
1.814     raeburn  6738:         } elsif ($thisallowed eq 'B') {
                   6739:             return 'B';
1.766     albertel 6740: 	} else {
                   6741: 	    return '1';
                   6742: 	}
1.52      www      6743:     }
1.29      www      6744: 
1.52      www      6745: #
                   6746: # Now user is definitely in a course
                   6747: #
1.53      www      6748: 
                   6749: 
                   6750: # Course preferences
                   6751: 
                   6752:    if ($thisallowed=~/C/) {
1.620     albertel 6753:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6754:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6755:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6756: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6757: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6758: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6759: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6760: 			$env{'request.course.id'});
                   6761: 	   }
1.237     www      6762:            return '';
                   6763:        }
                   6764: 
1.620     albertel 6765:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6766: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6767: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6768: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6769: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6770: 			$env{'request.course.id'});
                   6771: 	   }
1.54      www      6772:            return '';
                   6773:        }
1.53      www      6774:    }
                   6775: 
                   6776: # Resource preferences
                   6777: 
                   6778:    if ($thisallowed=~/R/) {
1.620     albertel 6779:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6780:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6781: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6782: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6783: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6784: 	   }
                   6785: 	   return '';
1.54      www      6786:        }
1.53      www      6787:    }
1.30      www      6788: 
1.246     www      6789: # Restricted by state or randomout?
1.30      www      6790: 
1.52      www      6791:    if ($thisallowed=~/X/) {
1.620     albertel 6792:       if ($env{'acc.randomout'}) {
1.579     albertel 6793: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6794:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6795:             return ''; 
                   6796:          }
1.247     www      6797:       }
                   6798:       if (&condval($statecond)) {
1.52      www      6799: 	 return '2';
                   6800:       } else {
                   6801:          return '';
                   6802:       }
                   6803:    }
1.30      www      6804: 
1.766     albertel 6805:     if ($thisallowed eq 'A') {
                   6806: 	return 'A';
1.814     raeburn  6807:     } elsif ($thisallowed eq 'B') {
                   6808:         return 'B';
1.766     albertel 6809:     }
1.52      www      6810:    return 'F';
1.232     www      6811: }
1.1162    raeburn  6812: 
1.1172.2.13  raeburn  6813: # ------------------------------------------- Check construction space access
                   6814: 
                   6815: sub constructaccess {
                   6816:     my ($url,$setpriv)=@_;
                   6817: 
                   6818: # We do not allow editing of previous versions of files
                   6819:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6820: 
                   6821: # Get username and domain from URL
                   6822:     my ($ownername,$ownerdomain,$ownerhome);
                   6823: 
                   6824:     ($ownerdomain,$ownername) =
                   6825:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6826: 
                   6827: # The URL does not really point to any authorspace, forget it
                   6828:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6829: 
                   6830: # Now we need to see if the user has access to the authorspace of
                   6831: # $ownername at $ownerdomain
                   6832: 
                   6833:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6834: # Real author for this?
                   6835:        $ownerhome = $env{'user.home'};
                   6836:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6837:           return ($ownername,$ownerdomain,$ownerhome);
                   6838:        }
                   6839:     } else {
                   6840: # Co-author for this?
                   6841:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6842:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6843:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6844:             return ($ownername,$ownerdomain,$ownerhome);
                   6845:         }
                   6846:     }
                   6847: 
                   6848: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6849: # we might as well leave
                   6850:    unless ($setpriv) { return ''; }
                   6851: 
                   6852: # Backdoor access?
                   6853:     my $allowed=&allowed('eco',$ownerdomain);
                   6854: # Nope
                   6855:     unless ($allowed) { return ''; }
                   6856: # Looks like we may have access, but could be locked by the owner of the construction space
                   6857:     if ($allowed eq 'U') {
                   6858:         my %blocked=&get('environment',['domcoord.author'],
                   6859:                          $ownerdomain,$ownername);
                   6860: # Is blocked by owner
                   6861:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6862:     }
                   6863:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6864: # Grant temporary access
                   6865:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6866:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6867:         if (!$update) { $update = $then; }
                   6868:         my $refresh=$env{'user.refresh.time'};
                   6869:         if (!$refresh) { $refresh = $update; }
                   6870:         my $now = time;
                   6871:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6872:                            $now,'ca','constructaccess');
                   6873:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6874:         return($ownername,$ownerdomain,$ownerhome);
                   6875:     }
                   6876: # No business here
                   6877:     return '';
                   6878: }
                   6879: 
1.1162    raeburn  6880: sub get_comm_blocks {
                   6881:     my ($cdom,$cnum) = @_;
                   6882:     if ($cdom eq '' || $cnum eq '') {
                   6883:         return unless ($env{'request.course.id'});
                   6884:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6885:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6886:     }
                   6887:     my %commblocks;
                   6888:     my $hashid=$cdom.'_'.$cnum;
                   6889:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6890:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6891:         %commblocks = %{$blocksref};
                   6892:     } else {
                   6893:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6894:         my $cachetime = 600;
                   6895:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6896:     }
                   6897:     return %commblocks;
                   6898: }
                   6899: 
                   6900: sub has_comm_blocking {
                   6901:     my ($priv,$symb,$uri,$blocks) = @_;
                   6902:     return unless ($env{'request.course.id'});
                   6903:     return unless ($priv eq 'bre');
                   6904:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6905:     my %commblocks;
                   6906:     if (ref($blocks) eq 'HASH') {
                   6907:         %commblocks = %{$blocks};
                   6908:     } else {
                   6909:         %commblocks = &get_comm_blocks();
                   6910:     }
                   6911:     return unless (keys(%commblocks) > 0);
                   6912:     if (!$symb) { $symb=&symbread($uri,1); }
                   6913:     my ($map,$resid,undef)=&decode_symb($symb);
                   6914:     my %tocheck = (
                   6915:                     maps      => $map,
                   6916:                     resources => $symb,
                   6917:                   );
                   6918:     my @blockers;
                   6919:     my $now = time;
1.1163    raeburn  6920:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6921:     foreach my $block (keys(%commblocks)) {
                   6922:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6923:             my ($start,$end) = ($1,$2);
                   6924:             if ($start <= $now && $end >= $now) {
                   6925:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6926:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6927:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6928:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6929:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6930:                                     push(@blockers,$block);
                   6931:                                 }
                   6932:                             }
                   6933:                         }
                   6934:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6935:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6936:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6937:                                     push(@blockers,$block);
                   6938:                                 }
                   6939:                             }
                   6940:                         }
                   6941:                     }
                   6942:                 }
                   6943:             }
                   6944:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6945:             my $item = $1;
1.1163    raeburn  6946:             my @to_test;
1.1162    raeburn  6947:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6948:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6949:                     my $check_interval;
                   6950:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6951:                         my @interval;
                   6952:                         my $type = 'map';
                   6953:                         if ($item eq 'course') {
                   6954:                             $type = 'course';
                   6955:                             @interval=&EXT("resource.0.interval");
                   6956:                         } else {
                   6957:                             if ($item =~ /___\d+___/) {
                   6958:                                 $type = 'resource';
                   6959:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6960:                                 if (ref($navmap)) {                        
                   6961:                                     my $res = $navmap->getBySymb($item); 
                   6962:                                     push(@to_test,$res);
                   6963:                                 }
1.1162    raeburn  6964:                             } else {
                   6965:                                 my $mapsymb = &symbread($item,1);
                   6966:                                 if ($mapsymb) {
                   6967:                                     if (ref($navmap)) {
                   6968:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6969:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6970:                                         foreach my $res (@to_test) {
1.1162    raeburn  6971:                                             my $symb = $res->symb();
                   6972:                                             next if ($symb eq $mapsymb);
                   6973:                                             if ($symb ne '') {
                   6974:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6975:                                                 last;
                   6976:                                             }
                   6977:                                         }
                   6978:                                     }
                   6979:                                 }
                   6980:                             }
                   6981:                         }
                   6982:                         if ($interval[0] =~ /\d+/) {
                   6983:                             my $first_access;
                   6984:                             if ($type eq 'resource') {
                   6985:                                 $first_access=&get_first_access($interval[1],$item);
                   6986:                             } elsif ($type eq 'map') {
                   6987:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6988:                             } else {
                   6989:                                 $first_access=&get_first_access($interval[1]);
                   6990:                             }
                   6991:                             if ($first_access) {
                   6992:                                 my $timesup = $first_access+$interval[0];
                   6993:                                 if ($timesup > $now) {
1.1163    raeburn  6994:                                     foreach my $res (@to_test) {
                   6995:                                         if ($res->is_problem()) {
                   6996:                                             if ($res->completable()) {
                   6997:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6998:                                                     push(@blockers,$block);
                   6999:                                                 }
                   7000:                                                 last;
                   7001:                                             }
                   7002:                                         }
1.1162    raeburn  7003:                                     }
                   7004:                                 }
                   7005:                             }
                   7006:                         }
                   7007:                     }
                   7008:                 }
                   7009:             }
                   7010:         }
                   7011:     }
                   7012:     return @blockers;
                   7013: }
                   7014: 
                   7015: sub check_docs_block {
                   7016:     my ($docsblock,$tocheck) =@_;
                   7017:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7018:         return;
                   7019:     }
                   7020:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7021:         if ($tocheck->{'maps'}) {
                   7022:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7023:                 return 1;
                   7024:             }
                   7025:         }
                   7026:     }
                   7027:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7028:         if ($tocheck->{'resources'}) {
                   7029:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7030:                 return 1;
                   7031:             }
                   7032:         }
                   7033:     }
                   7034:     return;
                   7035: }
                   7036: 
1.1133    foxr     7037: #
                   7038: #   Removes the versino from a URI and
                   7039: #   splits it in to its filename and path to the filename.
                   7040: #   Seems like File::Basename could have done this more clearly.
                   7041: #   Parameters:
                   7042: #      $uri   - input URI
                   7043: #   Returns:
                   7044: #     Two element list consisting of 
                   7045: #     $pathname  - the URI up to and excluding the trailing /
                   7046: #     $filename  - The part of the URI following the last /
                   7047: #  NOTE:
                   7048: #    Another realization of this is simply:
                   7049: #    use File::Basename;
                   7050: #    ...
                   7051: #    $uri = shift;
                   7052: #    $filename = basename($uri);
                   7053: #    $path     = dirname($uri);
                   7054: #    return ($filename, $path);
                   7055: #
                   7056: #     The implementation below is probably faster however.
                   7057: #
1.710     albertel 7058: sub split_uri_for_cond {
                   7059:     my $uri=&deversion(&declutter(shift));
                   7060:     my @uriparts=split(/\//,$uri);
                   7061:     my $filename=pop(@uriparts);
                   7062:     my $pathname=join('/',@uriparts);
                   7063:     return ($pathname,$filename);
                   7064: }
1.232     www      7065: # --------------------------------------------------- Is a resource on the map?
                   7066: 
                   7067: sub is_on_map {
1.710     albertel 7068:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7069:     #Trying to find the conditional for the file
1.620     albertel 7070:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7071: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7072:     if ($match) {
1.289     bowersj2 7073: 	return (1,$1);
                   7074:     } else {
1.434     www      7075: 	return (0,0);
1.289     bowersj2 7076:     }
1.12      www      7077: }
                   7078: 
1.427     www      7079: # --------------------------------------------------------- Get symb from alias
                   7080: 
                   7081: sub get_symb_from_alias {
                   7082:     my $symb=shift;
                   7083:     my ($map,$resid,$url)=&decode_symb($symb);
                   7084: # Already is a symb
                   7085:     if ($url) { return $symb; }
                   7086: # Must be an alias
                   7087:     my $aliassymb='';
                   7088:     my %bighash;
1.620     albertel 7089:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7090:                             &GDBM_READER(),0640)) {
                   7091:         my $rid=$bighash{'mapalias_'.$symb};
                   7092: 	if ($rid) {
                   7093: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7094: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7095: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7096: 	}
                   7097:         untie %bighash;
                   7098:     }
                   7099:     return $aliassymb;
                   7100: }
                   7101: 
1.12      www      7102: # ----------------------------------------------------------------- Define Role
                   7103: 
                   7104: sub definerole {
                   7105:   if (allowed('mcr','/')) {
                   7106:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7107:     foreach my $role (split(':',$sysrole)) {
                   7108: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7109:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7110:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7111: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7112:                return "refused:s:$crole&$cqual"; 
                   7113:             }
                   7114:         }
1.191     harris41 7115:     }
1.800     albertel 7116:     foreach my $role (split(':',$domrole)) {
                   7117: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7118:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7119:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7120: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7121:                return "refused:d:$crole&$cqual"; 
                   7122:             }
                   7123:         }
1.191     harris41 7124:     }
1.800     albertel 7125:     foreach my $role (split(':',$courole)) {
                   7126: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7127:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7128:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7129: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7130:                return "refused:c:$crole&$cqual"; 
                   7131:             }
                   7132:         }
1.191     harris41 7133:     }
1.620     albertel 7134:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7135:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7136: 	        "rolesdef_$rolename=".
                   7137:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7138:     return reply($command,$env{'user.home'});
1.12      www      7139:   } else {
                   7140:     return 'refused';
                   7141:   }
1.105     harris41 7142: }
                   7143: 
                   7144: # ---------------- Make a metadata query against the network of library servers
                   7145: 
                   7146: sub metadata_query {
1.244     matthew  7147:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7148:     my %rhash;
1.845     albertel 7149:     my %libserv = &all_library();
1.244     matthew  7150:     my @server_list = (defined($server_array) ? @$server_array
                   7151:                                               : keys(%libserv) );
                   7152:     for my $server (@server_list) {
1.118     harris41 7153: 	unless ($custom or $customshow) {
                   7154: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7155: 	    $rhash{$server}=$reply;
                   7156: 	}
                   7157: 	else {
                   7158: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7159: 			     &escape($custom).':'.&escape($customshow),
                   7160: 			     $server);
                   7161: 	    $rhash{$server}=$reply;
                   7162: 	}
1.112     harris41 7163:     }
1.118     harris41 7164:     return \%rhash;
1.240     www      7165: }
                   7166: 
                   7167: # ----------------------------------------- Send log queries and wait for reply
                   7168: 
                   7169: sub log_query {
                   7170:     my ($uname,$udom,$query,%filters)=@_;
                   7171:     my $uhome=&homeserver($uname,$udom);
                   7172:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7173:     my $uhost=&hostname($uhome);
1.800     albertel 7174:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7175:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7176:                        $uhome);
1.479     albertel 7177:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7178:     return get_query_reply($queryid);
                   7179: }
                   7180: 
1.818     raeburn  7181: # -------------------------- Update MySQL table for portfolio file
                   7182: 
                   7183: sub update_portfolio_table {
1.821     raeburn  7184:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7185:     if ($group ne '') {
                   7186:         $file_name =~s /^\Q$group\E//;
                   7187:     }
1.818     raeburn  7188:     my $homeserver = &homeserver($uname,$udom);
                   7189:     my $queryid=
1.821     raeburn  7190:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7191:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7192:     my $reply = &get_query_reply($queryid);
                   7193:     return $reply;
                   7194: }
                   7195: 
1.899     raeburn  7196: # -------------------------- Update MySQL allusers table
                   7197: 
                   7198: sub update_allusers_table {
                   7199:     my ($uname,$udom,$names) = @_;
                   7200:     my $homeserver = &homeserver($uname,$udom);
                   7201:     my $queryid=
                   7202:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7203:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7204:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7205:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7206:                'generation='.&escape($names->{'generation'}).'%%'.
                   7207:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7208:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7209:     return;
1.899     raeburn  7210: }
                   7211: 
1.508     raeburn  7212: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7213: 
                   7214: sub fetch_enrollment_query {
1.511     raeburn  7215:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7216:     my $homeserver;
1.547     raeburn  7217:     my $maxtries = 1;
1.508     raeburn  7218:     if ($context eq 'automated') {
                   7219:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7220:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7221:     } else {
                   7222:         $homeserver = &homeserver($cnum,$dom);
                   7223:     }
1.838     albertel 7224:     my $host=&hostname($homeserver);
1.506     raeburn  7225:     my $cmd = '';
1.1000    raeburn  7226:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7227:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7228:     }
                   7229:     $cmd =~ s/%%$//;
                   7230:     $cmd = &escape($cmd);
                   7231:     my $query = 'fetchenrollment';
1.620     albertel 7232:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7233:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7234:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7235:         return 'error: '.$queryid;
                   7236:     }
1.506     raeburn  7237:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7238:     my $tries = 1;
                   7239:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7240:         $reply = &get_query_reply($queryid);
                   7241:         $tries ++;
                   7242:     }
1.526     raeburn  7243:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7244:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7245:     } else {
1.901     albertel 7246:         my @responses = split(/:/,$reply);
1.515     raeburn  7247:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7248:             foreach my $line (@responses) {
                   7249:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7250:                 $$replyref{$key} = $value;
                   7251:             }
                   7252:         } else {
1.1117    foxr     7253:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7254:             foreach my $line (@responses) {
                   7255:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7256:                 $$replyref{$key} = $value;
                   7257:                 if ($value > 0) {
1.800     albertel 7258:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7259:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7260:                         my $destname = $pathname.'/'.$filename;
                   7261:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7262:                         if ($xml_classlist =~ /^error/) {
                   7263:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7264:                         } else {
1.506     raeburn  7265:                             if ( open(FILE,">$destname") ) {
                   7266:                                 print FILE &unescape($xml_classlist);
                   7267:                                 close(FILE);
1.526     raeburn  7268:                             } else {
                   7269:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7270:                             }
                   7271:                         }
                   7272:                     }
                   7273:                 }
                   7274:             }
                   7275:         }
                   7276:         return 'ok';
                   7277:     }
                   7278:     return 'error';
                   7279: }
                   7280: 
1.242     www      7281: sub get_query_reply {
                   7282:     my $queryid=shift;
1.1117    foxr     7283:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7284:     my $reply='';
                   7285:     for (1..100) {
                   7286: 	sleep 2;
                   7287:         if (-e $replyfile.'.end') {
1.448     albertel 7288: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7289: 		$reply = join('',<$fh>);
                   7290: 		close($fh);
1.240     www      7291: 	   } else { return 'error: reply_file_error'; }
1.242     www      7292:            return &unescape($reply);
                   7293: 	}
1.240     www      7294:     }
1.242     www      7295:     return 'timeout:'.$queryid;
1.240     www      7296: }
                   7297: 
                   7298: sub courselog_query {
1.241     www      7299: #
                   7300: # possible filters:
                   7301: # url: url or symb
                   7302: # username
                   7303: # domain
                   7304: # action: view, submit, grade
                   7305: # start: timestamp
                   7306: # end: timestamp
                   7307: #
1.240     www      7308:     my (%filters)=@_;
1.620     albertel 7309:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7310:     if ($filters{'url'}) {
                   7311: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7312:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7313:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7314:     }
1.620     albertel 7315:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7316:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7317:     return &log_query($cname,$cdom,'courselog',%filters);
                   7318: }
                   7319: 
                   7320: sub userlog_query {
1.858     raeburn  7321: #
                   7322: # possible filters:
                   7323: # action: log check role
                   7324: # start: timestamp
                   7325: # end: timestamp
                   7326: #
1.240     www      7327:     my ($uname,$udom,%filters)=@_;
                   7328:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7329: }
                   7330: 
1.506     raeburn  7331: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7332: 
                   7333: sub auto_run {
1.508     raeburn  7334:     my ($cnum,$cdom) = @_;
1.876     raeburn  7335:     my $response = 0;
                   7336:     my $settings;
                   7337:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7338:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7339:         $settings = $domconfig{'autoenroll'};
                   7340:         if ($settings->{'run'} eq '1') {
                   7341:             $response = 1;
                   7342:         }
                   7343:     } else {
1.934     raeburn  7344:         my $homeserver;
                   7345:         if (&is_course($cdom,$cnum)) {
                   7346:             $homeserver = &homeserver($cnum,$cdom);
                   7347:         } else {
                   7348:             $homeserver = &domain($cdom,'primary');
                   7349:         }
                   7350:         if ($homeserver ne 'no_host') {
                   7351:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7352:         }
1.876     raeburn  7353:     }
1.506     raeburn  7354:     return $response;
                   7355: }
1.776     albertel 7356: 
1.506     raeburn  7357: sub auto_get_sections {
1.508     raeburn  7358:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7359:     my $homeserver;
                   7360:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7361:         $homeserver = &homeserver($cnum,$cdom);
                   7362:     }
                   7363:     if (!defined($homeserver)) { 
                   7364:         if ($cdom =~ /^$match_domain$/) {
                   7365:             $homeserver = &domain($cdom,'primary');
                   7366:         }
                   7367:     }
                   7368:     my @secs;
                   7369:     if (defined($homeserver)) {
                   7370:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7371:         unless ($response eq 'refused') {
                   7372:             @secs = split(/:/,$response);
                   7373:         }
1.506     raeburn  7374:     }
                   7375:     return @secs;
                   7376: }
1.776     albertel 7377: 
1.506     raeburn  7378: sub auto_new_course {
1.1099    raeburn  7379:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7380:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7381:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7382:     return $response;
                   7383: }
1.776     albertel 7384: 
1.506     raeburn  7385: sub auto_validate_courseID {
1.508     raeburn  7386:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7387:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7388:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7389:     return $response;
                   7390: }
1.776     albertel 7391: 
1.1007    raeburn  7392: sub auto_validate_instcode {
1.1020    raeburn  7393:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7394:     my ($homeserver,$response);
                   7395:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7396:         $homeserver = &homeserver($cnum,$cdom);
                   7397:     }
                   7398:     if (!defined($homeserver)) {
                   7399:         if ($cdom =~ /^$match_domain$/) {
                   7400:             $homeserver = &domain($cdom,'primary');
                   7401:         }
                   7402:     }
1.1065    raeburn  7403:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7404:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7405:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7406:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7407: }
                   7408: 
1.506     raeburn  7409: sub auto_create_password {
1.873     raeburn  7410:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7411:     my ($homeserver,$response);
1.506     raeburn  7412:     my $create_passwd = 0;
                   7413:     my $authchk = '';
1.873     raeburn  7414:     if ($udom =~ /^$match_domain$/) {
                   7415:         $homeserver = &domain($udom,'primary');
                   7416:     }
                   7417:     if ($homeserver eq '') {
                   7418:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7419:             $homeserver = &homeserver($cnum,$cdom);
                   7420:         }
                   7421:     }
                   7422:     if ($homeserver eq '') {
                   7423:         $authchk = 'nodomain';
1.506     raeburn  7424:     } else {
1.873     raeburn  7425:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7426:         if ($response eq 'refused') {
                   7427:             $authchk = 'refused';
                   7428:         } else {
1.901     albertel 7429:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7430:         }
1.506     raeburn  7431:     }
                   7432:     return ($authparam,$create_passwd,$authchk);
                   7433: }
                   7434: 
1.706     raeburn  7435: sub auto_photo_permission {
                   7436:     my ($cnum,$cdom,$students) = @_;
                   7437:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7438:     my ($outcome,$perm_reqd,$conditions) = 
                   7439: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7440:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7441: 	return (undef,undef);
                   7442:     }
1.706     raeburn  7443:     return ($outcome,$perm_reqd,$conditions);
                   7444: }
                   7445: 
                   7446: sub auto_checkphotos {
                   7447:     my ($uname,$udom,$pid) = @_;
                   7448:     my $homeserver = &homeserver($uname,$udom);
                   7449:     my ($result,$resulttype);
                   7450:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7451: 				   &escape($uname).':'.&escape($pid),
                   7452: 				   $homeserver));
1.709     albertel 7453:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7454: 	return (undef,undef);
                   7455:     }
1.706     raeburn  7456:     if ($outcome) {
                   7457:         ($result,$resulttype) = split(/:/,$outcome);
                   7458:     } 
                   7459:     return ($result,$resulttype);
                   7460: }
                   7461: 
                   7462: sub auto_photochoice {
                   7463:     my ($cnum,$cdom) = @_;
                   7464:     my $homeserver = &homeserver($cnum,$cdom);
                   7465:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7466: 						       &escape($cdom),
                   7467: 						       $homeserver)));
1.709     albertel 7468:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7469: 	return (undef,undef);
                   7470:     }
1.706     raeburn  7471:     return ($update,$comment);
                   7472: }
                   7473: 
                   7474: sub auto_photoupdate {
                   7475:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7476:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7477:     my $host=&hostname($homeserver);
1.706     raeburn  7478:     my $cmd = '';
                   7479:     my $maxtries = 1;
1.800     albertel 7480:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7481:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7482:     }
                   7483:     $cmd =~ s/%%$//;
                   7484:     $cmd = &escape($cmd);
                   7485:     my $query = 'institutionalphotos';
                   7486:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7487:     unless ($queryid=~/^\Q$host\E\_/) {
                   7488:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7489:         return 'error: '.$queryid;
                   7490:     }
                   7491:     my $reply = &get_query_reply($queryid);
                   7492:     my $tries = 1;
                   7493:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7494:         $reply = &get_query_reply($queryid);
                   7495:         $tries ++;
                   7496:     }
                   7497:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7498:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7499:     } else {
                   7500:         my @responses = split(/:/,$reply);
                   7501:         my $outcome = shift(@responses); 
                   7502:         foreach my $item (@responses) {
                   7503:             my ($key,$value) = split(/=/,$item);
                   7504:             $$photo{$key} = $value;
                   7505:         }
                   7506:         return $outcome;
                   7507:     }
                   7508:     return 'error';
                   7509: }
                   7510: 
1.521     raeburn  7511: sub auto_instcode_format {
1.793     albertel 7512:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7513: 	$cat_order) = @_;
1.521     raeburn  7514:     my $courses = '';
1.772     raeburn  7515:     my @homeservers;
1.521     raeburn  7516:     if ($caller eq 'global') {
1.841     albertel 7517: 	my %servers = &get_servers($codedom,'library');
                   7518: 	foreach my $tryserver (keys(%servers)) {
                   7519: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7520: 		push(@homeservers,$tryserver);
                   7521: 	    }
1.584     raeburn  7522:         }
1.1022    raeburn  7523:     } elsif ($caller eq 'requests') {
                   7524:         if ($codedom =~ /^$match_domain$/) {
                   7525:             my $chome = &domain($codedom,'primary');
                   7526:             unless ($chome eq 'no_host') {
                   7527:                 push(@homeservers,$chome);
                   7528:             }
                   7529:         }
1.521     raeburn  7530:     } else {
1.772     raeburn  7531:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7532:     }
1.793     albertel 7533:     foreach my $code (keys(%{$instcodes})) {
                   7534:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7535:     }
                   7536:     chop($courses);
1.772     raeburn  7537:     my $ok_response = 0;
                   7538:     my $response;
                   7539:     while (@homeservers > 0 && $ok_response == 0) {
                   7540:         my $server = shift(@homeservers); 
                   7541:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7542:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7543:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7544: 		split(/:/,$response);
1.772     raeburn  7545:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7546:             push(@{$codetitles},&str2array($codetitles_str));
                   7547:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7548:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7549:             $ok_response = 1;
                   7550:         }
                   7551:     }
                   7552:     if ($ok_response) {
1.521     raeburn  7553:         return 'ok';
1.772     raeburn  7554:     } else {
                   7555:         return $response;
1.521     raeburn  7556:     }
                   7557: }
                   7558: 
1.792     raeburn  7559: sub auto_instcode_defaults {
                   7560:     my ($domain,$returnhash,$code_order) = @_;
                   7561:     my @homeservers;
1.841     albertel 7562: 
                   7563:     my %servers = &get_servers($domain,'library');
                   7564:     foreach my $tryserver (keys(%servers)) {
                   7565: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7566: 	    push(@homeservers,$tryserver);
                   7567: 	}
1.792     raeburn  7568:     }
1.841     albertel 7569: 
1.792     raeburn  7570:     my $response;
1.841     albertel 7571:     foreach my $server (@homeservers) {
1.792     raeburn  7572:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7573:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7574: 	
                   7575: 	foreach my $pair (split(/\&/,$response)) {
                   7576: 	    my ($name,$value)=split(/\=/,$pair);
                   7577: 	    if ($name eq 'code_order') {
                   7578: 		@{$code_order} = split(/\&/,&unescape($value));
                   7579: 	    } else {
                   7580: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7581: 	    }
                   7582: 	}
                   7583: 	return 'ok';
1.792     raeburn  7584:     }
1.841     albertel 7585: 
                   7586:     return $response;
1.1003    raeburn  7587: }
                   7588: 
                   7589: sub auto_possible_instcodes {
1.1007    raeburn  7590:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7591:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7592:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7593:         return;
                   7594:     }
1.1003    raeburn  7595:     my (@homeservers,$uhome);
                   7596:     if (defined(&domain($domain,'primary'))) {
                   7597:         $uhome=&domain($domain,'primary');
                   7598:         push(@homeservers,&domain($domain,'primary'));
                   7599:     } else {
                   7600:         my %servers = &get_servers($domain,'library');
                   7601:         foreach my $tryserver (keys(%servers)) {
                   7602:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7603:                 push(@homeservers,$tryserver);
                   7604:             }
                   7605:         }
                   7606:     }
                   7607:     my $response;
                   7608:     foreach my $server (@homeservers) {
                   7609:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7610:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7611:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7612:             split(':',$response);
                   7613:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7614:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7615:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7616:             my ($name,$value)=split('=',$item);
                   7617:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7618:         }
                   7619:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7620:             my ($name,$value)=split('=',$item);
                   7621:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7622:         }
                   7623:         return 'ok';
                   7624:     }
                   7625:     return $response;
                   7626: }
1.792     raeburn  7627: 
1.1010    raeburn  7628: sub auto_courserequest_checks {
                   7629:     my ($dom) = @_;
1.1020    raeburn  7630:     my ($homeserver,%validations);
                   7631:     if ($dom =~ /^$match_domain$/) {
                   7632:         $homeserver = &domain($dom,'primary');
                   7633:     }
                   7634:     unless ($homeserver eq 'no_host') {
                   7635:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7636:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7637:             my @items = split(/&/,$response);
                   7638:             foreach my $item (@items) {
                   7639:                 my ($key,$value) = split('=',$item);
                   7640:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7641:             }
                   7642:         }
                   7643:     }
1.1010    raeburn  7644:     return %validations; 
                   7645: }
                   7646: 
1.1020    raeburn  7647: sub auto_courserequest_validation {
                   7648:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7649:     my ($homeserver,$response);
                   7650:     if ($dom =~ /^$match_domain$/) {
                   7651:         $homeserver = &domain($dom,'primary');
                   7652:     }
                   7653:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7654:           
1.1020    raeburn  7655:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7656:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7657:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7658:                                     $homeserver));
                   7659:     }
                   7660:     return $response;
                   7661: }
                   7662: 
1.777     albertel 7663: sub auto_validate_class_sec {
1.918     raeburn  7664:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7665:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7666:     my $ownerlist;
                   7667:     if (ref($owners) eq 'ARRAY') {
                   7668:         $ownerlist = join(',',@{$owners});
                   7669:     } else {
                   7670:         $ownerlist = $owners;
                   7671:     }
1.773     raeburn  7672:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7673:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7674:     return $response;
                   7675: }
                   7676: 
1.679     raeburn  7677: # ------------------------------------------------------- Course Group routines
                   7678: 
                   7679: sub get_coursegroups {
1.809     raeburn  7680:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7681:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7682: }
                   7683: 
1.679     raeburn  7684: sub modify_coursegroup {
                   7685:     my ($cdom,$cnum,$groupsettings) = @_;
                   7686:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7687: }
                   7688: 
1.809     raeburn  7689: sub toggle_coursegroup_status {
                   7690:     my ($cdom,$cnum,$group,$action) = @_;
                   7691:     my ($from_namespace,$to_namespace);
                   7692:     if ($action eq 'delete') {
                   7693:         $from_namespace = 'coursegroups';
                   7694:         $to_namespace = 'deleted_groups';
                   7695:     } else {
                   7696:         $from_namespace = 'deleted_groups';
                   7697:         $to_namespace = 'coursegroups';
                   7698:     }
                   7699:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7700:     if (my $tmp = &error(%curr_group)) {
                   7701:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7702:         return ('read error',$tmp);
                   7703:     } else {
                   7704:         my %savedsettings = %curr_group; 
1.809     raeburn  7705:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7706:         my $deloutcome;
                   7707:         if ($result eq 'ok') {
1.809     raeburn  7708:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7709:         } else {
                   7710:             return ('write error',$result);
                   7711:         }
                   7712:         if ($deloutcome eq 'ok') {
                   7713:             return 'ok';
                   7714:         } else {
                   7715:             return ('delete error',$deloutcome);
                   7716:         }
                   7717:     }
                   7718: }
                   7719: 
1.679     raeburn  7720: sub modify_group_roles {
1.957     raeburn  7721:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7722:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7723:     my $role = 'gr/'.&escape($userprivs);
                   7724:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7725:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7726:     if ($result eq 'ok') {
                   7727:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7728:     }
1.679     raeburn  7729:     return $result;
                   7730: }
                   7731: 
                   7732: sub modify_coursegroup_membership {
                   7733:     my ($cdom,$cnum,$membership) = @_;
                   7734:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7735:     return $result;
                   7736: }
                   7737: 
1.682     raeburn  7738: sub get_active_groups {
                   7739:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7740:     my $now = time;
                   7741:     my %groups = ();
                   7742:     foreach my $key (keys(%env)) {
1.811     albertel 7743:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7744:             my ($start,$end) = split(/\./,$env{$key});
                   7745:             if (($end!=0) && ($end<$now)) { next; }
                   7746:             if (($start!=0) && ($start>$now)) { next; }
                   7747:             if ($1 eq $cdom && $2 eq $cnum) {
                   7748:                 $groups{$3} = $env{$key} ;
                   7749:             }
                   7750:         }
                   7751:     }
                   7752:     return %groups;
                   7753: }
                   7754: 
1.683     raeburn  7755: sub get_group_membership {
                   7756:     my ($cdom,$cnum,$group) = @_;
                   7757:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7758: }
                   7759: 
                   7760: sub get_users_groups {
                   7761:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7762:     my @usersgroups;
1.683     raeburn  7763:     my $cachetime=1800;
                   7764: 
                   7765:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7766:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7767:     if (defined($cached)) {
1.734     albertel 7768:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7769:     } else {  
                   7770:         $grouplist = '';
1.816     raeburn  7771:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7772:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7773:         my $access_end = $env{'course.'.$courseid.
                   7774:                               '.default_enrollment_end_date'};
                   7775:         my $now = time;
                   7776:         foreach my $key (keys(%roleshash)) {
                   7777:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7778:                 my $group = $1;
                   7779:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7780:                     my $start = $2;
                   7781:                     my $end = $1;
                   7782:                     if ($start == -1) { next; } # deleted from group
                   7783:                     if (($start!=0) && ($start>$now)) { next; }
                   7784:                     if (($end!=0) && ($end<$now)) {
                   7785:                         if ($access_end && $access_end < $now) {
                   7786:                             if ($access_end - $end < 86400) {
                   7787:                                 push(@usersgroups,$group);
1.733     raeburn  7788:                             }
                   7789:                         }
1.817     raeburn  7790:                         next;
1.733     raeburn  7791:                     }
1.817     raeburn  7792:                     push(@usersgroups,$group);
1.683     raeburn  7793:                 }
                   7794:             }
                   7795:         }
1.817     raeburn  7796:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7797:         $grouplist = join(':',@usersgroups);
                   7798:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7799:     }
1.733     raeburn  7800:     return @usersgroups;
1.683     raeburn  7801: }
                   7802: 
                   7803: sub devalidate_getgroups_cache {
                   7804:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7805:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7806: 
1.683     raeburn  7807:     my $hashid="$udom:$uname:$courseid";
                   7808:     &devalidate_cache_new('getgroups',$hashid);
                   7809: }
                   7810: 
1.12      www      7811: # ------------------------------------------------------------------ Plain Text
                   7812: 
                   7813: sub plaintext {
1.988     raeburn  7814:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7815:     if ($short =~ m{^cr/}) {
1.758     albertel 7816: 	return (split('/',$short))[-1];
                   7817:     }
1.742     raeburn  7818:     if (!defined($cid)) {
                   7819:         $cid = $env{'request.course.id'};
                   7820:     }
                   7821:     my %rolenames = (
1.1008    raeburn  7822:                       Course    => 'std',
                   7823:                       Community => 'alt1',
1.742     raeburn  7824:                     );
1.1037    raeburn  7825:     if ($cid ne '') {
                   7826:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7827:             unless ($forcedefault) {
                   7828:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7829:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7830:                 return &Apache::lonlocal::mt($roletext);
                   7831:             }
                   7832:         }
                   7833:     }
                   7834:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7835:         (defined($rolenames{$type})) && 
                   7836:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7837:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7838:     } elsif ($cid ne '') {
                   7839:         my $crstype = $env{'course.'.$cid.'.type'};
                   7840:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7841:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7842:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7843:         }
1.742     raeburn  7844:     }
1.1037    raeburn  7845:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7846: }
                   7847: 
                   7848: # ----------------------------------------------------------------- Assign Role
                   7849: 
                   7850: sub assignrole {
1.957     raeburn  7851:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7852:         $context)=@_;
1.21      www      7853:     my $mrole;
                   7854:     if ($role =~ /^cr\//) {
1.393     www      7855:         my $cwosec=$url;
1.811     albertel 7856:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7857: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7858:            my $refused = 1;
                   7859:            if ($context eq 'requestcourses') {
                   7860:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7861:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7862:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7863:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7864:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7865:                            if ($crsenv{'internal.courseowner'} eq
                   7866:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7867:                                $refused = '';
                   7868:                            }
                   7869:                        }
                   7870:                    }
                   7871:                }
                   7872:            }
                   7873:            if ($refused) {
                   7874:                &logthis('Refused custom assignrole: '.
                   7875:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7876:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7877:                return 'refused';
                   7878:            }
1.104     www      7879:         }
1.21      www      7880:         $mrole='cr';
1.678     raeburn  7881:     } elsif ($role =~ /^gr\//) {
                   7882:         my $cwogrp=$url;
1.811     albertel 7883:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7884:         unless (&allowed('mdg',$cwogrp)) {
                   7885:             &logthis('Refused group assignrole: '.
                   7886:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7887:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7888:             return 'refused';
                   7889:         }
                   7890:         $mrole='gr';
1.21      www      7891:     } else {
1.82      www      7892:         my $cwosec=$url;
1.811     albertel 7893:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7894:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7895:             my $refused;
                   7896:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7897:                 if (!(&allowed('c'.$role,$url))) {
                   7898:                     $refused = 1;
                   7899:                 }
                   7900:             } else {
                   7901:                 $refused = 1;
                   7902:             }
1.947     raeburn  7903:             if ($refused) {
1.1045    raeburn  7904:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7905:                 if (!$selfenroll && $context eq 'course') {
                   7906:                     my %crsenv;
                   7907:                     if ($role eq 'cc' || $role eq 'co') {
                   7908:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7909:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7910:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7911:                                 if ($crsenv{'internal.courseowner'} eq 
                   7912:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7913:                                     $refused = '';
                   7914:                                 }
                   7915:                             }
                   7916:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7917:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7918:                                 if ($crsenv{'internal.courseowner'} eq 
                   7919:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7920:                                     $refused = '';
                   7921:                                 }
                   7922:                             }
                   7923:                         }
                   7924:                     }
                   7925:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7926:                     $refused = '';
1.1017    raeburn  7927:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7928:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7929:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7930:                         my $wrongcc;
                   7931:                         if ($cnum =~ /^$match_community$/) {
                   7932:                             $wrongcc = 1 if ($role eq 'cc');
                   7933:                         } else {
                   7934:                             $wrongcc = 1 if ($role eq 'co');
                   7935:                         }
                   7936:                         unless ($wrongcc) {
                   7937:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7938:                             if ($crsenv{'internal.courseowner'} eq 
                   7939:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7940:                                 $refused = '';
                   7941:                             }
1.1017    raeburn  7942:                         }
                   7943:                     }
1.1172.2.9  raeburn  7944:                 } elsif ($context eq 'requestauthor') {
                   7945:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7946:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7947:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7948:                             $refused = '';
                   7949:                         } else {
                   7950:                             my %domdefaults = &get_domain_defaults($udom);
                   7951:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7952:                                 my $checkbystatus;
                   7953:                                 if ($env{'user.adv'}) {
                   7954:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7955:                                     if ($disposition eq 'automatic') {
                   7956:                                         $refused = '';
                   7957:                                     } elsif ($disposition eq '') {
                   7958:                                         $checkbystatus = 1;
                   7959:                                     }
                   7960:                                 } else {
                   7961:                                     $checkbystatus = 1;
                   7962:                                 }
                   7963:                                 if ($checkbystatus) {
                   7964:                                     if ($env{'environment.inststatus'}) {
                   7965:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7966:                                         foreach my $type (@inststatuses) {
                   7967:                                             if (($type ne '') &&
                   7968:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7969:                                                 $refused = '';
                   7970:                                             }
                   7971:                                         }
                   7972:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7973:                                         $refused = '';
                   7974:                                     }
                   7975:                                 }
                   7976:                             }
                   7977:                         }
                   7978:                     }
1.1017    raeburn  7979:                 }
                   7980:                 if ($refused) {
1.947     raeburn  7981:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7982:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7983: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7984:                     return 'refused';
                   7985:                 }
1.932     raeburn  7986:             }
1.1131    raeburn  7987:         } elsif ($role eq 'au') {
                   7988:             if ($url ne '/'.$udom.'/') {
                   7989:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7990:                          ' to assign author role for '.$uname.':'.$udom.
                   7991:                          ' in domain: '.$url.' refused (wrong domain).');
                   7992:                 return 'refused';
                   7993:             }
1.104     www      7994:         }
1.21      www      7995:         $mrole=$role;
                   7996:     }
1.620     albertel 7997:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7998:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7999:     if ($end) { $command.='_'.$end; }
1.21      www      8000:     if ($start) {
                   8001: 	if ($end) { 
1.81      www      8002:            $command.='_'.$start; 
1.21      www      8003:         } else {
1.81      www      8004:            $command.='_0_'.$start;
1.21      www      8005:         }
                   8006:     }
1.739     raeburn  8007:     my $origstart = $start;
                   8008:     my $origend = $end;
1.957     raeburn  8009:     my $delflag;
1.357     www      8010: # actually delete
                   8011:     if ($deleteflag) {
1.373     www      8012: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8013: # modify command to delete the role
1.620     albertel 8014:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8015:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8016: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8017: # set start and finish to negative values for userrolelog
                   8018:            $start=-1;
                   8019:            $end=-1;
1.957     raeburn  8020:            $delflag = 1;
1.357     www      8021:         }
                   8022:     }
                   8023: # send command
1.349     www      8024:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8025: # log new user role if status is ok
1.349     www      8026:     if ($answer eq 'ok') {
1.663     raeburn  8027: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8028:         if (($role eq 'cc') || ($role eq 'in') ||
                   8029:             ($role eq 'ep') || ($role eq 'ad') ||
                   8030:             ($role eq 'ta') || ($role eq 'st') ||
                   8031:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8032:             ($role eq 'co')) {
1.1172.2.13  raeburn  8033: # for course roles, perform group memberships changes triggered by role change.
                   8034:             unless ($role =~ /^gr/) {
                   8035:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8036:                                                  $origstart,$selfenroll,$context);
                   8037:             }
1.1172.2.9  raeburn  8038:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8039:                            $selfenroll,$context);
                   8040:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8041:                  ($role eq 'au') || ($role eq 'dc')) {
                   8042:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8043:                            $context);
                   8044:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8045:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8046:                              $context);
                   8047:         }
1.1053    raeburn  8048:         if ($role eq 'cc') {
                   8049:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8050:         }
1.349     www      8051:     }
                   8052:     return $answer;
1.169     harris41 8053: }
                   8054: 
1.1053    raeburn  8055: sub autoupdate_coowners {
                   8056:     my ($url,$end,$start,$uname,$udom) = @_;
                   8057:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8058:     if (($cdom ne '') && ($cnum ne '')) {
                   8059:         my $now = time;
                   8060:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8061:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8062:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8063:             my $instcode = $coursehash{'internal.coursecode'};
                   8064:             if ($instcode ne '') {
1.1056    raeburn  8065:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8066:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8067:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8068:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8069:                         if ($result eq 'valid') {
                   8070:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8071:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8072:                                     push(@newcoowners,$coowner);
                   8073:                                 }
                   8074:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8075:                                     push(@newcoowners,$uname.':'.$udom);
                   8076:                                 }
                   8077:                                 @newcoowners = sort(@newcoowners);
                   8078:                             } else {
                   8079:                                 push(@newcoowners,$uname.':'.$udom);
                   8080:                             }
                   8081:                         } else {
                   8082:                             if ($coursehash{'internal.co-owners'}) {
                   8083:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8084:                                     unless ($coowner eq $uname.':'.$udom) {
                   8085:                                         push(@newcoowners,$coowner);
                   8086:                                     }
                   8087:                                 }
                   8088:                                 unless (@newcoowners > 0) {
                   8089:                                     $delcoowners = 1;
                   8090:                                     $coowners = '';
                   8091:                                 }
                   8092:                             }
                   8093:                         }
                   8094:                         if (@newcoowners || $delcoowners) {
                   8095:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8096:                                             $delcoowners,@newcoowners);
                   8097:                         }
                   8098:                     }
                   8099:                 }
                   8100:             }
                   8101:         }
                   8102:     }
                   8103: }
                   8104: 
                   8105: sub store_coowners {
                   8106:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8107:     my $cid = $cdom.'_'.$cnum;
                   8108:     my ($coowners,$delresult,$putresult);
                   8109:     if (@newcoowners) {
                   8110:         $coowners = join(',',@newcoowners);
                   8111:         my %coownershash = (
                   8112:                             'internal.co-owners' => $coowners,
                   8113:                            );
                   8114:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8115:         if ($putresult eq 'ok') {
                   8116:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8117:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8118:             }
                   8119:         }
                   8120:     }
                   8121:     if ($delcoowners) {
                   8122:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8123:         if ($delresult eq 'ok') {
                   8124:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8125:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8126:             }
                   8127:         }
                   8128:     }
                   8129:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8130:         my %crsinfo =
                   8131:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8132:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8133:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8134:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8135:         }
                   8136:     }
                   8137: }
                   8138: 
1.169     harris41 8139: # -------------------------------------------------- Modify user authentication
1.197     www      8140: # Overrides without validation
                   8141: 
1.169     harris41 8142: sub modifyuserauth {
                   8143:     my ($udom,$uname,$umode,$upass)=@_;
                   8144:     my $uhome=&homeserver($uname,$udom);
1.197     www      8145:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8146:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8147:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8148:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8149:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8150: 		     &escape($upass),$uhome);
1.620     albertel 8151:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8152:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8153:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8154:     &log($udom,,$uname,$uhome,
1.620     albertel 8155:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8156:                                      $env{'user.name'}.', '.$umode.
1.197     www      8157:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8158:     unless ($reply eq 'ok') {
1.197     www      8159:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8160: 	return 'error: '.$reply;
                   8161:     }   
1.170     harris41 8162:     return 'ok';
1.80      www      8163: }
                   8164: 
1.81      www      8165: # --------------------------------------------------------------- Modify a user
1.80      www      8166: 
1.81      www      8167: sub modifyuser {
1.206     matthew  8168:     my ($udom,    $uname, $uid,
                   8169:         $umode,   $upass, $first,
                   8170:         $middle,  $last,  $gene,
1.1058    raeburn  8171:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8172:     $udom= &LONCAPA::clean_domain($udom);
                   8173:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8174:     my $showcandelete = 'none';
                   8175:     if (ref($candelete) eq 'ARRAY') {
                   8176:         if (@{$candelete} > 0) {
                   8177:             $showcandelete = join(', ',@{$candelete});
                   8178:         }
                   8179:     }
1.81      www      8180:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8181:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8182: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8183:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8184:                                      ' desiredhome not specified'). 
1.620     albertel 8185:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8186:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8187:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8188:     my $newuser;
                   8189:     if ($uhome eq 'no_host') {
                   8190:         $newuser = 1;
                   8191:     }
1.80      www      8192: # ----------------------------------------------------------------- Create User
1.406     albertel 8193:     if (($uhome eq 'no_host') && 
                   8194: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8195:         my $unhome='';
1.844     albertel 8196:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8197:             $unhome = $desiredhome;
1.620     albertel 8198: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8199: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8200:         } else { # load balancing routine for determining $unhome
1.81      www      8201:             my $loadm=10000000;
1.841     albertel 8202: 	    my %servers = &get_servers($udom,'library');
                   8203: 	    foreach my $tryserver (keys(%servers)) {
                   8204: 		my $answer=reply('load',$tryserver);
                   8205: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8206: 		    $loadm=$answer;
                   8207: 		    $unhome=$tryserver;
                   8208: 		}
1.80      www      8209: 	    }
                   8210:         }
                   8211:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8212: 	    return 'error: unable to find a home server for '.$uname.
                   8213:                    ' in domain '.$udom;
1.80      www      8214:         }
                   8215:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8216:                          &escape($upass),$unhome);
                   8217: 	unless ($reply eq 'ok') {
                   8218:             return 'error: '.$reply;
                   8219:         }   
1.230     stredwic 8220:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8221:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8222: 	    return 'error: unable verify users home machine.';
1.80      www      8223:         }
1.209     matthew  8224:     }   # End of creation of new user
1.80      www      8225: # ---------------------------------------------------------------------- Add ID
                   8226:     if ($uid) {
                   8227:        $uid=~tr/A-Z/a-z/;
                   8228:        my %uidhash=&idrget($udom,$uname);
1.196     www      8229:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8230:          && (!$forceid)) {
1.80      www      8231: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8232: 	      return 'error: user id "'.$uid.'" does not match '.
                   8233:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8234:           }
                   8235:        } else {
                   8236: 	  &idput($udom,($uname => $uid));
                   8237:        }
                   8238:     }
                   8239: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8240:     my @tmp=&get('environment',
1.899     raeburn  8241: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8242:                     'permanentemail','inststatus'],
1.134     albertel 8243: 		   $udom,$uname);
1.1075    raeburn  8244:     my (%names,%oldnames);
1.313     matthew  8245:     if ($tmp[0] =~ m/^error:.*/) { 
                   8246:         %names=(); 
                   8247:     } else {
                   8248:         %names = @tmp;
1.1075    raeburn  8249:         %oldnames = %names;
1.313     matthew  8250:     }
1.388     www      8251: #
1.1058    raeburn  8252: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8253: # of users did not contain them), do not overwrite existing values
                   8254: # unless field is in $candelete array ref.  
                   8255: #
                   8256: 
                   8257:     my @fields = ('firstname','middlename','lastname','generation',
                   8258:                   'permanentemail','id');
                   8259:     my %newvalues;
                   8260:     if (ref($candelete) eq 'ARRAY') {
                   8261:         foreach my $field (@fields) {
                   8262:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8263:                 if ($field eq 'firstname') {
                   8264:                     $names{$field} = $first;
                   8265:                 } elsif ($field eq 'middlename') {
                   8266:                     $names{$field} = $middle;
                   8267:                 } elsif ($field eq 'lastname') {
                   8268:                     $names{$field} = $last;
                   8269:                 } elsif ($field eq 'generation') { 
                   8270:                     $names{$field} = $gene;
                   8271:                 } elsif ($field eq 'permanentemail') {
                   8272:                     $names{$field} = $email;
                   8273:                 } elsif ($field eq 'id') {
                   8274:                     $names{$field}  = $uid;
                   8275:                 }
                   8276:             }
                   8277:         }
                   8278:     }
1.388     www      8279:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8280:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8281:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8282:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8283:     if ($email) {
                   8284:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8285:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8286:     }
1.899     raeburn  8287:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8288:     if (defined($inststatus)) {
                   8289:         $names{'inststatus'} = '';
                   8290:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8291:         if (ref($usertypes) eq 'HASH') {
                   8292:             my @okstatuses; 
                   8293:             foreach my $item (split(/:/,$inststatus)) {
                   8294:                 if (defined($usertypes->{$item})) {
                   8295:                     push(@okstatuses,$item);  
                   8296:                 }
                   8297:             }
                   8298:             if (@okstatuses) {
                   8299:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8300:             }
                   8301:         }
                   8302:     }
1.1075    raeburn  8303:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8304:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8305:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8306:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8307:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8308:     } else {
                   8309:         $logmsg .= ' during self creation';
                   8310:     }
1.1075    raeburn  8311:     my $changed;
                   8312:     if ($newuser) {
                   8313:         $changed = 1;
                   8314:     } else {
                   8315:         foreach my $field (@fields) {
                   8316:             if ($names{$field} ne $oldnames{$field}) {
                   8317:                 $changed = 1;
                   8318:                 last;
                   8319:             }
                   8320:         }
                   8321:     }
                   8322:     unless ($changed) {
                   8323:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8324:         &logthis($logmsg);
                   8325:         return 'ok';
                   8326:     }
                   8327:     my $reply = &put('environment', \%names, $udom,$uname);
                   8328:     if ($reply ne 'ok') { 
                   8329:         return 'error: '.$reply;
                   8330:     }
1.1087    raeburn  8331:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8332:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8333:     }
1.1075    raeburn  8334:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8335:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8336:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8337:     &logthis($logmsg);
1.134     albertel 8338:     return 'ok';
1.80      www      8339: }
                   8340: 
1.81      www      8341: # -------------------------------------------------------------- Modify student
1.80      www      8342: 
1.81      www      8343: sub modifystudent {
                   8344:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8345:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8346:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8347:     if (!$cid) {
1.620     albertel 8348: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8349: 	    return 'not_in_class';
                   8350: 	}
1.80      www      8351:     }
                   8352: # --------------------------------------------------------------- Make the user
1.81      www      8353:     my $reply=&modifyuser
1.209     matthew  8354: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8355:          $desiredhome,$email,$inststatus);
1.80      www      8356:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8357:     # This will cause &modify_student_enrollment to get the uid from the
                   8358:     # students environment
                   8359:     $uid = undef if (!$forceid);
1.455     albertel 8360:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8361: 					$gene,$usec,$end,$start,$type,$locktype,
                   8362:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8363:     return $reply;
                   8364: }
                   8365: 
                   8366: sub modify_student_enrollment {
1.1172.2.19  raeburn  8367:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8368:     my ($cdom,$cnum,$chome);
                   8369:     if (!$cid) {
1.620     albertel 8370: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8371: 	    return 'not_in_class';
                   8372: 	}
1.620     albertel 8373: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8374: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8375:     } else {
                   8376: 	($cdom,$cnum)=split(/_/,$cid);
                   8377:     }
1.620     albertel 8378:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8379:     if (!$chome) {
1.457     raeburn  8380: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8381:     }
1.455     albertel 8382:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8383:     # Make sure the user exists
1.81      www      8384:     my $uhome=&homeserver($uname,$udom);
                   8385:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8386: 	return 'error: no such user';
                   8387:     }
1.297     matthew  8388:     # Get student data if we were not given enough information
                   8389:     if (!defined($first)  || $first  eq '' || 
                   8390:         !defined($last)   || $last   eq '' || 
                   8391:         !defined($uid)    || $uid    eq '' || 
                   8392:         !defined($middle) || $middle eq '' || 
                   8393:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8394:         # They did not supply us with enough data to enroll the student, so
                   8395:         # we need to pick up more information.
1.297     matthew  8396:         my %tmp = &get('environment',
1.294     matthew  8397:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8398:                        ,$udom,$uname);
                   8399: 
1.800     albertel 8400:         #foreach my $key (keys(%tmp)) {
                   8401:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8402:         #}
1.294     matthew  8403:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8404:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8405:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8406:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8407:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8408:     }
1.556     albertel 8409:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8410:     my $user = "$uname:$udom";
                   8411:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8412:     my $reply=cput('classlist',
1.1148    raeburn  8413: 		   {$user => 
1.1172.2.19  raeburn  8414: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8415: 		   $cdom,$cnum);
1.1148    raeburn  8416:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8417:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8418:     } else { 
1.81      www      8419: 	return 'error: '.$reply;
                   8420:     }
1.297     matthew  8421:     # Add student role to user
1.83      www      8422:     my $uurl='/'.$cid;
1.81      www      8423:     $uurl=~s/\_/\//g;
                   8424:     if ($usec) {
                   8425: 	$uurl.='/'.$usec;
                   8426:     }
1.1148    raeburn  8427:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8428:                              $selfenroll,$context);
                   8429:     if ($result ne 'ok') {
                   8430:         if ($old_entry{$user} ne '') {
                   8431:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8432:         } else {
                   8433:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8434:         }
                   8435:     }
                   8436:     return $result; 
1.21      www      8437: }
                   8438: 
1.556     albertel 8439: sub format_name {
                   8440:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8441:     my $name;
                   8442:     if ($first ne 'lastname') {
                   8443: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8444:     } else {
                   8445: 	if ($lastname=~/\S/) {
                   8446: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8447: 	    $name=~s/\s+,/,/;
                   8448: 	} else {
                   8449: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8450: 	}
                   8451:     }
                   8452:     $name=~s/^\s+//;
                   8453:     $name=~s/\s+$//;
                   8454:     $name=~s/\s+/ /g;
                   8455:     return $name;
                   8456: }
                   8457: 
1.84      www      8458: # ------------------------------------------------- Write to course preferences
                   8459: 
                   8460: sub writecoursepref {
                   8461:     my ($courseid,%prefs)=@_;
                   8462:     $courseid=~s/^\///;
                   8463:     $courseid=~s/\_/\//g;
                   8464:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8465:     my $chome=homeserver($cnum,$cdomain);
                   8466:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8467: 	return 'error: no such course';
                   8468:     }
                   8469:     my $cstring='';
1.800     albertel 8470:     foreach my $pref (keys(%prefs)) {
                   8471: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8472:     }
1.84      www      8473:     $cstring=~s/\&$//;
                   8474:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8475: }
                   8476: 
                   8477: # ---------------------------------------------------------- Make/modify course
                   8478: 
                   8479: sub createcourse {
1.741     raeburn  8480:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8481:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8482:     $url=&declutter($url);
                   8483:     my $cid='';
1.1028    raeburn  8484:     if ($context eq 'requestcourses') {
                   8485:         my $can_create = 0;
                   8486:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8487:         if ($udom eq $ownerdom) {
                   8488:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8489:                                   $context)) {
                   8490:                 $can_create = 1;
                   8491:             }
                   8492:         } else {
                   8493:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8494:                                            $category);
                   8495:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8496:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8497:                 if (@curr > 0) {
                   8498:                     my @options = qw(approval validate autolimit);
                   8499:                     my $optregex = join('|',@options);
                   8500:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8501:                         $can_create = 1;
                   8502:                     }
                   8503:                 }
                   8504:             }
                   8505:         }
                   8506:         if ($can_create) {
                   8507:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8508:                 unless (&allowed('ccc',$udom)) {
                   8509:                     return 'refused'; 
                   8510:                 }
1.1017    raeburn  8511:             }
                   8512:         } else {
                   8513:             return 'refused';
                   8514:         }
1.1028    raeburn  8515:     } elsif (!&allowed('ccc',$udom)) {
                   8516:         return 'refused';
1.84      www      8517:     }
1.1011    raeburn  8518: # --------------------------------------------------------------- Get Unique ID
                   8519:     my $uname;
                   8520:     if ($cnum =~ /^$match_courseid$/) {
                   8521:         my $chome=&homeserver($cnum,$udom,'true');
                   8522:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8523:             $uname = $cnum;
                   8524:         } else {
1.1038    raeburn  8525:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8526:         }
                   8527:     } else {
1.1038    raeburn  8528:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8529:     }
                   8530:     return $uname if ($uname =~ /^error/);
                   8531: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8532:     if (!defined($course_server)) {
                   8533:         if (defined(&domain($udom,'primary'))) {
                   8534:             $course_server = &domain($udom,'primary');
                   8535:         } else {
                   8536:             $course_server = $env{'user.home'}; 
                   8537:         }
                   8538:     }
                   8539:     my %host_servers =
                   8540:         &Apache::lonnet::get_servers($udom,'library');
                   8541:     unless ($host_servers{$course_server}) {
                   8542:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8543:     }
1.84      www      8544: # ------------------------------------------------------------- Make the course
                   8545:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8546:                       $course_server);
1.84      www      8547:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8548:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8549:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8550: 	return 'error: no such course';
                   8551:     }
1.271     www      8552: # ----------------------------------------------------------------- Course made
1.516     raeburn  8553: # log existence
1.1029    raeburn  8554:     my $now = time;
1.918     raeburn  8555:     my $newcourse = {
                   8556:                     $udom.'_'.$uname => {
1.921     raeburn  8557:                                      description => $description,
                   8558:                                      inst_code   => $inst_code,
                   8559:                                      owner       => $course_owner,
                   8560:                                      type        => $crstype,
1.1029    raeburn  8561:                                      creator     => $env{'user.name'}.':'.
                   8562:                                                     $env{'user.domain'},
                   8563:                                      created     => $now,
                   8564:                                      context     => $context,
1.918     raeburn  8565:                                                 },
                   8566:                     };
1.921     raeburn  8567:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8568: # set toplevel url
1.271     www      8569:     my $topurl=$url;
                   8570:     unless ($nonstandard) {
                   8571: # ------------------------------------------ For standard courses, make top url
                   8572:         my $mapurl=&clutter($url);
1.278     www      8573:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8574:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8575: <map>
                   8576: <resource id="1" type="start"></resource>
                   8577: <resource id="2" src="$mapurl"></resource>
                   8578: <resource id="3" type="finish"></resource>
                   8579: <link index="1" from="1" to="2"></link>
                   8580: <link index="2" from="2" to="3"></link>
                   8581: </map>
                   8582: ENDINITMAP
                   8583:         $topurl=&declutter(
1.638     albertel 8584:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8585:                           );
                   8586:     }
                   8587: # ----------------------------------------------------------- Write preferences
1.84      www      8588:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8589:                      ('description'              => $description,
                   8590:                       'url'                      => $topurl,
                   8591:                       'internal.creator'         => $env{'user.name'}.':'.
                   8592:                                                     $env{'user.domain'},
                   8593:                       'internal.created'         => $now,
                   8594:                       'internal.creationcontext' => $context)
                   8595:                     );
1.84      www      8596:     return '/'.$udom.'/'.$uname;
                   8597: }
                   8598: 
1.1011    raeburn  8599: # ------------------------------------------------------------------- Create ID
                   8600: sub generate_coursenum {
1.1038    raeburn  8601:     my ($udom,$crstype) = @_;
1.1011    raeburn  8602:     my $domdesc = &domain($udom);
                   8603:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8604:     my $first;
                   8605:     if ($crstype eq 'Community') {
                   8606:         $first = '0';
                   8607:     } else {
                   8608:         $first = int(1+rand(9)); 
                   8609:     } 
                   8610:     my $uname=$first.
1.1011    raeburn  8611:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8612:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8613:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8614: # ----------------------------------------------- Make sure that does not exist
                   8615:     my $uhome=&homeserver($uname,$udom,'true');
                   8616:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8617:         if ($crstype eq 'Community') {
                   8618:             $first = '0';
                   8619:         } else {
                   8620:             $first = int(1+rand(9));
                   8621:         }
                   8622:         $uname=$first.
1.1011    raeburn  8623:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8624:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8625:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8626:         $uhome=&homeserver($uname,$udom,'true');
                   8627:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8628:             return 'error: unable to generate unique course-ID';
                   8629:         }
                   8630:     }
                   8631:     return $uname;
                   8632: }
                   8633: 
1.813     albertel 8634: sub is_course {
1.1167    droeschl 8635:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8636:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8637: 
                   8638:     return unless $cdom and $cnum;
                   8639: 
                   8640:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8641:         '.');
                   8642: 
                   8643:     return unless exists($courses{$cdom.'_'.$cnum});
                   8644:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8645: }
                   8646: 
1.1015    raeburn  8647: sub store_userdata {
                   8648:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8649:     my $result;
1.1016    raeburn  8650:     if ($datakey ne '') {
1.1013    raeburn  8651:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8652:             if ($udom eq '' || $uname eq '') {
                   8653:                 $udom = $env{'user.domain'};
                   8654:                 $uname = $env{'user.name'};
                   8655:             }
                   8656:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8657:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8658:                 $result = 'error: no_host';
                   8659:             } else {
                   8660:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8661:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8662: 
                   8663:                 my $namevalue='';
                   8664:                 foreach my $key (keys(%{$storehash})) {
                   8665:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8666:                 }
                   8667:                 $namevalue=~s/\&$//;
1.1105    raeburn  8668:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8669:                                   $namevalue,$uhome);
1.1013    raeburn  8670:             }
                   8671:         } else {
                   8672:             $result = 'error: data to store was not a hash reference'; 
                   8673:         }
                   8674:     } else {
                   8675:         $result= 'error: invalid requestkey'; 
                   8676:     }
                   8677:     return $result;
                   8678: }
                   8679: 
1.21      www      8680: # ---------------------------------------------------------- Assign Custom Role
                   8681: 
                   8682: sub assigncustomrole {
1.957     raeburn  8683:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8684:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8685:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8686: }
                   8687: 
                   8688: # ----------------------------------------------------------------- Revoke Role
                   8689: 
                   8690: sub revokerole {
1.957     raeburn  8691:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8692:     my $now=time;
1.965     raeburn  8693:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8694: }
                   8695: 
                   8696: # ---------------------------------------------------------- Revoke Custom Role
                   8697: 
                   8698: sub revokecustomrole {
1.957     raeburn  8699:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8700:     my $now=time;
1.357     www      8701:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8702:            $deleteflag,$selfenroll,$context);
1.17      www      8703: }
                   8704: 
1.533     banghart 8705: # ------------------------------------------------------------ Disk usage
1.535     albertel 8706: sub diskusage {
1.955     raeburn  8707:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8708:     $directorypath =~ s/\/$//;
                   8709:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8710:                        .&escape($getpropath).':'.&escape($uname).':'
                   8711:                        .&escape($udom),homeserver($uname,$udom));
                   8712:     if ($listing eq 'unknown_cmd') {
                   8713:         if ($getpropath) {
                   8714:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8715:         }
                   8716:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8717:     }
1.514     albertel 8718:     return $listing;
1.512     banghart 8719: }
                   8720: 
1.566     banghart 8721: sub is_locked {
1.1096    raeburn  8722:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8723:     my @check;
                   8724:     my $is_locked;
1.1093    raeburn  8725:     push (@check,$file_name);
1.613     albertel 8726:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8727: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8728:     my ($tmp)=keys(%locked);
                   8729:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8730:     
1.566     banghart 8731:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8732:         $is_locked = 'false';
                   8733:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8734:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8735:                $is_locked = 'true';
1.1096    raeburn  8736:                if (ref($which) eq 'ARRAY') {
                   8737:                    push(@{$which},$entry);
                   8738:                } else {
                   8739:                    last;
                   8740:                }
1.745     raeburn  8741:            }
                   8742:        }
1.566     banghart 8743:     } else {
                   8744:         $is_locked = 'false';
                   8745:     }
1.1093    raeburn  8746:     return $is_locked;
1.566     banghart 8747: }
                   8748: 
1.759     albertel 8749: sub declutter_portfile {
                   8750:     my ($file) = @_;
1.833     albertel 8751:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8752:     return $file;
                   8753: }
                   8754: 
1.559     banghart 8755: # ------------------------------------------------------------- Mark as Read Only
                   8756: 
                   8757: sub mark_as_readonly {
                   8758:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8759:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8760:     my ($tmp)=keys(%current_permissions);
                   8761:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8762:     foreach my $file (@{$files}) {
1.759     albertel 8763: 	$file = &declutter_portfile($file);
1.561     banghart 8764:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8765:     }
1.613     albertel 8766:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8767:     return;
                   8768: }
                   8769: 
1.572     banghart 8770: # ------------------------------------------------------------Save Selected Files
                   8771: 
                   8772: sub save_selected_files {
                   8773:     my ($user, $path, @files) = @_;
                   8774:     my $filename = $user."savedfiles";
1.573     banghart 8775:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8776:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8777:     foreach my $file (@files) {
1.620     albertel 8778:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8779:     }
                   8780:     foreach my $file (@other_files) {
1.574     banghart 8781:         print (OUT $file."\n");
1.572     banghart 8782:     }
1.574     banghart 8783:     close (OUT);
1.572     banghart 8784:     return 'ok';
                   8785: }
                   8786: 
1.574     banghart 8787: sub clear_selected_files {
                   8788:     my ($user) = @_;
                   8789:     my $filename = $user."savedfiles";
1.1117    foxr     8790:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8791:     print (OUT undef);
                   8792:     close (OUT);
                   8793:     return ("ok");    
                   8794: }
                   8795: 
1.572     banghart 8796: sub files_in_path {
                   8797:     my ($user, $path) = @_;
                   8798:     my $filename = $user."savedfiles";
                   8799:     my %return_files;
1.1117    foxr     8800:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8801:     while (my $line_in = <IN>) {
1.574     banghart 8802:         chomp ($line_in);
                   8803:         my @paths_and_file = split (m!/!, $line_in);
                   8804:         my $file_part = pop (@paths_and_file);
                   8805:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8806:         $path_part.='/';
                   8807:         my $path_and_file = $path_part.$file_part;
                   8808:         if ($path_part eq $path) {
                   8809:             $return_files{$file_part}= 'selected';
                   8810:         }
                   8811:     }
1.574     banghart 8812:     close (IN);
                   8813:     return (\%return_files);
1.572     banghart 8814: }
                   8815: 
                   8816: # called in portfolio select mode, to show files selected NOT in current directory
                   8817: sub files_not_in_path {
                   8818:     my ($user, $path) = @_;
                   8819:     my $filename = $user."savedfiles";
                   8820:     my @return_files;
                   8821:     my $path_part;
1.1117    foxr     8822:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8823:     while (my $line = <IN>) {
1.572     banghart 8824:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8825:         my @paths_and_file = split(m|/|, $line);
                   8826:         my $file_part = pop(@paths_and_file);
                   8827:         chomp($file_part);
                   8828:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8829:         $path_part .= '/';
                   8830:         my $path_and_file = $path_part.$file_part;
                   8831:         if ($path_part ne $path) {
1.800     albertel 8832:             push(@return_files, ($path_and_file));
1.572     banghart 8833:         }
                   8834:     }
1.800     albertel 8835:     close(OUT);
1.574     banghart 8836:     return (@return_files);
1.572     banghart 8837: }
                   8838: 
1.745     raeburn  8839: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8840: 
1.745     raeburn  8841: sub get_portfile_permissions {
                   8842:     my ($domain,$user) = @_;
1.613     albertel 8843:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8844:     my ($tmp)=keys(%current_permissions);
                   8845:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8846:     return \%current_permissions;
                   8847: }
                   8848: 
                   8849: #---------------------------------------------Get portfolio file access controls
                   8850: 
1.749     raeburn  8851: sub get_access_controls {
1.745     raeburn  8852:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8853:     my %access;
                   8854:     my $real_file = $file;
                   8855:     $file =~ s/\.meta$//;
1.745     raeburn  8856:     if (defined($file)) {
1.749     raeburn  8857:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8858:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8859:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8860:             }
                   8861:         }
1.745     raeburn  8862:     } else {
1.749     raeburn  8863:         foreach my $key (keys(%{$current_permissions})) {
                   8864:             if ($key =~ /\0accesscontrol$/) {
                   8865:                 if (defined($group)) {
                   8866:                     if ($key !~ m-^\Q$group\E/-) {
                   8867:                         next;
                   8868:                     }
                   8869:                 }
                   8870:                 my ($fullpath) = split(/\0/,$key);
                   8871:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8872:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8873:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8874:                     }
                   8875:                 }
                   8876:             }
                   8877:         }
                   8878:     }
                   8879:     return %access;
                   8880: }
                   8881: 
                   8882: sub modify_access_controls {
                   8883:     my ($file_name,$changes,$domain,$user)=@_;
                   8884:     my ($outcome,$deloutcome);
                   8885:     my %store_permissions;
                   8886:     my %new_values;
                   8887:     my %new_control;
                   8888:     my %translation;
                   8889:     my @deletions = ();
                   8890:     my $now = time;
                   8891:     if (exists($$changes{'activate'})) {
                   8892:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8893:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8894:             my $numnew = scalar(@newitems);
                   8895:             for (my $i=0; $i<$numnew; $i++) {
                   8896:                 my $newkey = $newitems[$i];
                   8897:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8898:                 if ($newkey =~ /^\d+:/) { 
                   8899:                     $newkey =~ s/^(\d+)/$newid/;
                   8900:                     $translation{$1} = $newid;
                   8901:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8902:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8903:                     $translation{$1} = $newid;
                   8904:                 }
1.749     raeburn  8905:                 $new_values{$file_name."\0".$newkey} = 
                   8906:                                           $$changes{'activate'}{$newitems[$i]};
                   8907:                 $new_control{$newkey} = $now;
                   8908:             }
                   8909:         }
                   8910:     }
                   8911:     my %todelete;
                   8912:     my %changed_items;
                   8913:     foreach my $action ('delete','update') {
                   8914:         if (exists($$changes{$action})) {
                   8915:             if (ref($$changes{$action}) eq 'HASH') {
                   8916:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8917:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8918:                     if ($action eq 'delete') { 
                   8919:                         $todelete{$itemnum} = 1;
                   8920:                     } else {
                   8921:                         $changed_items{$itemnum} = $key;
                   8922:                     }
                   8923:                 }
1.745     raeburn  8924:             }
                   8925:         }
1.749     raeburn  8926:     }
                   8927:     # get lock on access controls for file.
                   8928:     my $lockhash = {
                   8929:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8930:                                                        ':'.$env{'user.domain'},
                   8931:                    }; 
                   8932:     my $tries = 0;
                   8933:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8934:    
                   8935:     while (($gotlock ne 'ok') && $tries <3) {
                   8936:         $tries ++;
                   8937:         sleep 1;
                   8938:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8939:     }
                   8940:     if ($gotlock eq 'ok') {
                   8941:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8942:         my ($tmp)=keys(%curr_permissions);
                   8943:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8944:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8945:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8946:             if (ref($curr_controls) eq 'HASH') {
                   8947:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8948:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8949:                     if (defined($todelete{$itemnum})) {
                   8950:                         push(@deletions,$file_name."\0".$control_item);
                   8951:                     } else {
                   8952:                         if (defined($changed_items{$itemnum})) {
                   8953:                             $new_control{$changed_items{$itemnum}} = $now;
                   8954:                             push(@deletions,$file_name."\0".$control_item);
                   8955:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8956:                         } else {
                   8957:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8958:                         }
                   8959:                     }
1.745     raeburn  8960:                 }
                   8961:             }
                   8962:         }
1.970     raeburn  8963:         my ($group);
                   8964:         if (&is_course($domain,$user)) {
                   8965:             ($group,my $file) = split(/\//,$file_name,2);
                   8966:         }
1.749     raeburn  8967:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8968:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8969:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8970:         #  remove lock
                   8971:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8972:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8973:         my $sqlresult =
1.970     raeburn  8974:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8975:                                     $group);
1.749     raeburn  8976:     } else {
                   8977:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8978:     }
1.749     raeburn  8979:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8980: }
                   8981: 
1.827     raeburn  8982: sub make_public_indefinitely {
                   8983:     my ($requrl) = @_;
                   8984:     my $now = time;
                   8985:     my $action = 'activate';
                   8986:     my $aclnum = 0;
                   8987:     if (&is_portfolio_url($requrl)) {
                   8988:         my (undef,$udom,$unum,$file_name,$group) =
                   8989:             &parse_portfolio_url($requrl);
                   8990:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8991:         my %access_controls = &get_access_controls($current_perms,
                   8992:                                                    $group,$file_name);
                   8993:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8994:             my ($num,$scope,$end,$start) = 
                   8995:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8996:             if ($scope eq 'public') {
                   8997:                 if ($start <= $now && $end == 0) {
                   8998:                     $action = 'none';
                   8999:                 } else {
                   9000:                     $action = 'update';
                   9001:                     $aclnum = $num;
                   9002:                 }
                   9003:                 last;
                   9004:             }
                   9005:         }
                   9006:         if ($action eq 'none') {
                   9007:              return 'ok';
                   9008:         } else {
                   9009:             my %changes;
                   9010:             my $newend = 0;
                   9011:             my $newstart = $now;
                   9012:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9013:             $changes{$action}{$newkey} = {
                   9014:                 type => 'public',
                   9015:                 time => {
                   9016:                     start => $newstart,
                   9017:                     end   => $newend,
                   9018:                 },
                   9019:             };
                   9020:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9021:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9022:             return $outcome;
                   9023:         }
                   9024:     } else {
                   9025:         return 'invalid';
                   9026:     }
                   9027: }
                   9028: 
1.745     raeburn  9029: #------------------------------------------------------Get Marked as Read Only
                   9030: 
                   9031: sub get_marked_as_readonly {
                   9032:     my ($domain,$user,$what,$group) = @_;
                   9033:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9034:     my @readonly_files;
1.629     banghart 9035:     my $cmp1=$what;
                   9036:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9037:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9038:         if (defined($group)) {
                   9039:             if ($file_name !~ m-^\Q$group\E/-) {
                   9040:                 next;
                   9041:             }
                   9042:         }
1.561     banghart 9043:         if (ref($value) eq "ARRAY"){
                   9044:             foreach my $stored_what (@{$value}) {
1.629     banghart 9045:                 my $cmp2=$stored_what;
1.759     albertel 9046:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9047:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9048:                 }
1.629     banghart 9049:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9050:                     push(@readonly_files, $file_name);
1.745     raeburn  9051:                     last;
1.563     banghart 9052:                 } elsif (!defined($what)) {
                   9053:                     push(@readonly_files, $file_name);
1.745     raeburn  9054:                     last;
1.561     banghart 9055:                 }
                   9056:             }
1.745     raeburn  9057:         }
1.561     banghart 9058:     }
                   9059:     return @readonly_files;
                   9060: }
1.577     banghart 9061: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9062: 
1.577     banghart 9063: sub get_marked_as_readonly_hash {
1.745     raeburn  9064:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9065:     my %readonly_files;
1.745     raeburn  9066:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9067:         if (defined($group)) {
                   9068:             if ($file_name !~ m-^\Q$group\E/-) {
                   9069:                 next;
                   9070:             }
                   9071:         }
1.577     banghart 9072:         if (ref($value) eq "ARRAY"){
                   9073:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9074:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9075:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9076:                         if ($lock_descriptor eq 'graded') {
                   9077:                             $readonly_files{$file_name} = 'graded';
                   9078:                         } elsif ($lock_descriptor eq 'handback') {
                   9079:                             $readonly_files{$file_name} = 'handback';
                   9080:                         } else {
                   9081:                             if (!exists($readonly_files{$file_name})) {
                   9082:                                 $readonly_files{$file_name} = 'locked';
                   9083:                             }
                   9084:                         }
1.745     raeburn  9085:                     }
1.750     banghart 9086:                 } 
1.577     banghart 9087:             }
                   9088:         } 
                   9089:     }
                   9090:     return %readonly_files;
                   9091: }
1.559     banghart 9092: # ------------------------------------------------------------ Unmark as Read Only
                   9093: 
                   9094: sub unmark_as_readonly {
1.629     banghart 9095:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9096:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9097:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9098:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9099:     my $symb_crs = $what;
                   9100:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9101:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9102:     my ($tmp)=keys(%current_permissions);
                   9103:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9104:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9105:     foreach my $file (@readonly_files) {
1.759     albertel 9106: 	my $clean_file = &declutter_portfile($file);
                   9107: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9108: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9109:         my @new_locks;
                   9110:         my @del_keys;
                   9111:         if (ref($current_locks) eq "ARRAY"){
                   9112:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9113:                 my $compare=$locker;
1.749     raeburn  9114:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9115:                     $compare=join('',@{$locker});
1.746     raeburn  9116:                     if ($compare ne $symb_crs) {
                   9117:                         push(@new_locks, $locker);
                   9118:                     }
1.563     banghart 9119:                 }
                   9120:             }
1.650     albertel 9121:             if (scalar(@new_locks) > 0) {
1.563     banghart 9122:                 $current_permissions{$file} = \@new_locks;
                   9123:             } else {
                   9124:                 push(@del_keys, $file);
1.613     albertel 9125:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9126:                 delete($current_permissions{$file});
1.563     banghart 9127:             }
                   9128:         }
1.561     banghart 9129:     }
1.613     albertel 9130:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9131:     return;
                   9132: }
1.512     banghart 9133: 
1.17      www      9134: # ------------------------------------------------------------ Directory lister
                   9135: 
                   9136: sub dirlist {
1.955     raeburn  9137:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9138:     $uri=~s/^\///;
                   9139:     $uri=~s/\/$//;
1.253     stredwic 9140:     my ($udom, $uname);
1.955     raeburn  9141:     if ($getuserdir) {
1.253     stredwic 9142:         $udom = $userdomain;
                   9143:         $uname = $username;
1.955     raeburn  9144:     } else {
                   9145:         (undef,$udom,$uname)=split(/\//,$uri);
                   9146:         if(defined($userdomain)) {
                   9147:             $udom = $userdomain;
                   9148:         }
                   9149:         if(defined($username)) {
                   9150:             $uname = $username;
                   9151:         }
1.253     stredwic 9152:     }
1.955     raeburn  9153:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9154: 
1.955     raeburn  9155:     $dirRoot = $perlvar{'lonDocRoot'};
                   9156:     if (defined($getpropath)) {
                   9157:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9158:         $dirRoot =~ s/\/$//;
1.955     raeburn  9159:     } elsif (defined($getuserdir)) {
                   9160:         my $subdir=$uname.'__';
                   9161:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9162:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9163:                    ."/$udom/$subdir/$uname";
                   9164:     } elsif (defined($alternateRoot)) {
                   9165:         $dirRoot = $alternateRoot;
1.751     banghart 9166:     }
1.253     stredwic 9167: 
                   9168:     if($udom) {
                   9169:         if($uname) {
1.1135    raeburn  9170:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9171:             if ($uhome eq 'no_host') {
                   9172:                 return ([],'no_host');
                   9173:             }
1.955     raeburn  9174:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9175:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9176:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9177:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9178:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9179:             } else {
                   9180:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9181:             }
1.605     matthew  9182:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9183:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9184:                 @listing_results = split(/:/,$listing);
                   9185:             } else {
                   9186:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9187:             }
1.1135    raeburn  9188:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9189:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9190:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9191:                 return ([],$listing);
                   9192:             } else {
                   9193:                 return (\@listing_results);
1.1135    raeburn  9194:             }
1.955     raeburn  9195:         } elsif(!$alternateRoot) {
1.1136    raeburn  9196:             my (%allusers,%listerror);
1.841     albertel 9197: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9198:  	    foreach my $tryserver (keys(%servers)) {
                   9199:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9200:                                   &escape($udom),$tryserver);
                   9201:                 if ($listing eq 'unknown_cmd') {
                   9202: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9203: 				      $udom, $tryserver);
                   9204:                 } else {
                   9205:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9206:                 }
1.841     albertel 9207: 		if ($listing eq 'unknown_cmd') {
                   9208: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9209: 				      $udom, $tryserver);
                   9210: 		    @listing_results = split(/:/,$listing);
                   9211: 		} else {
                   9212: 		    @listing_results =
                   9213: 			map { &unescape($_); } split(/:/,$listing);
                   9214: 		}
1.1136    raeburn  9215:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9216:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9217:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9218:                     $listerror{$tryserver} = $listing;
                   9219:                 } else {
1.841     albertel 9220: 		    foreach my $line (@listing_results) {
                   9221: 			my ($entry) = split(/&/,$line,2);
                   9222: 			$allusers{$entry} = 1;
                   9223: 		    }
                   9224: 		}
1.253     stredwic 9225:             }
1.1136    raeburn  9226:             my @alluserslist=();
1.800     albertel 9227:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9228:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9229:             }
1.1136    raeburn  9230:             return (\@alluserslist);
1.253     stredwic 9231:         } else {
1.1136    raeburn  9232:             return ([],'missing username');
1.253     stredwic 9233:         }
1.955     raeburn  9234:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9235:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9236:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9237:         return (\@all_domains);
1.955     raeburn  9238:     } else {
1.1136    raeburn  9239:         return ([],'missing domain');
1.275     stredwic 9240:     }
                   9241: }
                   9242: 
                   9243: # --------------------------------------------- GetFileTimestamp
                   9244: # This function utilizes dirlist and returns the date stamp for
                   9245: # when it was last modified.  It will also return an error of -1
                   9246: # if an error occurs
                   9247: 
                   9248: sub GetFileTimestamp {
1.955     raeburn  9249:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9250:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9251:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9252:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9253:                                     undef,$getuserdir);
                   9254:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9255:         return -1;
                   9256:     }
                   9257:     if (ref($fileref) eq 'ARRAY') {
                   9258:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9259:         # @stats contains first the filename, then the stat output
                   9260:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9261:     } else {
                   9262:         return -1;
1.253     stredwic 9263:     }
1.26      www      9264: }
                   9265: 
1.712     albertel 9266: sub stat_file {
                   9267:     my ($uri) = @_;
1.787     albertel 9268:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9269: 
1.955     raeburn  9270:     my ($udom,$uname,$file);
1.712     albertel 9271:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9272: 	($udom,$uname,$file) =
1.811     albertel 9273: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9274: 	$file = 'userfiles/'.$file;
                   9275:     }
                   9276:     if ($uri =~ m-^/res/-) {
                   9277: 	($udom,$uname) = 
1.807     albertel 9278: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9279: 	$file = $uri;
                   9280:     }
                   9281: 
                   9282:     if (!$udom || !$uname || !$file) {
                   9283: 	# unable to handle the uri
                   9284: 	return ();
                   9285:     }
1.956     raeburn  9286:     my $getpropath;
                   9287:     if ($file =~ /^userfiles\//) {
                   9288:         $getpropath = 1;
                   9289:     }
1.1136    raeburn  9290:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9291:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9292:         return ();
                   9293:     } else {
                   9294:         if (ref($listref) eq 'ARRAY') {
                   9295:             my @stats = split('&',$listref->[0]);
                   9296: 	    shift(@stats); #filename is first
                   9297: 	    return @stats;
                   9298:         }
1.712     albertel 9299:     }
                   9300:     return ();
                   9301: }
                   9302: 
1.26      www      9303: # -------------------------------------------------------- Value of a Condition
                   9304: 
1.713     albertel 9305: # gets the value of a specific preevaluated condition
                   9306: #    stored in the string  $env{user.state.<cid>}
                   9307: # or looks up a condition reference in the bighash and if if hasn't
                   9308: # already been evaluated recurses into docondval to get the value of
                   9309: # the condition, then memoizing it to 
                   9310: #   $env{user.state.<cid>.<condition>}
1.40      www      9311: sub directcondval {
                   9312:     my $number=shift;
1.620     albertel 9313:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9314: 	&Apache::lonuserstate::evalstate();
                   9315:     }
1.713     albertel 9316:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9317: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9318:     } elsif ($number =~ /^_/) {
                   9319: 	my $sub_condition;
                   9320: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9321: 		&GDBM_READER(),0640)) {
                   9322: 	    $sub_condition=$bighash{'conditions'.$number};
                   9323: 	    untie(%bighash);
                   9324: 	}
                   9325: 	my $value = &docondval($sub_condition);
1.949     raeburn  9326: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9327: 	return $value;
                   9328:     }
1.620     albertel 9329:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9330:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9331:     } else {
                   9332:        return 2;
                   9333:     }
                   9334: }
                   9335: 
1.713     albertel 9336: # get the collection of conditions for this resource
1.26      www      9337: sub condval {
                   9338:     my $condidx=shift;
1.54      www      9339:     my $allpathcond='';
1.713     albertel 9340:     foreach my $cond (split(/\|/,$condidx)) {
                   9341: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9342: 	    $allpathcond.=
                   9343: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9344: 	}
1.191     harris41 9345:     }
1.54      www      9346:     $allpathcond=~s/\|$//;
1.713     albertel 9347:     return &docondval($allpathcond);
                   9348: }
                   9349: 
                   9350: #evaluates an expression of conditions
                   9351: sub docondval {
                   9352:     my ($allpathcond) = @_;
                   9353:     my $result=0;
                   9354:     if ($env{'request.course.id'}
                   9355: 	&& defined($allpathcond)) {
                   9356: 	my $operand='|';
                   9357: 	my @stack;
                   9358: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9359: 	    if ($chunk eq '(') {
                   9360: 		push @stack,($operand,$result);
                   9361: 	    } elsif ($chunk eq ')') {
                   9362: 		my $before=pop @stack;
                   9363: 		if (pop @stack eq '&') {
                   9364: 		    $result=$result>$before?$before:$result;
                   9365: 		} else {
                   9366: 		    $result=$result>$before?$result:$before;
                   9367: 		}
                   9368: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9369: 		$operand=$chunk;
                   9370: 	    } else {
                   9371: 		my $new=directcondval($chunk);
                   9372: 		if ($operand eq '&') {
                   9373: 		    $result=$result>$new?$new:$result;
                   9374: 		} else {
                   9375: 		    $result=$result>$new?$result:$new;
                   9376: 		}
                   9377: 	    }
                   9378: 	}
1.26      www      9379:     }
                   9380:     return $result;
1.421     albertel 9381: }
                   9382: 
                   9383: # ---------------------------------------------------- Devalidate courseresdata
                   9384: 
                   9385: sub devalidatecourseresdata {
                   9386:     my ($coursenum,$coursedomain)=@_;
                   9387:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9388:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9389: }
                   9390: 
1.763     www      9391: 
1.200     www      9392: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9393: #
                   9394: #  Parameters:
                   9395: #      $coursenum    - Number of the course.
                   9396: #      $coursedomain - Domain at which the course was created.
                   9397: #  Returns:
                   9398: #     A hash of the course parameters along (I think) with timestamps
                   9399: #     and version info.
1.877     foxr     9400: 
1.624     albertel 9401: sub get_courseresdata {
                   9402:     my ($coursenum,$coursedomain)=@_;
1.200     www      9403:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9404:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9405:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9406:     my %dumpreply;
1.417     albertel 9407:     unless (defined($cached)) {
1.624     albertel 9408: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9409: 	$result=\%dumpreply;
1.251     albertel 9410: 	my ($tmp) = keys(%dumpreply);
                   9411: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9412: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9413: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9414: 	    return $tmp;
1.416     albertel 9415: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9416: 	    $result=undef;
1.599     albertel 9417: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9418: 	}
                   9419:     }
1.624     albertel 9420:     return $result;
                   9421: }
                   9422: 
1.633     albertel 9423: sub devalidateuserresdata {
                   9424:     my ($uname,$udom)=@_;
                   9425:     my $hashid="$udom:$uname";
                   9426:     &devalidate_cache_new('userres',$hashid);
                   9427: }
                   9428: 
1.624     albertel 9429: sub get_userresdata {
                   9430:     my ($uname,$udom)=@_;
                   9431:     #most student don\'t have any data set, check if there is some data
                   9432:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9433: 
                   9434:     my $hashid="$udom:$uname";
                   9435:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9436:     if (!defined($cached)) {
                   9437: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9438: 	$result=\%resourcedata;
                   9439: 	&do_cache_new('userres',$hashid,$result,600);
                   9440:     }
                   9441:     my ($tmp)=keys(%$result);
                   9442:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9443: 	return $result;
                   9444:     }
                   9445:     #error 2 occurs when the .db doesn't exist
                   9446:     if ($tmp!~/error: 2 /) {
1.672     albertel 9447: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9448: 		 " Trying to get resource data for ".
                   9449: 		 $uname." at ".$udom.": ".
                   9450: 		 $tmp."</font>");
                   9451:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9452: 	#&EXT_cache_set($udom,$uname);
                   9453: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9454: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9455:     }
                   9456:     return $tmp;
                   9457: }
1.879     foxr     9458: #----------------------------------------------- resdata - return resource data
                   9459: #  Purpose:
                   9460: #    Return resource data for either users or for a course.
                   9461: #  Parameters:
                   9462: #     $name      - Course/user name.
                   9463: #     $domain    - Name of the domain the user/course is registered on.
                   9464: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9465: #     @which     - Array of names of resources desired.
                   9466: #  Returns:
                   9467: #     The value of the first reasource in @which that is found in the
                   9468: #     resource hash.
                   9469: #  Exceptional Conditions:
                   9470: #     If the $type passed in is not valid (not the string 'course' or 
                   9471: #     'user', an undefined  reference is returned.
                   9472: #     If none of the resources are found, an undef is returned
1.624     albertel 9473: sub resdata {
                   9474:     my ($name,$domain,$type,@which)=@_;
                   9475:     my $result;
                   9476:     if ($type eq 'course') {
                   9477: 	$result=&get_courseresdata($name,$domain);
                   9478:     } elsif ($type eq 'user') {
                   9479: 	$result=&get_userresdata($name,$domain);
                   9480:     }
                   9481:     if (!ref($result)) { return $result; }    
1.251     albertel 9482:     foreach my $item (@which) {
1.927     albertel 9483: 	if (defined($result->{$item->[0]})) {
                   9484: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9485: 	}
1.250     albertel 9486:     }
1.291     albertel 9487:     return undef;
1.200     www      9488: }
                   9489: 
1.379     matthew  9490: #
                   9491: # EXT resource caching routines
                   9492: #
                   9493: 
                   9494: sub clear_EXT_cache_status {
1.383     albertel 9495:     &delenv('cache.EXT.');
1.379     matthew  9496: }
                   9497: 
                   9498: sub EXT_cache_status {
                   9499:     my ($target_domain,$target_user) = @_;
1.383     albertel 9500:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9501:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9502:         # We know already the user has no data
                   9503:         return 1;
                   9504:     } else {
                   9505:         return 0;
                   9506:     }
                   9507: }
                   9508: 
                   9509: sub EXT_cache_set {
                   9510:     my ($target_domain,$target_user) = @_;
1.383     albertel 9511:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9512:     #&appenv({$cachename => time});
1.379     matthew  9513: }
                   9514: 
1.28      www      9515: # --------------------------------------------------------- Value of a Variable
1.58      www      9516: sub EXT {
1.715     albertel 9517: 
1.395     albertel 9518:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9519:     unless ($varname) { return ''; }
1.218     albertel 9520:     #get real user name/domain, courseid and symb
                   9521:     my $courseid;
1.359     albertel 9522:     my $publicuser;
1.427     www      9523:     if ($symbparm) {
                   9524: 	$symbparm=&get_symb_from_alias($symbparm);
                   9525:     }
1.218     albertel 9526:     if (!($uname && $udom)) {
1.790     albertel 9527:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9528:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9529:     } else {
1.620     albertel 9530: 	$courseid=$env{'request.course.id'};
1.218     albertel 9531:     }
1.48      www      9532:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9533:     my $rest;
1.320     albertel 9534:     if (defined($therest[0])) {
1.48      www      9535:        $rest=join('.',@therest);
                   9536:     } else {
                   9537:        $rest='';
                   9538:     }
1.320     albertel 9539: 
1.57      www      9540:     my $qualifierrest=$qualifier;
                   9541:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9542:     my $spacequalifierrest=$space;
                   9543:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9544:     if ($realm eq 'user') {
1.48      www      9545: # --------------------------------------------------------------- user.resource
                   9546: 	if ($space eq 'resource') {
1.651     albertel 9547: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9548: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9549: 		 &&
1.744     albertel 9550: 		 ($symbparm eq &symbread()) ) {	
                   9551: 		# if we are in the middle of processing the resource the
                   9552: 		# get the value we are planning on committing
                   9553:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9554:                     return $Apache::lonhomework::results{$qualifierrest};
                   9555:                 } else {
                   9556:                     return $Apache::lonhomework::history{$qualifierrest};
                   9557:                 }
1.335     albertel 9558: 	    } else {
1.359     albertel 9559: 		my %restored;
1.620     albertel 9560: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9561: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9562: 		} else {
                   9563: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9564: 		}
1.335     albertel 9565: 		return $restored{$qualifierrest};
                   9566: 	    }
1.48      www      9567: # ----------------------------------------------------------------- user.access
                   9568:         } elsif ($space eq 'access') {
1.218     albertel 9569: 	    # FIXME - not supporting calls for a specific user
1.48      www      9570:             return &allowed($qualifier,$rest);
                   9571: # ------------------------------------------ user.preferences, user.environment
                   9572:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9573: 	    if (($uname eq $env{'user.name'}) &&
                   9574: 		($udom eq $env{'user.domain'})) {
                   9575: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9576: 	    } else {
1.359     albertel 9577: 		my %returnhash;
                   9578: 		if (!$publicuser) {
                   9579: 		    %returnhash=&userenvironment($udom,$uname,
                   9580: 						 $qualifierrest);
                   9581: 		}
1.218     albertel 9582: 		return $returnhash{$qualifierrest};
                   9583: 	    }
1.48      www      9584: # ----------------------------------------------------------------- user.course
                   9585:         } elsif ($space eq 'course') {
1.218     albertel 9586: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9587:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9588: # ------------------------------------------------------------------- user.role
                   9589:         } elsif ($space eq 'role') {
1.218     albertel 9590: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9591:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9592:             if ($qualifier eq 'value') {
                   9593: 		return $role;
                   9594:             } elsif ($qualifier eq 'extent') {
                   9595:                 return $where;
                   9596:             }
                   9597: # ----------------------------------------------------------------- user.domain
                   9598:         } elsif ($space eq 'domain') {
1.218     albertel 9599:             return $udom;
1.48      www      9600: # ------------------------------------------------------------------- user.name
                   9601:         } elsif ($space eq 'name') {
1.218     albertel 9602:             return $uname;
1.48      www      9603: # ---------------------------------------------------- Any other user namespace
1.29      www      9604:         } else {
1.359     albertel 9605: 	    my %reply;
                   9606: 	    if (!$publicuser) {
                   9607: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9608: 	    }
                   9609: 	    return $reply{$qualifierrest};
1.48      www      9610:         }
1.236     www      9611:     } elsif ($realm eq 'query') {
                   9612: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9613:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9614: 						[$spacequalifierrest]);
1.620     albertel 9615: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9616:    } elsif ($realm eq 'request') {
1.48      www      9617: # ------------------------------------------------------------- request.browser
                   9618:         if ($space eq 'browser') {
1.1145    bisitz   9619:             return $env{'browser.'.$qualifier};
1.57      www      9620: # ------------------------------------------------------------ request.filename
                   9621:         } else {
1.620     albertel 9622:             return $env{'request.'.$spacequalifierrest};
1.29      www      9623:         }
1.28      www      9624:     } elsif ($realm eq 'course') {
1.48      www      9625: # ---------------------------------------------------------- course.description
1.620     albertel 9626:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9627:     } elsif ($realm eq 'resource') {
1.165     www      9628: 
1.620     albertel 9629: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9630: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9631: 	}
1.693     albertel 9632: 
                   9633: 	if ($space eq 'title') {
                   9634: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9635: 	    return &gettitle($symbparm);
                   9636: 	}
                   9637: 	
                   9638: 	if ($space eq 'map') {
                   9639: 	    my ($map) = &decode_symb($symbparm);
                   9640: 	    return &symbread($map);
                   9641: 	}
1.905     albertel 9642: 	if ($space eq 'filename') {
                   9643: 	    if ($symbparm) {
                   9644: 		return &clutter((&decode_symb($symbparm))[2]);
                   9645: 	    }
                   9646: 	    return &hreflocation('',$env{'request.filename'});
                   9647: 	}
1.693     albertel 9648: 
                   9649: 	my ($section, $group, @groups);
1.593     albertel 9650: 	my ($courselevelm,$courselevel);
1.539     albertel 9651: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9652: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9653: 
1.218     albertel 9654: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9655: 
1.60      www      9656: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9657: 	    my $symbp=$symbparm;
1.735     albertel 9658: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9659: 
                   9660: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9661: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9662: 
1.620     albertel 9663: 	    if (($env{'user.name'} eq $uname) &&
                   9664: 		($env{'user.domain'} eq $udom)) {
                   9665: 		$section=$env{'request.course.sec'};
1.733     raeburn  9666:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9667:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9668: 	    } else {
1.539     albertel 9669: 		if (! defined($usection)) {
1.551     albertel 9670: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9671: 		} else {
                   9672: 		    $section = $usection;
                   9673: 		}
1.733     raeburn  9674:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9675: 	    }
                   9676: 
                   9677: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9678: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9679: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9680: 
1.593     albertel 9681: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9682: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9683: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9684: 
1.60      www      9685: # ----------------------------------------------------------- first, check user
1.624     albertel 9686: 
                   9687: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9688: 				       ([$courselevelr,'resource'],
                   9689: 					[$courselevelm,'map'     ],
                   9690: 					[$courselevel, 'course'  ]));
1.931     albertel 9691: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9692: 
1.594     albertel 9693: # ------------------------------------------------ second, check some of course
1.684     raeburn  9694:             my $coursereply;
1.691     raeburn  9695:             if (@groups > 0) {
                   9696:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9697:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9698:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9699:             }
1.96      www      9700: 
1.684     raeburn  9701: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9702: 				  $env{'course.'.$courseid.'.domain'},
                   9703: 				  'course',
                   9704: 				  ([$seclevelr,   'resource'],
                   9705: 				   [$seclevelm,   'map'     ],
                   9706: 				   [$seclevel,    'course'  ],
                   9707: 				   [$courselevelr,'resource']));
                   9708: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9709: 
1.60      www      9710: # ------------------------------------------------------ third, check map parms
1.218     albertel 9711: 	    my %parmhash=();
                   9712: 	    my $thisparm='';
                   9713: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9714: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9715: 		    &GDBM_READER(),0640)) {
1.218     albertel 9716: 		$thisparm=$parmhash{$symbparm};
                   9717: 		untie(%parmhash);
                   9718: 	    }
1.927     albertel 9719: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9720: 	}
1.594     albertel 9721: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9722: 
1.218     albertel 9723: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9724: 	my $filename;
                   9725: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9726: 	if ($symbparm) {
1.409     www      9727: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9728: 	} else {
1.620     albertel 9729: 	    $filename=$env{'request.filename'};
1.282     albertel 9730: 	}
                   9731: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9732: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9733: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9734: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9735: 
1.927     albertel 9736: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9737: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9738: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9739: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9740: 				     $env{'course.'.$courseid.'.domain'},
                   9741: 				     'course',
1.927     albertel 9742: 				     ([$courselevelm,'map'   ],
                   9743: 				      [$courselevel, 'course']));
                   9744: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9745: 	}
1.145     www      9746: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9747: 	unless ($space eq '0') {
1.336     albertel 9748: 	    my @parts=split(/_/,$space);
                   9749: 	    my $id=pop(@parts);
                   9750: 	    my $part=join('_',@parts);
                   9751: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9752: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9753: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9754: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9755: 	}
1.395     albertel 9756: 	if ($recurse) { return undef; }
                   9757: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9758: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9759: # ---------------------------------------------------- Any other user namespace
                   9760:     } elsif ($realm eq 'environment') {
                   9761: # ----------------------------------------------------------------- environment
1.620     albertel 9762: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9763: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9764: 	} else {
1.770     albertel 9765: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9766: 		return '';
                   9767: 	    }
1.219     albertel 9768: 	    my %returnhash=&userenvironment($udom,$uname,
                   9769: 					    $spacequalifierrest);
                   9770: 	    return $returnhash{$spacequalifierrest};
                   9771: 	}
1.28      www      9772:     } elsif ($realm eq 'system') {
1.48      www      9773: # ----------------------------------------------------------------- system.time
                   9774: 	if ($space eq 'time') {
                   9775: 	    return time;
                   9776:         }
1.696     albertel 9777:     } elsif ($realm eq 'server') {
                   9778: # ----------------------------------------------------------------- system.time
                   9779: 	if ($space eq 'name') {
                   9780: 	    return $ENV{'SERVER_NAME'};
                   9781:         }
1.28      www      9782:     }
1.48      www      9783:     return '';
1.61      www      9784: }
                   9785: 
1.927     albertel 9786: sub get_reply {
                   9787:     my ($reply_value) = @_;
1.940     raeburn  9788:     if (ref($reply_value) eq 'ARRAY') {
                   9789:         if (wantarray) {
                   9790: 	    return @$reply_value;
                   9791:         }
                   9792:         return $reply_value->[0];
                   9793:     } else {
                   9794:         return $reply_value;
1.927     albertel 9795:     }
                   9796: }
                   9797: 
1.691     raeburn  9798: sub check_group_parms {
                   9799:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9800:     my @groupitems = ();
                   9801:     my $resultitem;
1.927     albertel 9802:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9803:     foreach my $group (@{$groups}) {
                   9804:         foreach my $level (@levels) {
1.927     albertel 9805:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9806:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9807:         }
                   9808:     }
                   9809:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9810:                             $env{'course.'.$courseid.'.domain'},
                   9811:                                      'course',@groupitems);
                   9812:     return $coursereply;
                   9813: }
                   9814: 
                   9815: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9816:     my ($courseid,@groups) = @_;
                   9817:     @groups = sort(@groups);
1.691     raeburn  9818:     return @groups;
                   9819: }
                   9820: 
1.395     albertel 9821: sub packages_tab_default {
                   9822:     my ($uri,$varname)=@_;
                   9823:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9824: 
                   9825:     my (@extension,@specifics,$do_default);
                   9826:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9827: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9828: 	if ($pack_type eq 'default') {
                   9829: 	    $do_default=1;
                   9830: 	} elsif ($pack_type eq 'extension') {
                   9831: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9832: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9833: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9834: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9835: 	}
                   9836:     }
                   9837:     # first look for a package that matches the requested part id
                   9838:     foreach my $package (@specifics) {
                   9839: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9840: 	next if ($pack_part ne $part);
                   9841: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9842: 	    return $packagetab{"$pack_type&$name&default"};
                   9843: 	}
                   9844:     }
                   9845:     # look for any possible matching non extension_ package
                   9846:     foreach my $package (@specifics) {
                   9847: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9848: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9849: 	    return $packagetab{"$pack_type&$name&default"};
                   9850: 	}
1.585     albertel 9851: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9852: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9853: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9854: 	}
                   9855:     }
1.738     albertel 9856:     # look for any posible extension_ match
                   9857:     foreach my $package (@extension) {
                   9858: 	my ($package,$pack_type)=@{$package};
                   9859: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9860: 	    return $packagetab{"$pack_type&$name&default"};
                   9861: 	}
                   9862: 	if (defined($packagetab{$package."&$name&default"})) {
                   9863: 	    return $packagetab{$package."&$name&default"};
                   9864: 	}
                   9865:     }
                   9866:     # look for a global default setting
                   9867:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9868: 	return $packagetab{"default&$name&default"};
                   9869:     }
1.395     albertel 9870:     return undef;
                   9871: }
                   9872: 
1.334     albertel 9873: sub add_prefix_and_part {
                   9874:     my ($prefix,$part)=@_;
                   9875:     my $keyroot;
                   9876:     if (defined($prefix) && $prefix !~ /^__/) {
                   9877: 	# prefix that has a part already
                   9878: 	$keyroot=$prefix;
                   9879:     } elsif (defined($prefix)) {
                   9880: 	# prefix that is missing a part
                   9881: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9882:     } else {
                   9883: 	# no prefix at all
                   9884: 	if (defined($part)) { $keyroot='_'.$part; }
                   9885:     }
                   9886:     return $keyroot;
                   9887: }
                   9888: 
1.71      www      9889: # ---------------------------------------------------------------- Get metadata
                   9890: 
1.599     albertel 9891: my %metaentry;
1.1070    www      9892: my %importedpartids;
1.71      www      9893: sub metadata {
1.176     www      9894:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9895:     $uri=&declutter($uri);
1.288     albertel 9896:     # if it is a non metadata possible uri return quickly
1.529     albertel 9897:     if (($uri eq '') || 
                   9898: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20! raeburn  9899: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9900:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9901: 	return undef;
                   9902:     }
1.1140    www      9903:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9904: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9905: 	return undef;
1.288     albertel 9906:     }
1.73      www      9907:     my $filename=$uri;
                   9908:     $uri=~s/\.meta$//;
1.172     www      9909: #
                   9910: # Is the metadata already cached?
1.177     www      9911: # Look at timestamp of caching
1.172     www      9912: # Everything is cached by the main uri, libraries are never directly cached
                   9913: #
1.428     albertel 9914:     if (!defined($liburi)) {
1.599     albertel 9915: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9916: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9917:     }
                   9918:     {
1.1069    www      9919: # Imported parts would go here
1.1070    www      9920:         my %importedids=();
                   9921:         my @origfileimportpartids=();
1.1069    www      9922:         my $importedparts=0;
1.172     www      9923: #
                   9924: # Is this a recursive call for a library?
                   9925: #
1.599     albertel 9926: #	if (! exists($metacache{$uri})) {
                   9927: #	    $metacache{$uri}={};
                   9928: #	}
1.924     albertel 9929: 	my $cachetime = 60*60;
1.171     www      9930:         if ($liburi) {
                   9931: 	    $liburi=&declutter($liburi);
                   9932:             $filename=$liburi;
1.401     bowersj2 9933:         } else {
1.599     albertel 9934: 	    &devalidate_cache_new('meta',$uri);
                   9935: 	    undef(%metaentry);
1.401     bowersj2 9936: 	}
1.140     www      9937:         my %metathesekeys=();
1.73      www      9938:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9939: 	my $metastring;
1.1140    www      9940: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9941: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9942: 	    $metastring = 
1.929     albertel 9943: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9944: 					  ('grade_target' => 'meta'));
                   9945: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9946: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9947:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9948: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9949: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9950: 	    $metastring=&getfile($file);
1.489     albertel 9951: 	}
1.208     albertel 9952:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9953:         my $token;
1.140     www      9954:         undef %metathesekeys;
1.71      www      9955:         while ($token=$parser->get_token) {
1.339     albertel 9956: 	    if ($token->[0] eq 'S') {
                   9957: 		if (defined($token->[2]->{'package'})) {
1.172     www      9958: #
                   9959: # This is a package - get package info
                   9960: #
1.339     albertel 9961: 		    my $package=$token->[2]->{'package'};
                   9962: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9963: 		    if (defined($token->[2]->{'id'})) { 
                   9964: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9965: 		    }
1.599     albertel 9966: 		    if ($metaentry{':packages'}) {
                   9967: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9968: 		    } else {
1.599     albertel 9969: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9970: 		    }
1.736     albertel 9971: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9972: 			my $part=$keyroot;
                   9973: 			$part=~s/^\_//;
1.736     albertel 9974: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9975: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9976: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9977: 			    # ignore package.tab specified default values
                   9978:                             # here &package_tab_default() will fetch those
                   9979: 			    if ($subp eq 'default') { next; }
1.736     albertel 9980: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9981: 			    my $unikey;
                   9982: 			    if ($pack =~ /_0$/) {
                   9983: 				$unikey='parameter_0_'.$name;
                   9984: 				$part=0;
                   9985: 			    } else {
                   9986: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9987: 			    }
1.339     albertel 9988: 			    if ($subp eq 'display') {
                   9989: 				$value.=' [Part: '.$part.']';
                   9990: 			    }
1.599     albertel 9991: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9992: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9993: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9994: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9995: 			    }
1.599     albertel 9996: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9997: 				$metaentry{':'.$unikey}=
                   9998: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9999: 			    }
1.339     albertel 10000: 			}
                   10001: 		    }
                   10002: 		} else {
1.172     www      10003: #
                   10004: # This is not a package - some other kind of start tag
1.339     albertel 10005: #
                   10006: 		    my $entry=$token->[1];
1.1068    www      10007: 		    my $unikey='';
1.175     www      10008: 
1.339     albertel 10009: 		    if ($entry eq 'import') {
1.175     www      10010: #
                   10011: # Importing a library here
1.339     albertel 10012: #
1.1067    www      10013:                         my $location=$parser->get_text('/import');
                   10014:                         my $dir=$filename;
                   10015:                         $dir=~s|[^/]*$||;
                   10016:                         $location=&filelocation($dir,$location);
1.1069    www      10017:                        
1.1068    www      10018:                         my $importmode=$token->[2]->{'importmode'};
                   10019:                         if ($importmode eq 'problem') {
1.1069    www      10020: # Import as problem/response
1.1068    www      10021:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10022:                         } elsif ($importmode eq 'part') {
                   10023: # Import as part(s)
1.1069    www      10024:                            $importedparts=1;
                   10025: # We need to get the original file and the imported file to get the part order correct
                   10026: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10027: # Load and inspect original file
1.1070    www      10028:                            if ($#origfileimportpartids<0) {
                   10029:                               undef(%importedpartids);
                   10030:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10031:                               my $origfile=&getfile($origfilelocation);
                   10032:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10033:                            }
                   10034: 
1.1069    www      10035: # Load and inspect imported file
                   10036:                            my $impfile=&getfile($location);
                   10037:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10038:                            if ($#impfilepartids>=0) {
                   10039: # This problem had parts
1.1070    www      10040:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10041:                            } else {
                   10042: # Importing by turning a single problem into a problem part
                   10043: # It gets the import-tags ID as part-ID
                   10044:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10045:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10046:                            }
1.1068    www      10047:                         } else {
                   10048: # Normal import
                   10049:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10050:                            if (defined($token->[2]->{'id'})) {
                   10051:                               $unikey.='_'.$token->[2]->{'id'};
                   10052:                            }
1.1067    www      10053:                         }
                   10054: 
1.339     albertel 10055: 			if ($depthcount<20) {
1.736     albertel 10056: 			    my $metadata = 
                   10057: 				&metadata($uri,'keys', $location,$unikey,
                   10058: 					  $depthcount+1);
                   10059: 			    foreach my $meta (split(',',$metadata)) {
                   10060: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10061: 				$metathesekeys{$meta}=1;
1.339     albertel 10062: 			    }
1.1068    www      10063: 			
                   10064:                         }
1.1067    www      10065: 		    } else {
                   10066: #
                   10067: # Not importing, some other kind of non-package, non-library start tag
                   10068: # 
                   10069:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10070:                         if (defined($token->[2]->{'id'})) {
                   10071:                             $unikey.='_'.$token->[2]->{'id'};
                   10072:                         }
1.339     albertel 10073: 			if (defined($token->[2]->{'name'})) { 
                   10074: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10075: 			}
                   10076: 			$metathesekeys{$unikey}=1;
1.736     albertel 10077: 			foreach my $param (@{$token->[3]}) {
                   10078: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10079: 				$token->[2]->{$param};
1.339     albertel 10080: 			}
                   10081: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10082: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10083: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10084: 		 # only ws inside the tag, and not in default, so use default
                   10085: 		 # as value
1.599     albertel 10086: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10087: 			} elsif ( $internaltext =~ /\S/ ) {
                   10088: 		  # something interesting inside the tag
                   10089: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10090: 			} else {
1.908     albertel 10091: 		  # no interesting values, don't set a default
1.339     albertel 10092: 			}
1.172     www      10093: # end of not-a-package not-a-library import
1.339     albertel 10094: 		    }
1.172     www      10095: # end of not-a-package start tag
1.339     albertel 10096: 		}
1.172     www      10097: # the next is the end of "start tag"
1.339     albertel 10098: 	    }
                   10099: 	}
1.483     albertel 10100: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10101: 	$extension = lc($extension);
                   10102: 	if ($extension eq 'htm') { $extension='html'; }
                   10103: 
1.737     albertel 10104: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10105: 	    #no specific packages #how's our extension
                   10106: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10107: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10108: 					 \%metathesekeys);
                   10109: 	}
1.883     albertel 10110: 
                   10111: 	if (!exists($metaentry{':packages'})
                   10112: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10113: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10114: 		#no specific packages well let's get default then
                   10115: 		if ($key!~/^default&/) { next; }
1.488     albertel 10116: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10117: 					     \%metathesekeys);
                   10118: 	    }
                   10119: 	}
1.338     www      10120: # are there custom rights to evaluate
1.599     albertel 10121: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10122: 
1.338     www      10123:     #
                   10124:     # Importing a rights file here
1.339     albertel 10125:     #
                   10126: 	    unless ($depthcount) {
1.599     albertel 10127: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10128: 		my $dir=$filename;
                   10129: 		$dir=~s|[^/]*$||;
                   10130: 		$location=&filelocation($dir,$location);
1.736     albertel 10131: 		my $rights_metadata =
                   10132: 		    &metadata($uri,'keys',$location,'_rights',
                   10133: 			      $depthcount+1);
                   10134: 		foreach my $rights (split(',',$rights_metadata)) {
                   10135: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10136: 		    $metathesekeys{$rights}=1;
1.339     albertel 10137: 		}
                   10138: 	    }
                   10139: 	}
1.737     albertel 10140: 	# uniqifiy package listing
                   10141: 	my %seen;
                   10142: 	my @uniq_packages =
                   10143: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10144: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10145: 
1.1070    www      10146:         if ($importedparts) {
                   10147: # We had imported parts and need to rebuild partorder
                   10148:            $metaentry{':partorder'}='';
                   10149:            $metathesekeys{'partorder'}=1;
                   10150:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10151:                if ($origfileimportpartids[$index] eq 'part') {
                   10152: # original part, part of the problem
                   10153:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10154:                } else {
                   10155: # we have imported parts at this position
                   10156:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10157:                }
                   10158:            }
                   10159:            $metaentry{':partorder'}=~s/^\,//;
                   10160:         }
                   10161: 
1.737     albertel 10162: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10163: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10164: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10165: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10166: # this is the end of "was not already recently cached
1.71      www      10167:     }
1.599     albertel 10168:     return $metaentry{':'.$what};
1.261     albertel 10169: }
                   10170: 
1.488     albertel 10171: sub metadata_create_package_def {
1.483     albertel 10172:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10173:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10174:     if ($subp eq 'default') { next; }
                   10175:     
1.599     albertel 10176:     if (defined($metaentry{':packages'})) {
                   10177: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10178:     } else {
1.599     albertel 10179: 	$metaentry{':packages'}=$package;
1.483     albertel 10180:     }
                   10181:     my $value=$packagetab{$key};
                   10182:     my $unikey;
                   10183:     $unikey='parameter_0_'.$name;
1.599     albertel 10184:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10185:     $$metathesekeys{$unikey}=1;
1.599     albertel 10186:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10187: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10188:     }
1.599     albertel 10189:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10190: 	$metaentry{':'.$unikey}=
                   10191: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10192:     }
                   10193: }
                   10194: 
1.261     albertel 10195: sub metadata_generate_part0 {
                   10196:     my ($metadata,$metacache,$uri) = @_;
                   10197:     my %allnames;
1.737     albertel 10198:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10199: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10200: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10201: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10202: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10203: 	    $allnames{$name}=$part;
                   10204: 	  }
                   10205: 	}
                   10206:     }
                   10207:     foreach my $name (keys(%allnames)) {
                   10208:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10209:       my $key=":parameter_0_$name";
1.261     albertel 10210:       $$metacache{"$key.part"}='0';
                   10211:       $$metacache{"$key.name"}=$name;
1.428     albertel 10212:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10213: 					   $allnames{$name}.'_'.$name.
                   10214: 					   '.type'};
1.428     albertel 10215:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10216: 			     '.display'};
1.644     www      10217:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10218:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10219:       $$metacache{"$key.display"}=$olddis;
                   10220:     }
1.71      www      10221: }
                   10222: 
1.764     albertel 10223: # ------------------------------------------------------ Devalidate title cache
                   10224: 
                   10225: sub devalidate_title_cache {
                   10226:     my ($url)=@_;
                   10227:     if (!$env{'request.course.id'}) { return; }
                   10228:     my $symb=&symbread($url);
                   10229:     if (!$symb) { return; }
                   10230:     my $key=$env{'request.course.id'}."\0".$symb;
                   10231:     &devalidate_cache_new('title',$key);
                   10232: }
                   10233: 
1.1014    droeschl 10234: # ------------------------------------------------- Get the title of a course
                   10235: 
                   10236: sub current_course_title {
                   10237:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10238: }
1.301     www      10239: # ------------------------------------------------- Get the title of a resource
                   10240: 
                   10241: sub gettitle {
                   10242:     my $urlsymb=shift;
                   10243:     my $symb=&symbread($urlsymb);
1.534     albertel 10244:     if ($symb) {
1.620     albertel 10245: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10246: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10247: 	if (defined($cached)) { 
                   10248: 	    return $result;
                   10249: 	}
1.534     albertel 10250: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10251: 	my $title='';
1.907     albertel 10252: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10253: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10254: 	} else {
                   10255: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10256: 		    &GDBM_READER(),0640)) {
                   10257: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10258: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10259: 		untie(%bighash);
                   10260: 	    }
1.534     albertel 10261: 	}
                   10262: 	$title=~s/\&colon\;/\:/gs;
                   10263: 	if ($title) {
1.1159    www      10264: # Remember both $symb and $title for dynamic metadata
                   10265:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10266:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10267: # Cache this title and then return it
1.599     albertel 10268: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10269: 	}
                   10270: 	$urlsymb=$url;
                   10271:     }
                   10272:     my $title=&metadata($urlsymb,'title');
                   10273:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10274:     return $title;
1.301     www      10275: }
1.613     albertel 10276: 
1.1172.2.13  raeburn  10277: sub getdocspath {
                   10278:     my ($symb) = @_;
                   10279:     my $path;
                   10280:     if ($symb) {
                   10281:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10282:         if ($resurl=~/\.(sequence|page)$/) {
                   10283:             $mapurl=$resurl;
                   10284:         } elsif ($resurl eq 'adm/navmaps') {
                   10285:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10286:         }
                   10287:         my $mapresobj;
                   10288:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10289:         if (ref($navmap)) {
                   10290:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10291:         }
                   10292:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10293:         my $type=$2;
                   10294:         if (ref($mapresobj)) {
                   10295:             my $pcslist = $mapresobj->map_hierarchy();
                   10296:             if ($pcslist ne '') {
                   10297:                 foreach my $pc (split(/,/,$pcslist)) {
                   10298:                     next if ($pc <= 1);
                   10299:                     my $res = $navmap->getByMapPc($pc);
                   10300:                     if (ref($res)) {
                   10301:                         my $thisurl = $res->src();
                   10302:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10303:                         my $thistitle = $res->title();
                   10304:                         $path .= '&'.
                   10305:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10306:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10307:                                  ':'.$res->randompick().
                   10308:                                  ':'.$res->randomout().
                   10309:                                  ':'.$res->encrypted().
                   10310:                                  ':'.$res->randomorder().
                   10311:                                  ':'.$res->is_page();
                   10312:                     }
                   10313:                 }
                   10314:             }
                   10315:             $path =~ s/^\&//;
                   10316:             my $maptitle = $mapresobj->title();
                   10317:             if ($mapurl eq 'default') {
                   10318:                 $maptitle = 'Main Course Documents';
                   10319:             }
                   10320:             $path .= ($path ne '')? '&' : ''.
                   10321:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10322:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10323:                     ':'.$mapresobj->randompick().
                   10324:                     ':'.$mapresobj->randomout().
                   10325:                     ':'.$mapresobj->encrypted().
                   10326:                     ':'.$mapresobj->randomorder().
                   10327:                     ':'.$mapresobj->is_page();
                   10328:         } else {
                   10329:             my $maptitle = &gettitle($mapurl);
                   10330:             my $ispage;
                   10331:             if ($mapurl =~ /\.page$/) {
                   10332:                 $ispage = 1;
                   10333:             }
                   10334:             if ($mapurl eq 'default') {
                   10335:                 $maptitle = 'Main Course Documents';
                   10336:             }
                   10337:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10338:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10339:         }
                   10340:         unless ($mapurl eq 'default') {
                   10341:             $path = 'default&'.
                   10342:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10343:                     ':::::&'.$path;
                   10344:         }
                   10345:     }
                   10346:     return $path;
                   10347: }
                   10348: 
1.614     albertel 10349: sub get_slot {
                   10350:     my ($which,$cnum,$cdom)=@_;
                   10351:     if (!$cnum || !$cdom) {
1.790     albertel 10352: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10353: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10354: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10355:     }
1.703     albertel 10356:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10357:     my %slotinfo;
                   10358:     if (exists($remembered{$key})) {
                   10359: 	$slotinfo{$which} = $remembered{$key};
                   10360:     } else {
                   10361: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10362: 	&Apache::lonhomework::showhash(%slotinfo);
                   10363: 	my ($tmp)=keys(%slotinfo);
                   10364: 	if ($tmp=~/^error:/) { return (); }
                   10365: 	$remembered{$key} = $slotinfo{$which};
                   10366:     }
1.616     albertel 10367:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10368: 	return %{$slotinfo{$which}};
                   10369:     }
                   10370:     return $slotinfo{$which};
1.614     albertel 10371: }
1.1150    raeburn  10372: 
                   10373: sub get_reservable_slots {
                   10374:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10375:     my $now = time;
                   10376:     my $reservable_info;
                   10377:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10378:     if (exists($remembered{$key})) {
                   10379:         $reservable_info = $remembered{$key};
                   10380:     } else {
                   10381:         my %resv;
                   10382:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10383:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10384:         $reservable_info = \%resv;
                   10385:         $remembered{$key} = $reservable_info;
                   10386:     }
                   10387:     return $reservable_info;
                   10388: }
                   10389: 
                   10390: sub get_course_slots {
                   10391:     my ($cnum,$cdom) = @_;
                   10392:     my $hashid=$cnum.':'.$cdom;
                   10393:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10394:     if (defined($cached)) {
                   10395:         if (ref($result) eq 'HASH') {
                   10396:             return %{$result};
                   10397:         }
                   10398:     } else {
                   10399:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10400:         my ($tmp) = keys(%slots);
                   10401:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10402:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10403:             return %slots;
                   10404:         }
                   10405:     }
                   10406:     return;
                   10407: }
                   10408: 
                   10409: sub devalidate_slots_cache {
                   10410:     my ($cnum,$cdom)=@_;
                   10411:     my $hashid=$cnum.':'.$cdom;
                   10412:     &devalidate_cache_new('allslots',$hashid);
                   10413: }
                   10414: 
1.1172.2.8  raeburn  10415: sub get_coursechange {
                   10416:     my ($cdom,$cnum) = @_;
                   10417:     if ($cdom eq '' || $cnum eq '') {
                   10418:         return unless ($env{'request.course.id'});
                   10419:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10420:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10421:     }
                   10422:     my $hashid=$cdom.'_'.$cnum;
                   10423:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10424:     if ((defined($cached)) && ($change ne '')) {
                   10425:         return $change;
                   10426:     } else {
                   10427:         my %crshash;
                   10428:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10429:         if ($crshash{'internal.contentchange'} eq '') {
                   10430:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10431:             if ($change eq '') {
                   10432:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10433:                 $change = $crshash{'internal.created'};
                   10434:             }
                   10435:         } else {
                   10436:             $change = $crshash{'internal.contentchange'};
                   10437:         }
                   10438:         my $cachetime = 600;
                   10439:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10440:     }
                   10441:     return $change;
                   10442: }
                   10443: 
                   10444: sub devalidate_coursechange_cache {
                   10445:     my ($cnum,$cdom)=@_;
                   10446:     my $hashid=$cnum.':'.$cdom;
                   10447:     &devalidate_cache_new('crschange',$hashid);
                   10448: }
                   10449: 
1.31      www      10450: # ------------------------------------------------- Update symbolic store links
                   10451: 
                   10452: sub symblist {
                   10453:     my ($mapname,%newhash)=@_;
1.438     www      10454:     $mapname=&deversion(&declutter($mapname));
1.31      www      10455:     my %hash;
1.620     albertel 10456:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10457:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10458:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10459: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10460: 		next if ($url eq 'last_known'
                   10461: 			 && $env{'form.no_update_last_known'});
                   10462: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10463: 						    $newhash{$url}->[1],
                   10464: 						    $newhash{$url}->[0]);
1.191     harris41 10465:             }
1.31      www      10466:             if (untie(%hash)) {
                   10467: 		return 'ok';
                   10468:             }
                   10469:         }
                   10470:     }
                   10471:     return 'error';
1.212     www      10472: }
                   10473: 
                   10474: # --------------------------------------------------------------- Verify a symb
                   10475: 
                   10476: sub symbverify {
1.1172.2.11  raeburn  10477:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10478:     my $thisfn=$thisurl;
1.439     www      10479:     $thisfn=&declutter($thisfn);
1.215     www      10480: # direct jump to resource in page or to a sequence - will construct own symbs
                   10481:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10482: # check URL part
1.409     www      10483:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10484: 
1.431     www      10485:     unless ($url eq $thisfn) { return 0; }
1.213     www      10486: 
1.216     www      10487:     $symb=&symbclean($symb);
1.510     www      10488:     $thisurl=&deversion($thisurl);
1.439     www      10489:     $thisfn=&deversion($thisfn);
1.213     www      10490: 
                   10491:     my %bighash;
                   10492:     my $okay=0;
1.431     www      10493: 
1.620     albertel 10494:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10495:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10496:         my $noclutter;
1.1032    raeburn  10497:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10498:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10499:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10500:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10501:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10502:                 $noclutter = 1;
                   10503:             }
                   10504:         }
                   10505:         my $ids;
                   10506:         if ($noclutter) {
                   10507:             $ids=$bighash{'ids_'.$thisurl};
                   10508:         } else {
                   10509:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10510:         }
1.1102    raeburn  10511:         unless ($ids) {
1.1172.2.13  raeburn  10512:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10513:             $ids=$bighash{$idkey};
1.216     www      10514:         }
                   10515:         if ($ids) {
                   10516: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10517:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10518:                 $symb =~ s/\?.+$//;
                   10519:             }
1.800     albertel 10520: 	    foreach my $id (split(/\,/,$ids)) {
                   10521: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10522:                if (
                   10523:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10524:    eq $symb) {
1.1172.2.11  raeburn  10525:                    if (ref($encstate)) {
                   10526:                        $$encstate = $bighash{'encrypted_'.$id};
                   10527:                    }
1.1172.2.13  raeburn  10528:                    if (($env{'request.role.adv'}) ||
                   10529:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10530:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10531:                        $okay=1;
                   10532:                        last;
                   10533:                    }
                   10534:                }
                   10535:            }
1.216     www      10536:         }
1.213     www      10537: 	untie(%bighash);
                   10538:     }
                   10539:     return $okay;
1.31      www      10540: }
                   10541: 
1.210     www      10542: # --------------------------------------------------------------- Clean-up symb
                   10543: 
                   10544: sub symbclean {
                   10545:     my $symb=shift;
1.568     albertel 10546:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10547: # remove version from map
                   10548:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10549: 
1.210     www      10550: # remove version from URL
                   10551:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10552: 
1.507     www      10553: # remove wrapper
                   10554: 
1.510     www      10555:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10556:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10557:     return $symb;
1.409     www      10558: }
                   10559: 
                   10560: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10561: 
                   10562: sub encode_symb {
                   10563:     my ($map,$resid,$url)=@_;
                   10564:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10565: }
1.409     www      10566: 
                   10567: sub decode_symb {
1.568     albertel 10568:     my $symb=shift;
                   10569:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10570:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10571:     return (&fixversion($map),$resid,&fixversion($url));
                   10572: }
                   10573: 
                   10574: sub fixversion {
                   10575:     my $fn=shift;
1.609     banghart 10576:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10577:     my %bighash;
                   10578:     my $uri=&clutter($fn);
1.620     albertel 10579:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10580: # is this cached?
1.599     albertel 10581:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10582:     if (defined($cached)) { return $result; }
                   10583: # unfortunately not cached, or expired
1.620     albertel 10584:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10585: 	    &GDBM_READER(),0640)) {
                   10586:  	if ($bighash{'version_'.$uri}) {
                   10587:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10588:  	    unless (($version eq 'mostrecent') || 
                   10589: 		    ($version==&getversion($uri))) {
1.440     www      10590:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10591:  	    }
                   10592:  	}
                   10593:  	untie %bighash;
1.413     www      10594:     }
1.599     albertel 10595:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10596: }
                   10597: 
                   10598: sub deversion {
                   10599:     my $url=shift;
                   10600:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10601:     return $url;
1.210     www      10602: }
                   10603: 
1.31      www      10604: # ------------------------------------------------------ Return symb list entry
                   10605: 
                   10606: sub symbread {
1.249     www      10607:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10608:     my $cache_str;
                   10609:     if ($thisfn ne '') {
                   10610:         $cache_str='request.symbread.cached.'.$thisfn;
                   10611:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10612:             return $env{$cache_str};
                   10613:         }
1.1172.2.13  raeburn  10614:    } else {
1.242     www      10615: # no filename provided? try from environment
1.620     albertel 10616:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10617:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10618:         }
                   10619:         $thisfn=$env{'request.filename'};
1.44      www      10620:     }
1.569     albertel 10621:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10622: # is that filename actually a symb? Verify, clean, and return
                   10623:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10624: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10625: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10626: 	}
1.242     www      10627:     }
1.44      www      10628:     $thisfn=declutter($thisfn);
1.31      www      10629:     my %hash;
1.37      www      10630:     my %bighash;
                   10631:     my $syval='';
1.620     albertel 10632:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10633:         my $targetfn = $thisfn;
1.609     banghart 10634:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10635:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10636:         }
1.687     albertel 10637: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10638: 	    $targetfn=$1;
                   10639: 	}
1.620     albertel 10640:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10641:                       &GDBM_READER(),0640)) {
1.481     raeburn  10642: 	    $syval=$hash{$targetfn};
1.37      www      10643:             untie(%hash);
                   10644:         }
                   10645: # ---------------------------------------------------------- There was an entry
                   10646:         if ($syval) {
1.601     albertel 10647: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10648: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10649: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10650: 		    #return $env{$cache_str}='';
1.601     albertel 10651: 		#}    
                   10652: 		#$syval.=$1;
                   10653: 	    #}
1.37      www      10654:         } else {
                   10655: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10656:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10657:                             &GDBM_READER(),0640)) {
1.37      www      10658: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10659:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10660:               unless ($ids) { 
                   10661:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10662:               }
                   10663:               unless ($ids) {
                   10664: # alias?
                   10665: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10666:               }
1.37      www      10667:               if ($ids) {
                   10668: # ------------------------------------------------------------------- Has ID(s)
                   10669:                  my @possibilities=split(/\,/,$ids);
1.39      www      10670:                  if ($#possibilities==0) {
                   10671: # ----------------------------------------------- There is only one possibility
1.37      www      10672: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10673: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10674: 						    $resid,$thisfn);
1.249     www      10675:                  } elsif (!$donotrecurse) {
1.39      www      10676: # ------------------------------------------ There is more than one possibility
                   10677:                      my $realpossible=0;
1.800     albertel 10678:                      foreach my $id (@possibilities) {
                   10679: 			 my $file=$bighash{'src_'.$id};
1.39      www      10680:                          if (&allowed('bre',$file)) {
1.800     albertel 10681:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10682:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10683: 				$realpossible++;
1.626     albertel 10684:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10685: 						    $resid,$thisfn);
1.39      www      10686:                             }
                   10687: 			 }
1.191     harris41 10688:                      }
1.39      www      10689: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10690:                  } else {
                   10691:                      $syval='';
1.37      www      10692:                  }
                   10693: 	      }
                   10694:               untie(%bighash)
1.481     raeburn  10695:            }
1.31      www      10696:         }
1.62      www      10697:         if ($syval) {
1.620     albertel 10698: 	    return $env{$cache_str}=$syval;
1.62      www      10699:         }
1.31      www      10700:     }
1.949     raeburn  10701:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10702:     return $env{$cache_str}='';
1.31      www      10703: }
                   10704: 
                   10705: # ---------------------------------------------------------- Return random seed
                   10706: 
1.32      www      10707: sub numval {
                   10708:     my $txt=shift;
                   10709:     $txt=~tr/A-J/0-9/;
                   10710:     $txt=~tr/a-j/0-9/;
                   10711:     $txt=~tr/K-T/0-9/;
                   10712:     $txt=~tr/k-t/0-9/;
                   10713:     $txt=~tr/U-Z/0-5/;
                   10714:     $txt=~tr/u-z/0-5/;
                   10715:     $txt=~s/\D//g;
1.564     albertel 10716:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10717:     return int($txt);
1.368     albertel 10718: }
                   10719: 
1.484     albertel 10720: sub numval2 {
                   10721:     my $txt=shift;
                   10722:     $txt=~tr/A-J/0-9/;
                   10723:     $txt=~tr/a-j/0-9/;
                   10724:     $txt=~tr/K-T/0-9/;
                   10725:     $txt=~tr/k-t/0-9/;
                   10726:     $txt=~tr/U-Z/0-5/;
                   10727:     $txt=~tr/u-z/0-5/;
                   10728:     $txt=~s/\D//g;
                   10729:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10730:     my $total;
                   10731:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10732:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10733:     return int($total);
                   10734: }
                   10735: 
1.575     albertel 10736: sub numval3 {
                   10737:     use integer;
                   10738:     my $txt=shift;
                   10739:     $txt=~tr/A-J/0-9/;
                   10740:     $txt=~tr/a-j/0-9/;
                   10741:     $txt=~tr/K-T/0-9/;
                   10742:     $txt=~tr/k-t/0-9/;
                   10743:     $txt=~tr/U-Z/0-5/;
                   10744:     $txt=~tr/u-z/0-5/;
                   10745:     $txt=~s/\D//g;
                   10746:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10747:     my $total;
                   10748:     foreach my $val (@txts) { $total+=$val; }
                   10749:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10750:     return $total;
                   10751: }
                   10752: 
1.675     albertel 10753: sub digest {
                   10754:     my ($data)=@_;
                   10755:     my $digest=&Digest::MD5::md5($data);
                   10756:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10757:     my ($e,$f);
                   10758:     {
                   10759:         use integer;
                   10760:         $e=($a+$b);
                   10761:         $f=($c+$d);
                   10762:         if ($_64bit) {
                   10763:             $e=(($e<<32)>>32);
                   10764:             $f=(($f<<32)>>32);
                   10765:         }
                   10766:     }
                   10767:     if (wantarray) {
                   10768: 	return ($e,$f);
                   10769:     } else {
                   10770: 	my $g;
                   10771: 	{
                   10772: 	    use integer;
                   10773: 	    $g=($e+$f);
                   10774: 	    if ($_64bit) {
                   10775: 		$g=(($g<<32)>>32);
                   10776: 	    }
                   10777: 	}
                   10778: 	return $g;
                   10779:     }
                   10780: }
                   10781: 
1.368     albertel 10782: sub latest_rnd_algorithm_id {
1.675     albertel 10783:     return '64bit5';
1.366     albertel 10784: }
1.32      www      10785: 
1.503     albertel 10786: sub get_rand_alg {
                   10787:     my ($courseid)=@_;
1.790     albertel 10788:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10789:     if ($courseid) {
1.620     albertel 10790: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10791:     }
                   10792:     return &latest_rnd_algorithm_id();
                   10793: }
                   10794: 
1.562     albertel 10795: sub validCODE {
                   10796:     my ($CODE)=@_;
                   10797:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10798:     return 0;
                   10799: }
                   10800: 
1.491     albertel 10801: sub getCODE {
1.620     albertel 10802:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10803:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10804: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10805: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10806: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10807:     }
                   10808:     return undef;
                   10809: }
1.1133    foxr     10810: #
                   10811: #  Determines the random seed for a specific context:
                   10812: #
                   10813: # parameters:
                   10814: #   symb      - in course context the symb for the seed.
                   10815: #   course_id - The course id of the form domain_coursenum.
                   10816: #   domain    - Domain for the user.
                   10817: #   course    - Course for the user.
                   10818: #   cenv      - environment of the course.
                   10819: #
                   10820: # NOTE:
                   10821: #   All parameters are picked out of the environment if missing
                   10822: #   or not defined.
                   10823: #   If a symb cannot be determined the current time is used instead.
                   10824: #
                   10825: #  For a given well defined symb, courside, domain, username,
                   10826: #  and course environment, the seed is reproducible.
                   10827: #
1.31      www      10828: sub rndseed {
1.1133    foxr     10829:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10830:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10831:     if (!defined($symb)) {
1.366     albertel 10832: 	unless ($symb=$wsymb) { return time; }
                   10833:     }
1.1146    foxr     10834:     if (!defined $courseid) { 
                   10835: 	$courseid=$wcourseid; 
                   10836:     }
                   10837:     if (!defined $domain) { $domain=$wdomain; }
                   10838:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10839: 
                   10840:     my $which;
                   10841:     if (defined($cenv->{'rndseed'})) {
                   10842: 	$which = $cenv->{'rndseed'};
                   10843:     } else {
                   10844: 	$which =&get_rand_alg($courseid);
                   10845:     }
1.491     albertel 10846:     if (defined(&getCODE())) {
1.675     albertel 10847: 	if ($which eq '64bit5') {
                   10848: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10849: 	} elsif ($which eq '64bit4') {
1.575     albertel 10850: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10851: 	} else {
                   10852: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10853: 	}
1.675     albertel 10854:     } elsif ($which eq '64bit5') {
                   10855: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10856:     } elsif ($which eq '64bit4') {
                   10857: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10858:     } elsif ($which eq '64bit3') {
                   10859: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10860:     } elsif ($which eq '64bit2') {
                   10861: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10862:     } elsif ($which eq '64bit') {
                   10863: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10864:     }
                   10865:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10866: }
                   10867: 
                   10868: sub rndseed_32bit {
                   10869:     my ($symb,$courseid,$domain,$username)=@_;
                   10870:     {
                   10871: 	use integer;
                   10872: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10873: 	my $symbseed=numval($symb) << 22;
                   10874: 	my $namechck=unpack("%32C*",$username) << 17;
                   10875: 	my $nameseed=numval($username) << 12;
                   10876: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10877: 	my $courseseed=unpack("%32C*",$courseid);
                   10878: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10879: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10880: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10881: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10882: 	return $num;
                   10883:     }
                   10884: }
                   10885: 
                   10886: sub rndseed_64bit {
                   10887:     my ($symb,$courseid,$domain,$username)=@_;
                   10888:     {
                   10889: 	use integer;
                   10890: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10891: 	my $symbseed=numval($symb) << 10;
                   10892: 	my $namechck=unpack("%32S*",$username);
                   10893: 	
                   10894: 	my $nameseed=numval($username) << 21;
                   10895: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10896: 	my $courseseed=unpack("%32S*",$courseid);
                   10897: 	
                   10898: 	my $num1=$symbchck+$symbseed+$namechck;
                   10899: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10900: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10901: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10902: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10903: 	return "$num1,$num2";
1.155     albertel 10904:     }
1.366     albertel 10905: }
                   10906: 
1.443     albertel 10907: sub rndseed_64bit2 {
                   10908:     my ($symb,$courseid,$domain,$username)=@_;
                   10909:     {
                   10910: 	use integer;
                   10911: 	# strings need to be an even # of cahracters long, it it is odd the
                   10912:         # last characters gets thrown away
                   10913: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10914: 	my $symbseed=numval($symb) << 10;
                   10915: 	my $namechck=unpack("%32S*",$username.' ');
                   10916: 	
                   10917: 	my $nameseed=numval($username) << 21;
1.501     albertel 10918: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10919: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10920: 	
                   10921: 	my $num1=$symbchck+$symbseed+$namechck;
                   10922: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10923: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10924: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10925: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10926: 	return "$num1,$num2";
                   10927:     }
                   10928: }
                   10929: 
                   10930: sub rndseed_64bit3 {
                   10931:     my ($symb,$courseid,$domain,$username)=@_;
                   10932:     {
                   10933: 	use integer;
                   10934: 	# strings need to be an even # of cahracters long, it it is odd the
                   10935:         # last characters gets thrown away
                   10936: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10937: 	my $symbseed=numval2($symb) << 10;
                   10938: 	my $namechck=unpack("%32S*",$username.' ');
                   10939: 	
                   10940: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10941: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10942: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10943: 	
                   10944: 	my $num1=$symbchck+$symbseed+$namechck;
                   10945: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10946: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10947: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10948: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10949: 	
1.503     albertel 10950: 	return "$num1:$num2";
1.443     albertel 10951:     }
                   10952: }
                   10953: 
1.575     albertel 10954: sub rndseed_64bit4 {
                   10955:     my ($symb,$courseid,$domain,$username)=@_;
                   10956:     {
                   10957: 	use integer;
                   10958: 	# strings need to be an even # of cahracters long, it it is odd the
                   10959:         # last characters gets thrown away
                   10960: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10961: 	my $symbseed=numval3($symb) << 10;
                   10962: 	my $namechck=unpack("%32S*",$username.' ');
                   10963: 	
                   10964: 	my $nameseed=numval3($username) << 21;
                   10965: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10966: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10967: 	
                   10968: 	my $num1=$symbchck+$symbseed+$namechck;
                   10969: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10970: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10971: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10972: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10973: 	
1.575     albertel 10974: 	return "$num1:$num2";
                   10975:     }
                   10976: }
                   10977: 
1.675     albertel 10978: sub rndseed_64bit5 {
                   10979:     my ($symb,$courseid,$domain,$username)=@_;
                   10980:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10981:     return "$num1:$num2";
                   10982: }
                   10983: 
1.366     albertel 10984: sub rndseed_CODE_64bit {
                   10985:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10986:     {
1.366     albertel 10987: 	use integer;
1.443     albertel 10988: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10989: 	my $symbseed=numval2($symb);
1.491     albertel 10990: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10991: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10992: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10993: 	my $num1=$symbseed+$CODEchck;
                   10994: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10995: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10996: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10997: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10998: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10999: 	return "$num1:$num2";
1.366     albertel 11000:     }
                   11001: }
                   11002: 
1.575     albertel 11003: sub rndseed_CODE_64bit4 {
                   11004:     my ($symb,$courseid,$domain,$username)=@_;
                   11005:     {
                   11006: 	use integer;
                   11007: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11008: 	my $symbseed=numval3($symb);
                   11009: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11010: 	my $CODEseed=numval3(&getCODE());
                   11011: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11012: 	my $num1=$symbseed+$CODEchck;
                   11013: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11014: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11015: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11016: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11017: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11018: 	return "$num1:$num2";
                   11019:     }
                   11020: }
                   11021: 
1.675     albertel 11022: sub rndseed_CODE_64bit5 {
                   11023:     my ($symb,$courseid,$domain,$username)=@_;
                   11024:     my $code = &getCODE();
                   11025:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11026:     return "$num1:$num2";
                   11027: }
                   11028: 
1.366     albertel 11029: sub setup_random_from_rndseed {
                   11030:     my ($rndseed)=@_;
1.503     albertel 11031:     if ($rndseed =~/([,:])/) {
                   11032: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11033: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11034:     } else {
                   11035: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11036:     }
1.36      albertel 11037: }
                   11038: 
1.474     albertel 11039: sub latest_receipt_algorithm_id {
1.835     albertel 11040:     return 'receipt3';
1.474     albertel 11041: }
                   11042: 
1.480     www      11043: sub recunique {
                   11044:     my $fucourseid=shift;
                   11045:     my $unique;
1.835     albertel 11046:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11047: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11048: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11049:     } else {
                   11050: 	$unique=$perlvar{'lonReceipt'};
                   11051:     }
                   11052:     return unpack("%32C*",$unique);
                   11053: }
                   11054: 
                   11055: sub recprefix {
                   11056:     my $fucourseid=shift;
                   11057:     my $prefix;
1.835     albertel 11058:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11059: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11060: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11061:     } else {
                   11062: 	$prefix=$perlvar{'lonHostID'};
                   11063:     }
                   11064:     return unpack("%32C*",$prefix);
                   11065: }
                   11066: 
1.76      www      11067: sub ireceipt {
1.474     albertel 11068:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11069: 
                   11070:     my $return =&recprefix($fucourseid).'-';
                   11071: 
                   11072:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11073: 	$env{'request.state'} eq 'construct') {
                   11074: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11075: 	return $return;
                   11076:     }
                   11077: 
1.76      www      11078:     my $cuname=unpack("%32C*",$funame);
                   11079:     my $cudom=unpack("%32C*",$fudom);
                   11080:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11081:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11082:     my $cunique=&recunique($fucourseid);
1.474     albertel 11083:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11084:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11085: 
1.790     albertel 11086: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11087: 			       
                   11088: 	$return.= ($cunique%$cuname+
                   11089: 		   $cunique%$cudom+
                   11090: 		   $cusymb%$cuname+
                   11091: 		   $cusymb%$cudom+
                   11092: 		   $cucourseid%$cuname+
                   11093: 		   $cucourseid%$cudom+
                   11094: 		   $cpart%$cuname+
                   11095: 		   $cpart%$cudom);
                   11096:     } else {
                   11097: 	$return.= ($cunique%$cuname+
                   11098: 		   $cunique%$cudom+
                   11099: 		   $cusymb%$cuname+
                   11100: 		   $cusymb%$cudom+
                   11101: 		   $cucourseid%$cuname+
                   11102: 		   $cucourseid%$cudom);
                   11103:     }
                   11104:     return $return;
1.76      www      11105: }
                   11106: 
                   11107: sub receipt {
1.474     albertel 11108:     my ($part)=@_;
1.790     albertel 11109:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11110:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11111: }
1.260     ng       11112: 
1.790     albertel 11113: sub whichuser {
                   11114:     my ($passedsymb)=@_;
                   11115:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11116:     if (defined($env{'form.grade_symb'})) {
                   11117: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11118: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11119: 	if (!$allowed &&
                   11120: 	    exists($env{'request.course.sec'}) &&
                   11121: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11122: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11123: 			      '/'.$env{'request.course.sec'});
                   11124: 	}
                   11125: 	if ($allowed) {
                   11126: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11127: 	    $courseid=$tmp_courseid;
                   11128: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11129: 	    ($name)=&get_env_multiple('form.grade_username');
                   11130: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11131: 	}
                   11132:     }
                   11133:     if (!$passedsymb) {
                   11134: 	$symb=&symbread();
                   11135:     } else {
                   11136: 	$symb=$passedsymb;
                   11137:     }
                   11138:     $courseid=$env{'request.course.id'};
                   11139:     $domain=$env{'user.domain'};
                   11140:     $name=$env{'user.name'};
                   11141:     if ($name eq 'public' && $domain eq 'public') {
                   11142: 	if (!defined($env{'form.username'})) {
                   11143: 	    $env{'form.username'}.=time.rand(10000000);
                   11144: 	}
                   11145: 	$name.=$env{'form.username'};
                   11146:     }
                   11147:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11148: 
                   11149: }
                   11150: 
1.36      albertel 11151: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11152: # returns either the contents of the file or 
                   11153: # -1 if the file doesn't exist
1.481     raeburn  11154: #
                   11155: # if the target is a file that was uploaded via DOCS, 
                   11156: # a check will be made to see if a current copy exists on the local server,
                   11157: # if it does this will be served, otherwise a copy will be retrieved from
                   11158: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11159: # the local server.   
1.472     albertel 11160: 
1.36      albertel 11161: sub getfile {
1.538     albertel 11162:     my ($file) = @_;
1.609     banghart 11163:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11164:     &repcopy($file);
                   11165:     return &readfile($file);
                   11166: }
                   11167: 
                   11168: sub repcopy_userfile {
                   11169:     my ($file)=@_;
1.1142    raeburn  11170:     my $londocroot = $perlvar{'lonDocRoot'};
                   11171:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11172:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11173:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11174: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11175:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11176:     if (-e "$file") {
1.828     www      11177: # we already have a local copy, check it out
1.538     albertel 11178: 	my @fileinfo = stat($file);
1.828     www      11179: 	my $rtncode;
                   11180: 	my $info;
1.538     albertel 11181: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11182: 	if ($lwpresp ne 'ok') {
1.828     www      11183: # there is no such file anymore, even though we had a local copy
1.482     albertel 11184: 	    if ($rtncode eq '404') {
1.538     albertel 11185: 		unlink($file);
1.482     albertel 11186: 	    }
                   11187: 	    return -1;
                   11188: 	}
                   11189: 	if ($info < $fileinfo[9]) {
1.828     www      11190: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11191: 	    return 'ok';
1.828     www      11192: 	} else {
                   11193: # the file is outdated, get rid of it
                   11194: 	    unlink($file);
1.482     albertel 11195: 	}
1.828     www      11196:     }
                   11197: # one way or the other, at this point, we don't have the file
                   11198: # construct the correct path for the file
                   11199:     my @parts = ($cdom,$cnum); 
                   11200:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11201: 	push @parts, split(/\//,$1);
                   11202:     }
                   11203:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11204:     foreach my $part (@parts) {
                   11205: 	$path .= '/'.$part;
                   11206: 	if (!-e $path) {
                   11207: 	    mkdir($path,0770);
1.482     albertel 11208: 	}
                   11209:     }
1.828     www      11210: # now the path exists for sure
                   11211: # get a user agent
                   11212:     my $ua=new LWP::UserAgent;
                   11213:     my $transferfile=$file.'.in.transfer';
                   11214: # FIXME: this should flock
                   11215:     if (-e $transferfile) { return 'ok'; }
                   11216:     my $request;
                   11217:     $uri=~s/^\///;
1.980     raeburn  11218:     my $homeserver = &homeserver($cnum,$cdom);
                   11219:     my $protocol = $protocol{$homeserver};
                   11220:     $protocol = 'http' if ($protocol ne 'https');
                   11221:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11222:     my $response=$ua->request($request,$transferfile);
                   11223: # did it work?
                   11224:     if ($response->is_error()) {
                   11225: 	unlink($transferfile);
                   11226: 	&logthis("Userfile repcopy failed for $uri");
                   11227: 	return -1;
                   11228:     }
                   11229: # worked, rename the transfer file
                   11230:     rename($transferfile,$file);
1.607     raeburn  11231:     return 'ok';
1.481     raeburn  11232: }
                   11233: 
1.517     albertel 11234: sub tokenwrapper {
                   11235:     my $uri=shift;
1.980     raeburn  11236:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11237:     $uri=~s|^/||;
1.620     albertel 11238:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11239:     my $token=$1;
1.552     albertel 11240:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11241:     if ($udom && $uname && $file) {
                   11242: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11243:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11244:         my $homeserver = &homeserver($uname,$udom);
                   11245:         my $protocol = $protocol{$homeserver};
                   11246:         $protocol = 'http' if ($protocol ne 'https');
                   11247:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11248:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11249:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11250:     } else {
                   11251:         return '/adm/notfound.html';
                   11252:     }
                   11253: }
                   11254: 
1.828     www      11255: # call with reqtype HEAD: get last modification time
                   11256: # call with reqtype GET: get the file contents
                   11257: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11258: #
1.481     raeburn  11259: sub getuploaded {
                   11260:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11261:     $uri=~s/^\///;
1.980     raeburn  11262:     my $homeserver = &homeserver($cnum,$cdom);
                   11263:     my $protocol = $protocol{$homeserver};
                   11264:     $protocol = 'http' if ($protocol ne 'https');
                   11265:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11266:     my $ua=new LWP::UserAgent;
                   11267:     my $request=new HTTP::Request($reqtype,$uri);
                   11268:     my $response=$ua->request($request);
                   11269:     $$rtncode = $response->code;
1.482     albertel 11270:     if (! $response->is_success()) {
                   11271: 	return 'failed';
                   11272:     }      
                   11273:     if ($reqtype eq 'HEAD') {
1.486     www      11274: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11275:     } elsif ($reqtype eq 'GET') {
                   11276: 	$$info = $response->content;
1.472     albertel 11277:     }
1.482     albertel 11278:     return 'ok';
1.36      albertel 11279: }
                   11280: 
1.481     raeburn  11281: sub readfile {
                   11282:     my $file = shift;
                   11283:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11284:     my $fh;
                   11285:     open($fh,"<$file");
                   11286:     my $a='';
1.800     albertel 11287:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11288:     return $a;
                   11289: }
                   11290: 
1.36      albertel 11291: sub filelocation {
1.590     banghart 11292:     my ($dir,$file) = @_;
                   11293:     my $location;
                   11294:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11295: 
                   11296:     if ($file =~ m-^/adm/-) {
                   11297: 	$file=~s-^/adm/wrapper/-/-;
                   11298: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11299:     }
1.882     albertel 11300: 
1.1139    www      11301:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11302:         $location = $file;
1.609     banghart 11303:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11304:         my ($udom,$uname,$filename)=
1.811     albertel 11305:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11306:         my $home=&homeserver($uname,$udom);
                   11307:         my $is_me=0;
                   11308:         my @ids=&current_machine_ids();
                   11309:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11310:         if ($is_me) {
1.1117    foxr     11311:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11312:         } else {
                   11313:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11314:   	      $udom.'/'.$uname.'/'.$filename;
                   11315:         }
1.882     albertel 11316:     } elsif ($file =~ m-^/adm/-) {
                   11317: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11318:     } else {
                   11319:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11320:         $file=~s:^/(res|priv)/:/:;
                   11321:         my $space=$1;
1.590     banghart 11322:         if ( !( $file =~ m:^/:) ) {
                   11323:             $location = $dir. '/'.$file;
                   11324:         } else {
1.1142    raeburn  11325:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11326:         }
1.59      albertel 11327:     }
1.590     banghart 11328:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11329:     while ($location=~m{/\.\./}) {
                   11330: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11331: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11332: 	} else {
                   11333: 	    $location=~ s{/\.\./}{/}g;
                   11334: 	}
                   11335:     } #remove dir/..
1.590     banghart 11336:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11337:     return $location;
1.46      www      11338: }
1.36      albertel 11339: 
1.46      www      11340: sub hreflocation {
                   11341:     my ($dir,$file)=@_;
1.980     raeburn  11342:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11343: 	$file=filelocation($dir,$file);
1.700     albertel 11344:     } elsif ($file=~m-^/adm/-) {
                   11345: 	$file=~s-^/adm/wrapper/-/-;
                   11346: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11347:     }
                   11348:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11349: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11350:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11351: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11352: 	        {/uploaded/$1/$2/}x;
1.46      www      11353:     }
1.913     albertel 11354:     if ($file=~ m{^/userfiles/}) {
                   11355: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11356:     }
1.462     albertel 11357:     return $file;
1.465     albertel 11358: }
                   11359: 
1.1139    www      11360: 
                   11361: 
                   11362: 
                   11363: 
1.465     albertel 11364: sub current_machine_domains {
1.853     albertel 11365:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11366: }
                   11367: 
                   11368: sub machine_domains {
                   11369:     my ($hostname) = @_;
1.465     albertel 11370:     my @domains;
1.838     albertel 11371:     my %hostname = &all_hostnames();
1.465     albertel 11372:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11373: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11374: 	if ($hostname eq $name) {
1.844     albertel 11375: 	    push(@domains,&host_domain($id));
1.465     albertel 11376: 	}
                   11377:     }
                   11378:     return @domains;
                   11379: }
                   11380: 
                   11381: sub current_machine_ids {
1.853     albertel 11382:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11383: }
                   11384: 
                   11385: sub machine_ids {
                   11386:     my ($hostname) = @_;
                   11387:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11388:     my @ids;
1.888     albertel 11389:     my %name_to_host = &all_names();
1.889     albertel 11390:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11391: 	return @{ $name_to_host{$hostname} };
                   11392:     }
                   11393:     return;
1.31      www      11394: }
                   11395: 
1.824     raeburn  11396: sub additional_machine_domains {
                   11397:     my @domains;
                   11398:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11399:     while( my $line = <$fh>) {
                   11400:         $line =~ s/\s//g;
                   11401:         push(@domains,$line);
                   11402:     }
                   11403:     return @domains;
                   11404: }
                   11405: 
                   11406: sub default_login_domain {
                   11407:     my $domain = $perlvar{'lonDefDomain'};
                   11408:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11409:     foreach my $posdom (&current_machine_domains(),
                   11410:                         &additional_machine_domains()) {
                   11411:         if (lc($posdom) eq lc($testdomain)) {
                   11412:             $domain=$posdom;
                   11413:             last;
                   11414:         }
                   11415:     }
                   11416:     return $domain;
                   11417: }
                   11418: 
1.31      www      11419: # ------------------------------------------------------------- Declutters URLs
                   11420: 
                   11421: sub declutter {
                   11422:     my $thisfn=shift;
1.569     albertel 11423:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11424:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11425:     $thisfn=~s/^\///;
1.697     albertel 11426:     $thisfn=~s|^adm/wrapper/||;
                   11427:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11428:     $thisfn=~s/^res\///;
1.1172    bisitz   11429:     $thisfn=~s/^priv\///;
1.1032    raeburn  11430:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11431:         $thisfn=~s/\?.+$//;
                   11432:     }
1.268     www      11433:     return $thisfn;
                   11434: }
                   11435: 
                   11436: # ------------------------------------------------------------- Clutter up URLs
                   11437: 
                   11438: sub clutter {
                   11439:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11440:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11441: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11442:        $thisfn='/res'.$thisfn; 
                   11443:     }
1.1031    raeburn  11444:     if ($thisfn !~m|^/adm|) {
                   11445: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11446: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11447: 	} else {
                   11448: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11449: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11450: 	    if ($embstyle eq 'ssi'
                   11451: 		|| ($embstyle eq 'hdn')
                   11452: 		|| ($embstyle eq 'rat')
                   11453: 		|| ($embstyle eq 'prv')
                   11454: 		|| ($embstyle eq 'ign')) {
                   11455: 		#do nothing with these
                   11456: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11457: 		|| ($embstyle eq 'emb')
                   11458: 		|| ($embstyle eq 'wrp')) {
                   11459: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11460: 	    } elsif ($embstyle eq 'unk'
                   11461: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11462: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11463: 	    } else {
1.718     www      11464: #		&logthis("Got a blank emb style");
1.695     albertel 11465: 	    }
1.694     albertel 11466: 	}
                   11467:     }
1.31      www      11468:     return $thisfn;
1.12      www      11469: }
                   11470: 
1.787     albertel 11471: sub clutter_with_no_wrapper {
                   11472:     my $uri = &clutter(shift);
                   11473:     if ($uri =~ m-^/adm/-) {
                   11474: 	$uri =~ s-^/adm/wrapper/-/-;
                   11475: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11476:     }
                   11477:     return $uri;
                   11478: }
                   11479: 
1.557     albertel 11480: sub freeze_escape {
                   11481:     my ($value)=@_;
                   11482:     if (ref($value)) {
                   11483: 	$value=&nfreeze($value);
                   11484: 	return '__FROZEN__'.&escape($value);
                   11485:     }
                   11486:     return &escape($value);
                   11487: }
                   11488: 
1.11      www      11489: 
1.557     albertel 11490: sub thaw_unescape {
                   11491:     my ($value)=@_;
                   11492:     if ($value =~ /^__FROZEN__/) {
                   11493: 	substr($value,0,10,undef);
                   11494: 	$value=&unescape($value);
                   11495: 	return &thaw($value);
                   11496:     }
                   11497:     return &unescape($value);
                   11498: }
                   11499: 
1.436     albertel 11500: sub correct_line_ends {
                   11501:     my ($result)=@_;
                   11502:     $$result =~s/\r\n/\n/mg;
                   11503:     $$result =~s/\r/\n/mg;
1.415     albertel 11504: }
1.1       albertel 11505: # ================================================================ Main Program
                   11506: 
1.184     www      11507: sub goodbye {
1.204     albertel 11508:    &logthis("Starting Shut down");
1.443     albertel 11509: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11510:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11511: #converted
1.599     albertel 11512: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11513:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11514: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11515: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11516: #1.1 only
1.870     albertel 11517: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11518: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11519: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11520: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11521:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11522:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11523:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11524:    &flushcourselogs();
                   11525:    &logthis("Shutting down");
                   11526: }
                   11527: 
1.852     albertel 11528: sub get_dns {
1.1172.2.17  raeburn  11529:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11530:     if (!$ignore_cache) {
                   11531: 	my ($content,$cached)=
                   11532: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11533: 	if ($cached) {
1.1172.2.17  raeburn  11534: 	    &$func($content,$hashref);
1.869     albertel 11535: 	    return;
                   11536: 	}
                   11537:     }
                   11538: 
                   11539:     my %alldns;
1.852     albertel 11540:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11541:     foreach my $dns (<$config>) {
                   11542: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11543:         my $line = $1;
                   11544:         my ($host,$protocol) = split(/:/,$line);
                   11545:         if ($protocol ne 'https') {
                   11546:             $protocol = 'http';
                   11547:         }
                   11548: 	$alldns{$host} = $protocol;
1.869     albertel 11549:     }
                   11550:     while (%alldns) {
                   11551: 	my ($dns) = keys(%alldns);
1.852     albertel 11552: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11553:         $ua->timeout(30);
1.979     raeburn  11554: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11555: 	my $response=$ua->request($request);
1.979     raeburn  11556:         delete($alldns{$dns});
1.852     albertel 11557: 	next if ($response->is_error());
                   11558: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11559:         unless ($nocache) {
                   11560: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
                   11561:         }
                   11562: 	&$func(\@content,$hashref);
1.869     albertel 11563: 	return;
1.852     albertel 11564:     }
                   11565:     close($config);
1.871     albertel 11566:     my $which = (split('/',$url))[3];
                   11567:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11568:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11569:     my @content = <$config>;
1.1172.2.17  raeburn  11570:     &$func(\@content,$hashref);
                   11571:     return;
                   11572: }
                   11573: 
                   11574: # ------------------------------------------------------Get DNS checksums file
                   11575: sub parse_dns_checksums_tab {
                   11576:     my ($lines,$hashref) = @_;
                   11577:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11578:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11579:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11580:     my (%chksum,%revnum);
                   11581:     if (ref($lines) eq 'ARRAY') {
                   11582:         chomp(@{$lines});
                   11583:         my $versions = shift(@{$lines});
                   11584:         my %supported;
                   11585:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11586:             my $releaseslist = $1;
                   11587:             if ($releaseslist =~ /,/) {
                   11588:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11589:             } elsif ($releaseslist) {
                   11590:                 $supported{$releaseslist} = 1;
                   11591:             }
                   11592:         }
                   11593:         if ($supported{$release}) {
                   11594:             my $matchthis = 0;
                   11595:             foreach my $line (@{$lines}) {
                   11596:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11597:                     if ($matchthis) {
                   11598:                         last;
                   11599:                     } elsif ($1 eq $release) {
                   11600:                         $matchthis = 1;
                   11601:                     }
                   11602:                 } elsif ($matchthis) {
                   11603:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11604:                     $chksum{$file} = $shasum;
                   11605:                     $revnum{$file} = $version;
                   11606:                 }
                   11607:             }
                   11608:             if (ref($hashref) eq 'HASH') {
                   11609:                 %{$hashref} = (
                   11610:                                 sums     => \%chksum,
                   11611:                                 versions => \%revnum,
                   11612:                               );
                   11613:             }
                   11614:         }
                   11615:     }
1.869     albertel 11616:     return;
1.852     albertel 11617: }
1.1172.2.17  raeburn  11618: 
                   11619: sub fetch_dns_checksums {
                   11620:     my %checksums;
                   11621:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11622:              \%checksums);
                   11623:     return \%checksums;
                   11624: }
                   11625: 
1.327     albertel 11626: # ------------------------------------------------------------ Read domain file
                   11627: {
1.852     albertel 11628:     my $loaded;
1.846     albertel 11629:     my %domain;
                   11630: 
1.852     albertel 11631:     sub parse_domain_tab {
                   11632: 	my ($lines) = @_;
                   11633: 	foreach my $line (@$lines) {
                   11634: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11635: 
1.846     albertel 11636: 	    chomp($line);
1.852     albertel 11637: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11638: 	    my %this_domain;
                   11639: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11640: 			       'lang_def', 'city', 'longi', 'lati',
                   11641: 			       'primary') {
                   11642: 		$this_domain{$field} = shift(@elements);
                   11643: 	    }
                   11644: 	    $domain{$name} = \%this_domain;
1.852     albertel 11645: 	}
                   11646:     }
1.864     albertel 11647: 
                   11648:     sub reset_domain_info {
                   11649: 	undef($loaded);
                   11650: 	undef(%domain);
                   11651:     }
                   11652: 
1.852     albertel 11653:     sub load_domain_tab {
1.869     albertel 11654: 	my ($ignore_cache) = @_;
                   11655: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11656: 	my $fh;
                   11657: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11658: 	    my @lines = <$fh>;
                   11659: 	    &parse_domain_tab(\@lines);
1.448     albertel 11660: 	}
1.852     albertel 11661: 	close($fh);
                   11662: 	$loaded = 1;
1.327     albertel 11663:     }
1.846     albertel 11664: 
                   11665:     sub domain {
1.852     albertel 11666: 	&load_domain_tab() if (!$loaded);
                   11667: 
1.846     albertel 11668: 	my ($name,$what) = @_;
                   11669: 	return if ( !exists($domain{$name}) );
                   11670: 
                   11671: 	if (!$what) {
                   11672: 	    return $domain{$name}{'description'};
                   11673: 	}
                   11674: 	return $domain{$name}{$what};
                   11675:     }
1.974     raeburn  11676: 
                   11677:     sub domain_info {
                   11678:         &load_domain_tab() if (!$loaded);
                   11679:         return %domain;
                   11680:     }
                   11681: 
1.327     albertel 11682: }
                   11683: 
                   11684: 
1.1       albertel 11685: # ------------------------------------------------------------- Read hosts file
                   11686: {
1.838     albertel 11687:     my %hostname;
1.844     albertel 11688:     my %hostdom;
1.845     albertel 11689:     my %libserv;
1.852     albertel 11690:     my $loaded;
1.888     albertel 11691:     my %name_to_host;
1.1074    raeburn  11692:     my %internetdom;
1.1107    raeburn  11693:     my %LC_dns_serv;
1.852     albertel 11694: 
                   11695:     sub parse_hosts_tab {
                   11696: 	my ($file) = @_;
                   11697: 	foreach my $configline (@$file) {
                   11698: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11699:             chomp($configline);
                   11700: 	    if ($configline =~ /^\^/) {
                   11701:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11702:                     $LC_dns_serv{$1} = 1;
                   11703:                 }
                   11704:                 next;
                   11705:             }
1.1074    raeburn  11706: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11707: 	    $name=~s/\s//g;
                   11708: 	    if ($id && $domain && $role && $name) {
                   11709: 		$hostname{$id}=$name;
1.888     albertel 11710: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11711: 		$hostdom{$id}=$domain;
                   11712: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11713:                 if (defined($protocol)) {
                   11714:                     if ($protocol eq 'https') {
                   11715:                         $protocol{$id} = $protocol;
                   11716:                     } else {
                   11717:                         $protocol{$id} = 'http'; 
                   11718:                     }
1.968     raeburn  11719:                 } else {
1.969     raeburn  11720:                     $protocol{$id} = 'http';
1.968     raeburn  11721:                 }
1.1074    raeburn  11722:                 if (defined($intdom)) {
                   11723:                     $internetdom{$id} = $intdom;
                   11724:                 }
1.852     albertel 11725: 	    }
                   11726: 	}
                   11727:     }
1.864     albertel 11728:     
                   11729:     sub reset_hosts_info {
1.897     albertel 11730: 	&purge_remembered();
1.864     albertel 11731: 	&reset_domain_info();
                   11732: 	&reset_hosts_ip_info();
1.892     albertel 11733: 	undef(%name_to_host);
1.864     albertel 11734: 	undef(%hostname);
                   11735: 	undef(%hostdom);
                   11736: 	undef(%libserv);
                   11737: 	undef($loaded);
                   11738:     }
1.1       albertel 11739: 
1.852     albertel 11740:     sub load_hosts_tab {
1.869     albertel 11741: 	my ($ignore_cache) = @_;
                   11742: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11743: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11744: 	my @config = <$config>;
                   11745: 	&parse_hosts_tab(\@config);
                   11746: 	close($config);
                   11747: 	$loaded=1;
1.1       albertel 11748:     }
1.852     albertel 11749: 
1.838     albertel 11750:     sub hostname {
1.852     albertel 11751: 	&load_hosts_tab() if (!$loaded);
                   11752: 
1.838     albertel 11753: 	my ($lonid) = @_;
                   11754: 	return $hostname{$lonid};
                   11755:     }
1.845     albertel 11756: 
1.838     albertel 11757:     sub all_hostnames {
1.852     albertel 11758: 	&load_hosts_tab() if (!$loaded);
                   11759: 
1.838     albertel 11760: 	return %hostname;
                   11761:     }
1.845     albertel 11762: 
1.888     albertel 11763:     sub all_names {
                   11764: 	&load_hosts_tab() if (!$loaded);
                   11765: 
                   11766: 	return %name_to_host;
                   11767:     }
                   11768: 
1.974     raeburn  11769:     sub all_host_domain {
                   11770:         &load_hosts_tab() if (!$loaded);
                   11771:         return %hostdom;
                   11772:     }
                   11773: 
1.845     albertel 11774:     sub is_library {
1.852     albertel 11775: 	&load_hosts_tab() if (!$loaded);
                   11776: 
1.845     albertel 11777: 	return exists($libserv{$_[0]});
                   11778:     }
                   11779: 
                   11780:     sub all_library {
1.852     albertel 11781: 	&load_hosts_tab() if (!$loaded);
                   11782: 
1.845     albertel 11783: 	return %libserv;
                   11784:     }
                   11785: 
1.1062    droeschl 11786:     sub unique_library {
                   11787: 	#2x reverse removes all hostnames that appear more than once
                   11788:         my %unique = reverse &all_library();
                   11789:         return reverse %unique;
                   11790:     }
                   11791: 
1.841     albertel 11792:     sub get_servers {
1.852     albertel 11793: 	&load_hosts_tab() if (!$loaded);
                   11794: 
1.841     albertel 11795: 	my ($domain,$type) = @_;
                   11796: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11797: 	                                          : %hostname;
                   11798: 	my %result;
1.842     albertel 11799: 	if (ref($domain) eq 'ARRAY') {
                   11800: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11801: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11802: 		    $result{$host} = $hostname;
                   11803: 		}
                   11804: 	    }
                   11805: 	} else {
                   11806: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11807: 		if ($hostdom{$host} eq $domain) {
                   11808: 		    $result{$host} = $hostname;
                   11809: 		}
1.841     albertel 11810: 	    }
                   11811: 	}
                   11812: 	return %result;
                   11813:     }
1.845     albertel 11814: 
1.1062    droeschl 11815:     sub get_unique_servers {
                   11816:         my %unique = reverse &get_servers(@_);
                   11817: 	return reverse %unique;
                   11818:     }
                   11819: 
1.844     albertel 11820:     sub host_domain {
1.852     albertel 11821: 	&load_hosts_tab() if (!$loaded);
                   11822: 
1.844     albertel 11823: 	my ($lonid) = @_;
                   11824: 	return $hostdom{$lonid};
                   11825:     }
                   11826: 
1.841     albertel 11827:     sub all_domains {
1.852     albertel 11828: 	&load_hosts_tab() if (!$loaded);
                   11829: 
1.841     albertel 11830: 	my %seen;
                   11831: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11832: 	return @uniq;
                   11833:     }
1.1074    raeburn  11834: 
                   11835:     sub internet_dom {
                   11836:         &load_hosts_tab() if (!$loaded);
                   11837: 
                   11838:         my ($lonid) = @_;
                   11839:         return $internetdom{$lonid};
                   11840:     }
1.1107    raeburn  11841: 
                   11842:     sub is_LC_dns {
                   11843:         &load_hosts_tab() if (!$loaded);
                   11844: 
                   11845:         my ($hostname) = @_;
                   11846:         return exists($LC_dns_serv{$hostname});
                   11847:     }
                   11848: 
1.1       albertel 11849: }
                   11850: 
1.847     albertel 11851: { 
                   11852:     my %iphost;
1.856     albertel 11853:     my %name_to_ip;
                   11854:     my %lonid_to_ip;
1.869     albertel 11855: 
1.847     albertel 11856:     sub get_hosts_from_ip {
                   11857: 	my ($ip) = @_;
                   11858: 	my %iphosts = &get_iphost();
                   11859: 	if (ref($iphosts{$ip})) {
                   11860: 	    return @{$iphosts{$ip}};
                   11861: 	}
                   11862: 	return;
1.839     albertel 11863:     }
1.864     albertel 11864:     
                   11865:     sub reset_hosts_ip_info {
                   11866: 	undef(%iphost);
                   11867: 	undef(%name_to_ip);
                   11868: 	undef(%lonid_to_ip);
                   11869:     }
1.856     albertel 11870: 
                   11871:     sub get_host_ip {
                   11872: 	my ($lonid) = @_;
                   11873: 	if (exists($lonid_to_ip{$lonid})) {
                   11874: 	    return $lonid_to_ip{$lonid};
                   11875: 	}
                   11876: 	my $name=&hostname($lonid);
                   11877:    	my $ip = gethostbyname($name);
                   11878: 	return if (!$ip || length($ip) ne 4);
                   11879: 	$ip=inet_ntoa($ip);
                   11880: 	$name_to_ip{$name}   = $ip;
                   11881: 	$lonid_to_ip{$lonid} = $ip;
                   11882: 	return $ip;
                   11883:     }
1.847     albertel 11884:     
                   11885:     sub get_iphost {
1.869     albertel 11886: 	my ($ignore_cache) = @_;
1.894     albertel 11887: 
1.869     albertel 11888: 	if (!$ignore_cache) {
                   11889: 	    if (%iphost) {
                   11890: 		return %iphost;
                   11891: 	    }
                   11892: 	    my ($ip_info,$cached)=
                   11893: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11894: 	    if ($cached) {
                   11895: 		%iphost      = %{$ip_info->[0]};
                   11896: 		%name_to_ip  = %{$ip_info->[1]};
                   11897: 		%lonid_to_ip = %{$ip_info->[2]};
                   11898: 		return %iphost;
                   11899: 	    }
                   11900: 	}
1.894     albertel 11901: 
                   11902: 	# get yesterday's info for fallback
                   11903: 	my %old_name_to_ip;
                   11904: 	my ($ip_info,$cached)=
                   11905: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11906: 	if ($cached) {
                   11907: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11908: 	}
                   11909: 
1.888     albertel 11910: 	my %name_to_host = &all_names();
                   11911: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11912: 	    my $ip;
                   11913: 	    if (!exists($name_to_ip{$name})) {
                   11914: 		$ip = gethostbyname($name);
                   11915: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11916: 		    if (defined($old_name_to_ip{$name})) {
                   11917: 			$ip = $old_name_to_ip{$name};
                   11918: 			&logthis("Can't find $name defaulting to old $ip");
                   11919: 		    } else {
                   11920: 			&logthis("Name $name no IP found");
                   11921: 			next;
                   11922: 		    }
                   11923: 		} else {
                   11924: 		    $ip=inet_ntoa($ip);
1.847     albertel 11925: 		}
                   11926: 		$name_to_ip{$name} = $ip;
                   11927: 	    } else {
                   11928: 		$ip = $name_to_ip{$name};
1.653     albertel 11929: 	    }
1.888     albertel 11930: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11931: 		$lonid_to_ip{$id} = $ip;
                   11932: 	    }
                   11933: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11934: 	}
1.869     albertel 11935: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11936: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11937: 				      48*60*60);
1.869     albertel 11938: 
1.847     albertel 11939: 	return %iphost;
1.598     albertel 11940:     }
                   11941: 
1.992     raeburn  11942:     #
                   11943:     #  Given a DNS returns the loncapa host name for that DNS 
                   11944:     # 
                   11945:     sub host_from_dns {
                   11946:         my ($dns) = @_;
                   11947:         my @hosts;
                   11948:         my $ip;
                   11949: 
1.993     raeburn  11950:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11951:             $ip = $name_to_ip{$dns};
                   11952:         }
                   11953:         if (!$ip) {
                   11954:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11955:             if (length($ip) == 4) { 
                   11956: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11957:             }
                   11958:         }
                   11959:         if ($ip) {
                   11960: 	    @hosts = get_hosts_from_ip($ip);
                   11961: 	    return $hosts[0];
                   11962:         }
                   11963:         return undef;
1.986     foxr     11964:     }
1.992     raeburn  11965: 
1.1074    raeburn  11966:     sub get_internet_names {
                   11967:         my ($lonid) = @_;
                   11968:         return if ($lonid eq '');
                   11969:         my ($idnref,$cached)=
                   11970:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11971:         if ($cached) {
                   11972:             return $idnref;
                   11973:         }
                   11974:         my $ip = &get_host_ip($lonid);
                   11975:         my @hosts = &get_hosts_from_ip($ip);
                   11976:         my %iphost = &get_iphost();
                   11977:         my (@idns,%seen);
                   11978:         foreach my $id (@hosts) {
                   11979:             my $dom = &host_domain($id);
                   11980:             my $prim_id = &domain($dom,'primary');
                   11981:             my $prim_ip = &get_host_ip($prim_id);
                   11982:             next if ($seen{$prim_ip});
                   11983:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11984:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11985:                     my $intdom = &internet_dom($id);
                   11986:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11987:                         push(@idns,$intdom);
                   11988:                     }
                   11989:                 }
                   11990:             }
                   11991:             $seen{$prim_ip} = 1;
                   11992:         }
                   11993:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11994:     }
                   11995: 
1.986     foxr     11996: }
                   11997: 
1.1079    raeburn  11998: sub all_loncaparevs {
                   11999:     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);
                   12000: }
                   12001: 
1.862     albertel 12002: BEGIN {
                   12003: 
                   12004: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12005:     unless ($readit) {
                   12006: {
                   12007:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12008:     %perlvar = (%perlvar,%{$configvars});
                   12009: }
                   12010: 
                   12011: 
1.1       albertel 12012: # ------------------------------------------------------ Read spare server file
                   12013: {
1.448     albertel 12014:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12015: 
                   12016:     while (my $configline=<$config>) {
                   12017:        chomp($configline);
1.284     matthew  12018:        if ($configline) {
1.784     albertel 12019: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12020: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12021: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12022:        }
                   12023:     }
1.448     albertel 12024:     close($config);
1.1       albertel 12025: }
1.11      www      12026: # ------------------------------------------------------------ Read permissions
                   12027: {
1.448     albertel 12028:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12029: 
                   12030:     while (my $configline=<$config>) {
1.448     albertel 12031: 	chomp($configline);
                   12032: 	if ($configline) {
                   12033: 	    my ($role,$perm)=split(/ /,$configline);
                   12034: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12035: 	}
1.11      www      12036:     }
1.448     albertel 12037:     close($config);
1.11      www      12038: }
                   12039: 
                   12040: # -------------------------------------------- Read plain texts for permissions
                   12041: {
1.448     albertel 12042:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12043: 
                   12044:     while (my $configline=<$config>) {
1.448     albertel 12045: 	chomp($configline);
                   12046: 	if ($configline) {
1.742     raeburn  12047: 	    my ($short,@plain)=split(/:/,$configline);
                   12048:             %{$prp{$short}} = ();
                   12049: 	    if (@plain > 0) {
                   12050:                 $prp{$short}{'std'} = $plain[0];
                   12051:                 for (my $i=1; $i<@plain; $i++) {
                   12052:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12053:                 }
                   12054:             }
1.448     albertel 12055: 	}
1.135     www      12056:     }
1.448     albertel 12057:     close($config);
1.135     www      12058: }
                   12059: 
                   12060: # ---------------------------------------------------------- Read package table
                   12061: {
1.448     albertel 12062:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12063: 
                   12064:     while (my $configline=<$config>) {
1.483     albertel 12065: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12066: 	chomp($configline);
                   12067: 	my ($short,$plain)=split(/:/,$configline);
                   12068: 	my ($pack,$name)=split(/\&/,$short);
                   12069: 	if ($plain ne '') {
                   12070: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12071: 	    $packagetab{$short}=$plain; 
                   12072: 	}
1.11      www      12073:     }
1.448     albertel 12074:     close($config);
1.329     matthew  12075: }
                   12076: 
1.1073    raeburn  12077: # ---------------------------------------------------------- Read loncaparev table
                   12078: {
                   12079:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12080:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12081:             while (my $configline=<$config>) {
                   12082:                 chomp($configline);
                   12083:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12084:                 $loncaparevs{$hostid}=$loncaparev;
                   12085:             }
                   12086:             close($config);
                   12087:         }
                   12088:     }
                   12089: }
                   12090: 
1.1074    raeburn  12091: # ---------------------------------------------------------- Read serverhostID table
                   12092: {
                   12093:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12094:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12095:             while (my $configline=<$config>) {
                   12096:                 chomp($configline);
                   12097:                 my ($name,$id)=split(/:/,$configline);
                   12098:                 $serverhomeIDs{$name}=$id;
                   12099:             }
                   12100:             close($config);
                   12101:         }
                   12102:     }
                   12103: }
                   12104: 
1.1079    raeburn  12105: {
                   12106:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12107:     if (-e $file) {
                   12108:         my $parser = HTML::LCParser->new($file);
                   12109:         while (my $token = $parser->get_token()) {
                   12110:             if ($token->[0] eq 'S') {
                   12111:                 my $item = $token->[1];
                   12112:                 my $name = $token->[2]{'name'};
                   12113:                 my $value = $token->[2]{'value'};
                   12114:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12115:                     my $release = $parser->get_text();
                   12116:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12117:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12118:                 }
                   12119:             }
                   12120:         }
                   12121:     }
1.1073    raeburn  12122: }
                   12123: 
1.1138    raeburn  12124: # ---------------------------------------------------------- Read managers table
                   12125: {
                   12126:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12127:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12128:             while (my $configline=<$config>) {
                   12129:                 chomp($configline);
                   12130:                 next if ($configline =~ /^\#/);
                   12131:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12132:                     $managerstab{$configline} = 1;
                   12133:                 }
                   12134:             }
                   12135:             close($config);
                   12136:         }
                   12137:     }
                   12138: }
                   12139: 
1.329     matthew  12140: # ------------- set up temporary directory
                   12141: {
1.1117    foxr     12142:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12143: 
1.11      www      12144: }
                   12145: 
1.794     albertel 12146: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12147: 				'compress_threshold'=> 20_000,
                   12148:  			        });
1.185     www      12149: 
1.281     www      12150: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12151: $dumpcount=0;
1.958     www      12152: $locknum=0;
1.22      www      12153: 
1.163     harris41 12154: &logtouch();
1.672     albertel 12155: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12156: $readit=1;
1.564     albertel 12157:     {
                   12158: 	use integer;
                   12159: 	my $test=(2**32)+1;
1.568     albertel 12160: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12161: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12162:     }
1.1172.2.18  raeburn  12163: 
                   12164:     {
                   12165:         eval {
                   12166:             ($apache) =
                   12167:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12168:         };
                   12169:         if ($@) {
                   12170:            $apache = 1.3;
                   12171:         }
                   12172:     }
                   12173: 
1.195     www      12174: }
1.1       albertel 12175: }
1.179     www      12176: 
1.1       albertel 12177: 1;
1.191     harris41 12178: __END__
                   12179: 
1.243     albertel 12180: =pod
                   12181: 
1.191     harris41 12182: =head1 NAME
                   12183: 
1.243     albertel 12184: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12185: 
                   12186: =head1 SYNOPSIS
                   12187: 
1.243     albertel 12188: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12189: 
                   12190:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12191: 
1.243     albertel 12192: Common parameters:
                   12193: 
                   12194: =over 4
                   12195: 
                   12196: =item *
                   12197: 
                   12198: $uname : an internal username (if $cname expecting a course Id specifically)
                   12199: 
                   12200: =item *
                   12201: 
                   12202: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12203: 
                   12204: =item *
                   12205: 
                   12206: $symb : a resource instance identifier
                   12207: 
                   12208: =item *
                   12209: 
                   12210: $namespace : the name of a .db file that contains the data needed or
                   12211: being set.
                   12212: 
                   12213: =back
                   12214: 
1.394     bowersj2 12215: =head1 OVERVIEW
1.191     harris41 12216: 
1.394     bowersj2 12217: lonnet provides subroutines which interact with the
                   12218: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12219: about classes, users, and resources.
1.243     albertel 12220: 
                   12221: For many of these objects you can also use this to store data about
                   12222: them or modify them in various ways.
1.191     harris41 12223: 
1.394     bowersj2 12224: =head2 Symbs
1.191     harris41 12225: 
1.394     bowersj2 12226: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12227: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12228: map, the resource number of the resource in the map, and the URL of
                   12229: the resource itself. The latter is somewhat redundant, but might help
                   12230: if maps change.
                   12231: 
                   12232: An example is
                   12233: 
                   12234:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12235: 
                   12236: The respective map entry is
                   12237: 
                   12238:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12239:   title="Problem 2">
                   12240:  </resource>
                   12241: 
                   12242: Symbs are used by the random number generator, as well as to store and
                   12243: restore data specific to a certain instance of for example a problem.
                   12244: 
                   12245: =head2 Storing And Retrieving Data
                   12246: 
                   12247: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12248: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12249: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12250: is is the non-critical message twin of cstore. These functions are for
                   12251: handlers to store a perl hash to a user's permanent data space in an
                   12252: easy manner, and to retrieve it again on another call. It is expected
                   12253: that a handler would use this once at the beginning to retrieve data,
                   12254: and then again once at the end to send only the new data back.
                   12255: 
                   12256: The data is stored in the user's data directory on the user's
                   12257: homeserver under the ID of the course.
                   12258: 
                   12259: The hash that is returned by restore will have all of the previous
                   12260: value for all of the elements of the hash.
                   12261: 
                   12262: Example:
                   12263: 
                   12264:  #creating a hash
                   12265:  my %hash;
                   12266:  $hash{'foo'}='bar';
                   12267: 
                   12268:  #storing it
                   12269:  &Apache::lonnet::cstore(\%hash);
                   12270: 
                   12271:  #changing a value
                   12272:  $hash{'foo'}='notbar';
                   12273: 
                   12274:  #adding a new value
                   12275:  $hash{'bar'}='foo';
                   12276:  &Apache::lonnet::cstore(\%hash);
                   12277: 
                   12278:  #retrieving the hash
                   12279:  my %history=&Apache::lonnet::restore();
                   12280: 
                   12281:  #print the hash
                   12282:  foreach my $key (sort(keys(%history))) {
                   12283:    print("\%history{$key} = $history{$key}");
                   12284:  }
                   12285: 
                   12286: Will print out:
1.191     harris41 12287: 
1.394     bowersj2 12288:  %history{1:foo} = bar
                   12289:  %history{1:keys} = foo:timestamp
                   12290:  %history{1:timestamp} = 990455579
                   12291:  %history{2:bar} = foo
                   12292:  %history{2:foo} = notbar
                   12293:  %history{2:keys} = foo:bar:timestamp
                   12294:  %history{2:timestamp} = 990455580
                   12295:  %history{bar} = foo
                   12296:  %history{foo} = notbar
                   12297:  %history{timestamp} = 990455580
                   12298:  %history{version} = 2
                   12299: 
                   12300: Note that the special hash entries C<keys>, C<version> and
                   12301: C<timestamp> were added to the hash. C<version> will be equal to the
                   12302: total number of versions of the data that have been stored. The
                   12303: C<timestamp> attribute will be the UNIX time the hash was
                   12304: stored. C<keys> is available in every historical section to list which
                   12305: keys were added or changed at a specific historical revision of a
                   12306: hash.
                   12307: 
                   12308: B<Warning>: do not store the hash that restore returns directly. This
                   12309: will cause a mess since it will restore the historical keys as if the
                   12310: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12311: 
1.394     bowersj2 12312: Calling convention:
1.191     harris41 12313: 
1.394     bowersj2 12314:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12315:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12316: 
1.394     bowersj2 12317: For more detailed information, see lonnet specific documentation.
1.191     harris41 12318: 
1.394     bowersj2 12319: =head1 RETURN MESSAGES
1.191     harris41 12320: 
1.394     bowersj2 12321: =over 4
1.191     harris41 12322: 
1.394     bowersj2 12323: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12324: 
1.394     bowersj2 12325: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12326: when the connection is brought back up
1.191     harris41 12327: 
1.394     bowersj2 12328: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12329: for later delivery
1.191     harris41 12330: 
1.967     bisitz   12331: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12332: 
1.394     bowersj2 12333: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12334: that was requested
1.191     harris41 12335: 
1.243     albertel 12336: =back
1.191     harris41 12337: 
1.243     albertel 12338: =head1 PUBLIC SUBROUTINES
1.191     harris41 12339: 
1.243     albertel 12340: =head2 Session Environment Functions
1.191     harris41 12341: 
1.243     albertel 12342: =over 4
1.191     harris41 12343: 
1.394     bowersj2 12344: =item * 
                   12345: X<appenv()>
1.949     raeburn  12346: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12347: the user envirnoment file, and will be restored for each access this
1.620     albertel 12348: user makes during this session, also modifies the %env for the current
1.949     raeburn  12349: process. Optional rolesarrayref - if defined contains a reference to an array
                   12350: of roles which are exempt from the restriction on modifying user.role entries 
                   12351: in the user's environment.db and in %env.    
1.191     harris41 12352: 
                   12353: =item *
1.394     bowersj2 12354: X<delenv()>
1.987     raeburn  12355: B<delenv($delthis,$regexp)>: removes all items from the session
                   12356: environment file that begin with $delthis. If the 
                   12357: optional second arg - $regexp - is true, $delthis is treated as a 
                   12358: regular expression, otherwise \Q$delthis\E is used. 
                   12359: The values are also deleted from the current processes %env.
1.191     harris41 12360: 
1.795     albertel 12361: =item * get_env_multiple($name) 
                   12362: 
                   12363: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12364: values may be defined and end up as an array ref.
                   12365: 
                   12366: returns an array of values
                   12367: 
1.243     albertel 12368: =back
                   12369: 
                   12370: =head2 User Information
1.191     harris41 12371: 
1.243     albertel 12372: =over 4
1.191     harris41 12373: 
                   12374: =item *
1.394     bowersj2 12375: X<queryauthenticate()>
                   12376: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12377: authentication scheme
                   12378: 
                   12379: =item *
1.394     bowersj2 12380: X<authenticate()>
1.1073    raeburn  12381: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12382: authenticate user from domain's lib servers (first use the current
                   12383: one). C<$upass> should be the users password.
1.1073    raeburn  12384: $checkdefauth is optional (value is 1 if a check should be made to
                   12385:    authenticate user using default authentication method, and allow
                   12386:    account creation if username does not have account in the domain).
                   12387: $clientcancheckhost is optional (value is 1 if checking whether the
                   12388:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12389: 
                   12390: =item *
1.394     bowersj2 12391: X<homeserver()>
                   12392: B<homeserver($uname,$udom)>: find the server which has
                   12393: the user's directory and files (there must be only one), this caches
                   12394: the answer, and also caches if there is a borken connection.
1.191     harris41 12395: 
                   12396: =item *
1.394     bowersj2 12397: X<idget()>
                   12398: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12399: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12400: username, and only 1 username per ID in a specific domain) (returns
                   12401: hash: id=>name,id=>name)
1.191     harris41 12402: 
                   12403: =item *
1.394     bowersj2 12404: X<idrget()>
                   12405: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12406: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12407: 
                   12408: =item *
1.394     bowersj2 12409: X<idput()>
                   12410: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12411: 
                   12412: =item *
1.394     bowersj2 12413: X<rolesinit()>
1.1169    droeschl 12414: B<rolesinit($udom,$username)>: get user privileges.
                   12415: returns user role, first access and timer interval hashes
1.243     albertel 12416: 
                   12417: =item *
1.1171    droeschl 12418: X<privileged()>
                   12419: B<privileged($username,$domain)>: returns a true if user has a
                   12420: privileged and active role (i.e. su or dc), false otherwise.
                   12421: 
                   12422: =item *
1.551     albertel 12423: X<getsection()>
                   12424: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12425: course $cname, return section name/number or '' for "not in course"
                   12426: and '-1' for "no section"
                   12427: 
                   12428: =item *
1.394     bowersj2 12429: X<userenvironment()>
                   12430: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12431: passed in @what from the requested user's environment, returns a hash
                   12432: 
1.858     raeburn  12433: =item * 
                   12434: X<userlog_query()>
1.859     albertel 12435: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12436: activity.log file. %filters defines filters applied when parsing the
                   12437: log file. These can be start or end timestamps, or the type of action
                   12438: - log to look for Login or Logout events, check for Checkin or
                   12439: Checkout, role for role selection. The response is in the form
                   12440: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12441: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12442: 
1.243     albertel 12443: =back
                   12444: 
                   12445: =head2 User Roles
                   12446: 
                   12447: =over 4
                   12448: 
                   12449: =item *
                   12450: 
1.810     raeburn  12451: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12452:  F: full access
                   12453:  U,I,K: authentication modes (cxx only)
                   12454:  '': forbidden
                   12455:  1: user needs to choose course
                   12456:  2: browse allowed
1.766     albertel 12457:  A: passphrase authentication needed
1.243     albertel 12458: 
                   12459: =item *
                   12460: 
1.1172.2.13  raeburn  12461: constructaccess($url,$setpriv) : check for access to construction space URL
                   12462: 
                   12463: See if the owner domain and name in the URL match those in the
                   12464: expected environment.  If so, return three element list
                   12465: ($ownername,$ownerdomain,$ownerhome).
                   12466: 
                   12467: Otherwise return the null string.
                   12468: 
                   12469: If second argument 'setpriv' is true, it assigns the privileges,
                   12470: and returns the same three element list, unless the owner has
                   12471: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12472: in which case the null string is returned.
                   12473: 
                   12474: =item *
                   12475: 
1.243     albertel 12476: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12477: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12478: and course level
                   12479: 
                   12480: =item *
                   12481: 
1.988     raeburn  12482: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12483: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12484: $type is Course (default) or Community.
1.988     raeburn  12485: If $forcedefault evaluates to true, text returned will be default 
                   12486: text for $type. Otherwise, if this is a course, the text returned 
                   12487: will be a custom name for the role (if defined in the course's 
                   12488: environment).  If no custom name is defined the default is returned.
                   12489:    
1.832     raeburn  12490: =item *
                   12491: 
1.935     raeburn  12492: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12493: All arguments are optional. Returns a hash of a roles, either for
                   12494: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12495: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12496: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12497: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12498: For each key, value is set to colon-separated start and end times for
                   12499: the role.  If no username and domain are specified, will default to
1.934     raeburn  12500: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12501: of role statuses (active, future or previous), roles 
                   12502: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12503: to restrict the list of roles reported. If no array ref is 
                   12504: provided for types, will default to return only active roles.
1.834     albertel 12505: 
1.1172.2.13  raeburn  12506: =item *
                   12507: 
                   12508: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12509: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12510: 
                   12511: Additional optional arguments are: $type (if role checking is to be restricted
                   12512: to certain user status types -- previous (expired roles), active (currently
                   12513: available roles) or future (roles available in the future), and
                   12514: $hideprivileged -- if true will not report course roles for users who
                   12515: have active Domain Coordinator or Super User roles.
                   12516: 
1.243     albertel 12517: =back
                   12518: 
                   12519: =head2 User Modification
                   12520: 
                   12521: =over 4
                   12522: 
                   12523: =item *
                   12524: 
1.957     raeburn  12525: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12526: user for the level given by URL.  Optional start and end dates (leave empty
                   12527: string or zero for "no date")
1.191     harris41 12528: 
                   12529: =item *
                   12530: 
1.243     albertel 12531: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12532: change a users, password, possible return values are: ok,
                   12533: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12534: refused
1.191     harris41 12535: 
                   12536: =item *
                   12537: 
1.243     albertel 12538: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12539: 
                   12540: =item *
                   12541: 
1.1058    raeburn  12542: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12543:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12544: 
                   12545: will update user information (firstname,middlename,lastname,generation,
                   12546: permanentemail), and if forceid is true, student/employee ID also.
                   12547: A user's institutional affiliation(s) can also be updated.
                   12548: User information fields will not be overwritten with empty entries 
                   12549: unless the field is included in the $candelete array reference.
                   12550: This array is included when a single user is modified via "Manage Users",
                   12551: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12552: 
                   12553: =item *
                   12554: 
1.286     matthew  12555: modifystudent
                   12556: 
1.957     raeburn  12557: modify a student's enrollment and identification information.
1.286     matthew  12558: The course id is resolved based on the current users environment.  
                   12559: This means the envoking user must be a course coordinator or otherwise
                   12560: associated with a course.
                   12561: 
1.297     matthew  12562: This call is essentially a wrapper for lonnet::modifyuser and
                   12563: lonnet::modify_student_enrollment
1.286     matthew  12564: 
                   12565: Inputs: 
                   12566: 
                   12567: =over 4
                   12568: 
1.957     raeburn  12569: =item B<$udom> Student's loncapa domain
1.286     matthew  12570: 
1.957     raeburn  12571: =item B<$uname> Student's loncapa login name
1.286     matthew  12572: 
1.964     bisitz   12573: =item B<$uid> Student/Employee ID
1.286     matthew  12574: 
1.957     raeburn  12575: =item B<$umode> Student's authentication mode
1.286     matthew  12576: 
1.957     raeburn  12577: =item B<$upass> Student's password
1.286     matthew  12578: 
1.957     raeburn  12579: =item B<$first> Student's first name
1.286     matthew  12580: 
1.957     raeburn  12581: =item B<$middle> Student's middle name
1.286     matthew  12582: 
1.957     raeburn  12583: =item B<$last> Student's last name
1.286     matthew  12584: 
1.957     raeburn  12585: =item B<$gene> Student's generation
1.286     matthew  12586: 
1.957     raeburn  12587: =item B<$usec> Student's section in course
1.286     matthew  12588: 
                   12589: =item B<$end> Unix time of the roles expiration
                   12590: 
                   12591: =item B<$start> Unix time of the roles start date
                   12592: 
                   12593: =item B<$forceid> If defined, allow $uid to be changed
                   12594: 
                   12595: =item B<$desiredhome> server to use as home server for student
                   12596: 
1.957     raeburn  12597: =item B<$email> Student's permanent e-mail address
                   12598: 
                   12599: =item B<$type> Type of enrollment (auto or manual)
                   12600: 
1.963     raeburn  12601: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12602: 
                   12603: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12604: 
1.963     raeburn  12605: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12606: 
1.963     raeburn  12607: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12608: 
1.1172.2.19  raeburn  12609: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12610: 
                   12611: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  12612: 
1.286     matthew  12613: =back
1.297     matthew  12614: 
                   12615: =item *
                   12616: 
                   12617: modify_student_enrollment
                   12618: 
                   12619: Change a students enrollment status in a class.  The environment variable
                   12620: 'role.request.course' must be defined for this function to proceed.
                   12621: 
                   12622: Inputs:
                   12623: 
                   12624: =over 4
                   12625: 
                   12626: =item $udom, students domain
                   12627: 
                   12628: =item $uname, students name
                   12629: 
                   12630: =item $uid, students user id
                   12631: 
                   12632: =item $first, students first name
                   12633: 
                   12634: =item $middle
                   12635: 
                   12636: =item $last
                   12637: 
                   12638: =item $gene
                   12639: 
                   12640: =item $usec
                   12641: 
                   12642: =item $end
                   12643: 
                   12644: =item $start
                   12645: 
1.957     raeburn  12646: =item $type
                   12647: 
                   12648: =item $locktype
                   12649: 
                   12650: =item $cid
                   12651: 
                   12652: =item $selfenroll
                   12653: 
                   12654: =item $context
                   12655: 
1.1172.2.19  raeburn  12656: =item $credits, number of credits student will earn from this class
                   12657: 
1.297     matthew  12658: =back
                   12659: 
1.191     harris41 12660: 
                   12661: =item *
                   12662: 
1.243     albertel 12663: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12664: custom role; give a custom role to a user for the level given by URL.  Specify
                   12665: name and domain of role author, and role name
1.191     harris41 12666: 
                   12667: =item *
                   12668: 
1.243     albertel 12669: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12670: 
                   12671: =item *
                   12672: 
1.243     albertel 12673: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12674: 
                   12675: =back
                   12676: 
                   12677: =head2 Course Infomation
                   12678: 
                   12679: =over 4
1.191     harris41 12680: 
                   12681: =item *
                   12682: 
1.1118    foxr     12683: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12684: specified course id, including all environment settings for the
                   12685: course, the description of the course will be in the hash under the
                   12686: key 'description'
1.191     harris41 12687: 
1.1118    foxr     12688: $options is an optional parameter that if supplied is a hash reference that controls
                   12689: what how this function works.  It has the following key/values:
                   12690: 
                   12691: =over 4
                   12692: 
                   12693: =item freshen_cache
                   12694: 
                   12695: If defined, and the environment cache for the course is valid, it is 
                   12696: returned in the returned hash.
                   12697: 
                   12698: =item one_time
                   12699: 
                   12700: If defined, the last cache time is set to _now_
                   12701: 
                   12702: =item user
                   12703: 
                   12704: If defined, the supplied username is used instead of the current user.
                   12705: 
                   12706: 
                   12707: =back
                   12708: 
1.191     harris41 12709: =item *
                   12710: 
1.624     albertel 12711: resdata($name,$domain,$type,@which) : request for current parameter
                   12712: setting for a specific $type, where $type is either 'course' or 'user',
                   12713: @what should be a list of parameters to ask about. This routine caches
                   12714: answers for 5 minutes.
1.243     albertel 12715: 
1.877     foxr     12716: =item *
                   12717: 
                   12718: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12719: data base, returning a hash that is keyed by the resource name and has
                   12720: values that are the resource value.  I believe that the timestamps and
                   12721: versions are also returned.
                   12722: 
1.243     albertel 12723: =back
                   12724: 
                   12725: =head2 Course Modification
                   12726: 
                   12727: =over 4
1.191     harris41 12728: 
                   12729: =item *
                   12730: 
1.243     albertel 12731: writecoursepref($courseid,%prefs) : write preferences (environment
                   12732: database) for a course
1.191     harris41 12733: 
                   12734: =item *
                   12735: 
1.1011    raeburn  12736: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12737: 
                   12738: =item *
                   12739: 
1.1038    raeburn  12740: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12741: 
1.1167    droeschl 12742: =item *
                   12743: 
                   12744: is_course($courseid), is_course($cdom, $cnum)
                   12745: 
                   12746: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12747: two component version $cdom, $cnum. It checks if the specified course exists.
                   12748: 
                   12749: Returns:
                   12750:     undef if the course doesn't exist, otherwise
                   12751:     in scalar context the combined courseid.
                   12752:     in list context the two components of the course identifier, domain and 
                   12753:     courseid.    
                   12754: 
1.243     albertel 12755: =back
                   12756: 
                   12757: =head2 Resource Subroutines
                   12758: 
                   12759: =over 4
1.191     harris41 12760: 
                   12761: =item *
                   12762: 
1.243     albertel 12763: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12764: 
                   12765: =item *
                   12766: 
1.243     albertel 12767: repcopy($filename) : subscribes to the requested file, and attempts to
                   12768: replicate from the owning library server, Might return
1.607     raeburn  12769: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12770: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12771: resource. Expects the local filesystem pathname
                   12772: (/home/httpd/html/res/....)
                   12773: 
                   12774: =back
                   12775: 
                   12776: =head2 Resource Information
                   12777: 
                   12778: =over 4
1.191     harris41 12779: 
                   12780: =item *
                   12781: 
1.243     albertel 12782: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12783: a vairety of different possible values, $varname should be a request
                   12784: string, and the other parameters can be used to specify who and what
                   12785: one is asking about.
                   12786: 
                   12787: Possible values for $varname are environment.lastname (or other item
                   12788: from the envirnment hash), user.name (or someother aspect about the
                   12789: user), resource.0.maxtries (or some other part and parameter of a
                   12790: resource)
1.204     albertel 12791: 
                   12792: =item *
                   12793: 
1.243     albertel 12794: directcondval($number) : get current value of a condition; reads from a state
                   12795: string
1.204     albertel 12796: 
                   12797: =item *
                   12798: 
1.243     albertel 12799: condval($condidx) : value of condition index based on state
1.204     albertel 12800: 
                   12801: =item *
                   12802: 
1.243     albertel 12803: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12804: resource's metadata, $what should be either a specific key, or either
                   12805: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12806: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12807: 
                   12808: this function automatically caches all requests
1.191     harris41 12809: 
                   12810: =item *
                   12811: 
1.243     albertel 12812: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12813: network of library servers; returns file handle of where SQL and regex results
                   12814: will be stored for query
1.191     harris41 12815: 
                   12816: =item *
                   12817: 
1.243     albertel 12818: symbread($filename) : return symbolic list entry (filename argument optional);
                   12819: returns the data handle
1.191     harris41 12820: 
                   12821: =item *
                   12822: 
1.1172.2.17  raeburn  12823: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12824: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12825: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12826: on failure, user must be in a course, as it assumes the existence of
                   12827: the course initial hash, and uses $env('request.course.id'}.  The third
                   12828: arg is an optional reference to a scalar.  If this arg is passed in the
                   12829: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12830: encrypted; otherwise it will be null.
1.243     albertel 12831: 
1.191     harris41 12832: =item *
                   12833: 
1.243     albertel 12834: symbclean($symb) : removes versions numbers from a symb, returns the
                   12835: cleaned symb
1.191     harris41 12836: 
                   12837: =item *
                   12838: 
1.243     albertel 12839: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12840: course map, user must be in a course for it to work.
1.191     harris41 12841: 
                   12842: =item *
                   12843: 
1.243     albertel 12844: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12845: 
                   12846: =item *
                   12847: 
1.243     albertel 12848: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12849: a random seed, all arguments are optional, if they aren't sent it uses the
                   12850: environment to derive them. Note: if symb isn't sent and it can't get one
                   12851: from &symbread it will use the current time as its return value
1.191     harris41 12852: 
                   12853: =item *
                   12854: 
1.243     albertel 12855: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12856: unfakeable, receipt
1.191     harris41 12857: 
                   12858: =item *
                   12859: 
1.620     albertel 12860: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12861: 
                   12862: =item *
                   12863: 
1.243     albertel 12864: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12865: 
                   12866: =item *
                   12867: 
1.243     albertel 12868: 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 12869: 
                   12870: =item *
                   12871: 
1.243     albertel 12872: 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 12873: 
                   12874: =item *
                   12875: 
1.243     albertel 12876: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12877: 
                   12878: =item *
                   12879: 
1.243     albertel 12880: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12881: forcing spreadsheet to reevaluate the resource scores next time.
                   12882: 
1.1172.2.13  raeburn  12883: =item *
                   12884: 
                   12885: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12886: when viewing in course context.
                   12887: 
                   12888:  input: six args -- filename (decluttered), course number, course domain,
                   12889:                     url, symb (if registered) and group (if this is a
                   12890:                     group item -- e.g., bulletin board, group page etc.).
                   12891: 
                   12892:  output: array of five scalars --
                   12893:          $cfile -- url for file editing if editable on current server
                   12894:          $home -- homeserver of resource (i.e., for author if published,
                   12895:                                           or course if uploaded.).
                   12896:          $switchserver --  1 if server switch will be needed.
                   12897:          $forceedit -- 1 if icon/link should be to go to edit mode
                   12898:          $forceview -- 1 if icon/link should be to go to view mode
                   12899: 
                   12900: =item *
                   12901: 
                   12902: is_course_upload($file,$cnum,$cdom)
                   12903: 
                   12904: Used in course context to determine if current file was uploaded to
                   12905: the course (i.e., would be found in /userfiles/docs on the course's
                   12906: homeserver.
                   12907: 
                   12908:   input: 3 args -- filename (decluttered), course number and course domain.
                   12909:   output: boolean -- 1 if file was uploaded.
                   12910: 
1.243     albertel 12911: =back
                   12912: 
                   12913: =head2 Storing/Retreiving Data
                   12914: 
                   12915: =over 4
1.191     harris41 12916: 
                   12917: =item *
                   12918: 
1.243     albertel 12919: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12920: for this url; hashref needs to be given and should be a \%hashname; the
                   12921: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12922: be derived from the env
1.191     harris41 12923: 
                   12924: =item *
                   12925: 
1.243     albertel 12926: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12927: uses critical subroutine
1.191     harris41 12928: 
                   12929: =item *
                   12930: 
1.243     albertel 12931: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12932: all args are optional
1.191     harris41 12933: 
                   12934: =item *
                   12935: 
1.717     albertel 12936: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12937: dumps the complete (or key matching regexp) namespace into a hash
                   12938: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12939: normally &store()ed into
                   12940: 
                   12941: $range should be either an integer '100' (give me the first 100
                   12942:                                            matching records)
                   12943:               or be  two integers sperated by a - with no spaces
                   12944:                  '30-50' (give me the 30th through the 50th matching
                   12945:                           records)
                   12946: 
                   12947: 
                   12948: =item *
                   12949: 
                   12950: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12951: replaces a &store() version of data with a replacement set of data
                   12952: for a particular resource in a namespace passed in the $storehash hash 
                   12953: reference
                   12954: 
                   12955: =item *
                   12956: 
1.243     albertel 12957: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12958: works very similar to store/cstore, but all data is stored in a
                   12959: temporary location and can be reset using tmpreset, $storehash should
                   12960: be a hash reference, returns nothing on success
1.191     harris41 12961: 
                   12962: =item *
                   12963: 
1.243     albertel 12964: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12965: similar to restore, but all data is stored in a temporary location and
                   12966: can be reset using tmpreset. Returns a hash of values on success,
                   12967: error string otherwise.
1.191     harris41 12968: 
                   12969: =item *
                   12970: 
1.243     albertel 12971: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12972: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12973: 
                   12974: =item *
                   12975: 
1.243     albertel 12976: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12977: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12978: 
                   12979: =item *
                   12980: 
1.243     albertel 12981: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12982: namesp ($udom and $uname are optional)
1.191     harris41 12983: 
                   12984: =item *
                   12985: 
1.702     albertel 12986: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12987: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12988: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12989: 
1.702     albertel 12990: $range should be either an integer '100' (give me the first 100
                   12991:                                            matching records)
                   12992:               or be  two integers sperated by a - with no spaces
                   12993:                  '30-50' (give me the 30th through the 50th matching
                   12994:                           records)
1.449     matthew  12995: =item *
                   12996: 
                   12997: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12998: $store can be a scalar, an array reference, or if the amount to be 
                   12999: incremented is > 1, a hash reference.
                   13000: 
                   13001: ($udom and $uname are optional)
1.191     harris41 13002: 
                   13003: =item *
                   13004: 
1.243     albertel 13005: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13006: ($udom and $uname are optional)
1.191     harris41 13007: 
                   13008: =item *
                   13009: 
1.243     albertel 13010: cput($namespace,$storehash,$udom,$uname) : critical put
                   13011: ($udom and $uname are optional)
1.191     harris41 13012: 
                   13013: =item *
                   13014: 
1.748     albertel 13015: newput($namespace,$storehash,$udom,$uname) :
                   13016: 
                   13017: Attempts to store the items in the $storehash, but only if they don't
                   13018: currently exist, if this succeeds you can be certain that you have 
                   13019: successfully created a new key value pair in the $namespace db.
                   13020: 
                   13021: 
                   13022: Args:
                   13023:  $namespace: name of database to store values to
                   13024:  $storehash: hashref to store to the db
                   13025:  $udom: (optional) domain of user containing the db
                   13026:  $uname: (optional) name of user caontaining the db
                   13027: 
                   13028: Returns:
                   13029:  'ok' -> succeeded in storing all keys of $storehash
                   13030:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13031:                         least <key> already existed in the db (other
                   13032:                         requested keys may also already exist)
1.967     bisitz   13033:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13034:  'con_lost' -> unable to contact request server
                   13035:  'refused' -> action was not allowed by remote machine
                   13036: 
                   13037: 
                   13038: =item *
                   13039: 
1.243     albertel 13040: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13041: reference filled in from namesp (encrypts the return communication)
                   13042: ($udom and $uname are optional)
1.191     harris41 13043: 
                   13044: =item *
                   13045: 
1.243     albertel 13046: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13047: critical subroutine
                   13048: 
1.806     raeburn  13049: =item *
                   13050: 
1.860     raeburn  13051: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13052: array reference filled in from namespace found in domain level on either
                   13053: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13054: 
                   13055: =item *
                   13056: 
1.860     raeburn  13057: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13058: domain level either on specified domain server ($uhome) or primary domain 
                   13059: server ($udom and $uhome are optional)
1.806     raeburn  13060: 
1.943     raeburn  13061: =item * 
                   13062: 
                   13063: get_domain_defaults($target_domain) : returns hash with defaults for
                   13064: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13065: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13066: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13067: Values are retrieved from cache (if current), or from domain's configuration.db
                   13068: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13069: or lonTabs/domain.tab. 
                   13070: 
                   13071: %domdefaults = &get_auth_defaults($target_domain);
                   13072: 
1.243     albertel 13073: =back
                   13074: 
                   13075: =head2 Network Status Functions
                   13076: 
                   13077: =over 4
1.191     harris41 13078: 
                   13079: =item *
                   13080: 
1.1137    raeburn  13081: dirlist() : return directory list based on URI (first arg).
                   13082: 
                   13083: Inputs: 1 required, 5 optional.
                   13084: 
                   13085: =over
                   13086: 
                   13087: =item 
                   13088: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13089: 
                   13090: =item
                   13091: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13092: 
                   13093: =item
                   13094: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13095: 
                   13096: =item
                   13097: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13098: 
                   13099: =item
                   13100: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13101: 
                   13102: =item 
                   13103: $alternateRoot - path to prepend in place of path from $uri.
                   13104: 
                   13105: =back
                   13106: 
                   13107: Returns: Array of up to two items.
                   13108: 
                   13109: =over
                   13110: 
                   13111: a reference to an array of files/subdirectories
                   13112: 
                   13113: =over
                   13114: 
                   13115: Each element in the array of files/subdirectories is a & separated list of
                   13116: item name and the result of running stat on the item.  If dirlist was requested
                   13117: for a file instead of a directory, the item name will be ''. For a directory 
                   13118: listing, if the item is a metadata file, the element will end &N&M 
                   13119: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13120: default copyright set (1).  
                   13121: 
                   13122: =back
                   13123: 
                   13124: a scalar containing error condition (if encountered).
                   13125: 
                   13126: =over
                   13127: 
                   13128: =item 
                   13129: no_host (no homeserver identified for $username:$domain).
                   13130: 
                   13131: =item 
                   13132: no_such_host (server contacted for listing not identified as valid host).
                   13133: 
                   13134: =item 
                   13135: con_lost (connection to remote server failed).
                   13136: 
                   13137: =item 
                   13138: refused (invalid $username:$domain received on lond side).
                   13139: 
                   13140: =item 
                   13141: no_such_dir (directory at specified path on lond side does not exist). 
                   13142: 
                   13143: =item 
                   13144: empty (directory at specified path on lond side is empty).
                   13145: 
                   13146: =over
                   13147: 
                   13148: This is currently not encountered because the &ls3, &ls2, 
                   13149: &ls (_handler) routines on the lond side do not filter out
                   13150: . and .. from a directory listing. 
                   13151: 
                   13152: =back
                   13153: 
                   13154: =back
                   13155: 
                   13156: =back
1.191     harris41 13157: 
                   13158: =item *
                   13159: 
1.243     albertel 13160: spareserver() : find server with least workload from spare.tab
                   13161: 
1.986     foxr     13162: 
                   13163: =item *
                   13164: 
                   13165: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13166: if there is no corresponding loncapa host.
                   13167: 
1.243     albertel 13168: =back
                   13169: 
1.986     foxr     13170: 
1.243     albertel 13171: =head2 Apache Request
                   13172: 
                   13173: =over 4
1.191     harris41 13174: 
                   13175: =item *
                   13176: 
1.243     albertel 13177: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13178: localhost, posts hash
                   13179: 
                   13180: =back
                   13181: 
                   13182: =head2 Data to String to Data
                   13183: 
                   13184: =over 4
1.191     harris41 13185: 
                   13186: =item *
                   13187: 
1.243     albertel 13188: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13189: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13190: 
                   13191: =item *
                   13192: 
1.243     albertel 13193: hashref2str($hashref) : convert a hashref into a string complete with
                   13194: escaping and '=' and '&' separators, supports elements that are
                   13195: arrayrefs and hashrefs
1.191     harris41 13196: 
                   13197: =item *
                   13198: 
1.243     albertel 13199: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13200: with escaping and '&' separators, supports elements that are arrayrefs
                   13201: and hashrefs
1.191     harris41 13202: 
                   13203: =item *
                   13204: 
1.243     albertel 13205: str2hash($string) : convert string to hash using unescaping and
                   13206: splitting on '=' and '&', supports elements that are arrayrefs and
                   13207: hashrefs
1.191     harris41 13208: 
                   13209: =item *
                   13210: 
1.243     albertel 13211: str2array($string) : convert string to hash using unescaping and
                   13212: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13213: 
                   13214: =back
                   13215: 
                   13216: =head2 Logging Routines
                   13217: 
                   13218: 
                   13219: These routines allow one to make log messages in the lonnet.log and
                   13220: lonnet.perm logfiles.
1.191     harris41 13221: 
1.1119    foxr     13222: =over 4
                   13223: 
1.191     harris41 13224: =item *
                   13225: 
1.243     albertel 13226: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13227: 
                   13228: =item *
                   13229: 
1.243     albertel 13230: logthis() : append message to the normal lonnet.log file, it gets
                   13231: preiodically rolled over and deleted.
1.191     harris41 13232: 
                   13233: =item *
                   13234: 
1.243     albertel 13235: logperm() : append a permanent message to lonnet.perm.log, this log
                   13236: file never gets deleted by any automated portion of the system, only
                   13237: messages of critical importance should go in here.
                   13238: 
1.1119    foxr     13239: 
1.243     albertel 13240: =back
                   13241: 
                   13242: =head2 General File Helper Routines
                   13243: 
                   13244: =over 4
1.191     harris41 13245: 
                   13246: =item *
                   13247: 
1.481     raeburn  13248: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13249: (a) files in /uploaded
                   13250:   (i) If a local copy of the file exists - 
                   13251:       compares modification date of local copy with last-modified date for 
                   13252:       definitive version stored on home server for course. If local copy is 
                   13253:       stale, requests a new version from the home server and stores it. 
                   13254:       If the original has been removed from the home server, then local copy 
                   13255:       is unlinked.
                   13256:   (ii) If local copy does not exist -
                   13257:       requests the file from the home server and stores it. 
                   13258:   
                   13259:   If $caller is 'uploadrep':  
                   13260:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13261:     for request for files originally uploaded via DOCS. 
                   13262:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13263:   
                   13264:   Otherwise:
                   13265:      This indicates a call from the content generation phase of the request.
                   13266:      -  returns the entire contents of the file or -1.
                   13267:      
                   13268: (b) files in /res
                   13269:    - returns the entire contents of a file or -1; 
                   13270:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13271: 
1.712     albertel 13272: 
                   13273: =item *
                   13274: 
                   13275: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13276:                   reference
                   13277: 
                   13278: returns either a stat() list of data about the file or an empty list
                   13279: if the file doesn't exist or couldn't find out about it (connection
                   13280: problems or user unknown)
                   13281: 
1.191     harris41 13282: =item *
                   13283: 
1.243     albertel 13284: filelocation($dir,$file) : returns file system location of a file
                   13285: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13286: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13287: and a file of ../bob will become /a/bob)
1.191     harris41 13288: 
                   13289: =item *
                   13290: 
                   13291: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13292: filelocation except for hrefs
                   13293: 
                   13294: =item *
                   13295: 
                   13296: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13297: 
1.243     albertel 13298: =back
                   13299: 
1.608     albertel 13300: =head2 Usererfile file routines (/uploaded*)
                   13301: 
                   13302: =over 4
                   13303: 
                   13304: =item *
                   13305: 
                   13306: userfileupload(): main rotine for putting a file in a user or course's
                   13307:                   filespace, arguments are,
                   13308: 
1.620     albertel 13309:  formname - required - this is the name of the element in $env where the
1.608     albertel 13310:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13311:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13312:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13313:  context - if coursedoc, store the file in the course of the active role
                   13314:              of the current user; 
                   13315:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13316:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13317:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13318:          if undefined, it will be placed in "unknown"
                   13319: 
                   13320:  (This routine calls clean_filename() to remove any dangerous
                   13321:  characters from the filename, and then calls finuserfileupload() to
                   13322:  complete the transaction)
                   13323: 
                   13324:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13325:  and /adm/notfound.html if unsuccessful
                   13326: 
                   13327: =item *
                   13328: 
                   13329: clean_filename(): routine for cleaing a filename up for storage in
                   13330:                  userfile space, argument is:
                   13331: 
                   13332:  filename - proposed filename
                   13333: 
                   13334: returns: the new clean filename
                   13335: 
                   13336: =item *
                   13337: 
1.1090    raeburn  13338: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13339: userspace, probably shouldn't be called directly
                   13340: 
                   13341:   docuname: username or courseid of destination for the file
                   13342:   docudom: domain of user/course of destination for the file
                   13343:   formname: same as for userfileupload()
1.1090    raeburn  13344:   fname: filename (including subdirectories) for the file
                   13345:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13346:   allfiles: reference to hash used to store objects found by parser
                   13347:   codebase: reference to hash used for codebases of java objects found by parser
                   13348:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13349:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13350:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13351:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13352:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13353:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13354:   mimetype: reference to scalar to accommodate mime type determined
                   13355:             from File::MMagic if $parser = parse.
1.608     albertel 13356: 
                   13357:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13358:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13359:  was 'overwrite').
                   13360:  
1.608     albertel 13361: 
                   13362: =item *
                   13363: 
                   13364: renameuserfile(): renames an existing userfile to a new name
                   13365: 
                   13366:   Args:
                   13367:    docuname: username or courseid of destination for the file
                   13368:    docudom: domain of user/course of destination for the file
                   13369:    old: current file name (including any subdirs under userfiles)
                   13370:    new: desired file name (including any subdirs under userfiles)
                   13371: 
                   13372: =item *
                   13373: 
                   13374: mkdiruserfile(): creates a directory is a userfiles dir
                   13375: 
                   13376:   Args:
                   13377:    docuname: username or courseid of destination for the file
                   13378:    docudom: domain of user/course of destination for the file
                   13379:    dir: dir to create (including any subdirs under userfiles)
                   13380: 
                   13381: =item *
                   13382: 
                   13383: removeuserfile(): removes a file that exists in userfiles
                   13384: 
                   13385:   Args:
                   13386:    docuname: username or courseid of destination for the file
                   13387:    docudom: domain of user/course of destination for the file
                   13388:    fname: filname to delete (including any subdirs under userfiles)
                   13389: 
                   13390: =item *
                   13391: 
                   13392: removeuploadedurl(): convience function for removeuserfile()
                   13393: 
                   13394:   Args:
                   13395:    url:  a full /uploaded/... url to delete
                   13396: 
1.747     albertel 13397: =item * 
                   13398: 
                   13399: get_portfile_permissions():
                   13400:   Args:
                   13401:     domain: domain of user or course contain the portfolio files
                   13402:     user: name of user or num of course contain the portfolio files
                   13403:   Returns:
                   13404:     hashref of a dump of the proper file_permissions.db
                   13405:    
                   13406: 
                   13407: =item * 
                   13408: 
                   13409: get_access_controls():
                   13410: 
                   13411: Args:
                   13412:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13413:   group: (optional) the group you want the files associated with
                   13414:   file: (optional) the file you want access info on
                   13415: 
                   13416: Returns:
1.749     raeburn  13417:     a hash (keys are file names) of hashes containing
                   13418:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13419:         values are XML containing access control settings (see below) 
1.747     albertel 13420: 
                   13421: Internal notes:
                   13422: 
1.749     raeburn  13423:  access controls are stored in file_permissions.db as key=value pairs.
                   13424:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13425:         where scope -> public,guest,course,group,domains or users.
                   13426:               end -> UNIX time for end of access (0 -> no end date)
                   13427:               start -> UNIX time for start of access
                   13428: 
                   13429:     value -> XML description of access control
                   13430:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13431:             <start></start>
                   13432:             <end></end>
                   13433: 
                   13434:             <password></password>  for scope type = guest
                   13435: 
                   13436:             <domain></domain>     for scope type = course or group
                   13437:             <number></number>
                   13438:             <roles id="">
                   13439:              <role></role>
                   13440:              <access></access>
                   13441:              <section></section>
                   13442:              <group></group>
                   13443:             </roles>
                   13444: 
                   13445:             <dom></dom>         for scope type = domains
                   13446: 
                   13447:             <users>             for scope type = users
                   13448:              <user>
                   13449:               <uname></uname>
                   13450:               <udom></udom>
                   13451:              </user>
                   13452:             </users>
                   13453:            </scope> 
                   13454:               
                   13455:  Access data is also aggregated for each file in an additional key=value pair:
                   13456:  key -> path to file/file_name\0accesscontrol 
                   13457:  value -> reference to hash
                   13458:           hash contains key = value pairs
                   13459:           where key = uniqueID:scope_end_start
                   13460:                 value = UNIX time record was last updated
                   13461: 
                   13462:           Used to improve speed of look-ups of access controls for each file.  
                   13463:  
                   13464:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13465: 
1.1172.2.13  raeburn  13466: =item *
                   13467: 
1.749     raeburn  13468: modify_access_controls():
                   13469: 
                   13470: Modifies access controls for a portfolio file
                   13471: Args
                   13472: 1. file name
                   13473: 2. reference to hash of required changes,
                   13474: 3. domain
                   13475: 4. username
                   13476:   where domain,username are the domain of the portfolio owner 
                   13477:   (either a user or a course) 
                   13478: 
                   13479: Returns:
                   13480: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13481: 2. result of deletions ('ok' or 'error', with error message).
                   13482: 3. reference to hash of any new or updated access controls.
                   13483: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13484:    key = integer (inbound ID)
1.1172.2.13  raeburn  13485:    value = uniqueID
                   13486: 
                   13487: =item *
                   13488: 
                   13489: get_timebased_id():
                   13490: 
                   13491: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13492: course via the Course Editor (e.g., folders, composite pages,
                   13493: group bulletin boards).
                   13494: 
                   13495: Args: (first three required; six others optional)
                   13496: 
                   13497: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13498:    docssequence, or name of group
                   13499: 
                   13500: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13501:    e.g., num, boardids
                   13502: 
                   13503: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13504:    file will be named nohist_namespace.db
                   13505: 
                   13506: 4. cdom: domain of course; default is current course domain from %env
                   13507: 
                   13508: 5. cnum: course number; default is current course number from %env
                   13509: 
                   13510: 6. idtype: set to concat if an additional digit is to be appended to the
                   13511:    unix timestamp to form the suffix, if the plain timestamp is already
                   13512:    in use.  Default is to not do this, but simply increment the unix
                   13513:    timestamp by 1 until a unique key is obtained.
                   13514: 
                   13515: 7. who: holder of locking key; defaults to user:domain for user.
                   13516: 
                   13517: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13518:    retrying); default is 3.
                   13519: 
                   13520: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13521: 
                   13522: Returns:
                   13523: 
                   13524: 1. suffix obtained (numeric)
                   13525: 
                   13526: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13527: 
                   13528: 3. error: contains (localized) error message if an error occurred.
                   13529: 
1.747     albertel 13530: 
1.608     albertel 13531: =back
                   13532: 
1.243     albertel 13533: =head2 HTTP Helper Routines
                   13534: 
                   13535: =over 4
                   13536: 
1.191     harris41 13537: =item *
                   13538: 
                   13539: escape() : unpack non-word characters into CGI-compatible hex codes
                   13540: 
                   13541: =item *
                   13542: 
                   13543: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13544: 
1.243     albertel 13545: =back
                   13546: 
                   13547: =head1 PRIVATE SUBROUTINES
                   13548: 
                   13549: =head2 Underlying communication routines (Shouldn't call)
                   13550: 
                   13551: =over 4
                   13552: 
                   13553: =item *
                   13554: 
                   13555: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13556: 
                   13557: =item *
                   13558: 
                   13559: reply() : uses subreply to send a message to remote machine, logs all failures
                   13560: 
                   13561: =item *
                   13562: 
                   13563: critical() : passes a critical message to another server; if cannot
                   13564: get through then place message in connection buffer directory and
                   13565: returns con_delayed, if incapable of saving message, returns
                   13566: con_failed
                   13567: 
                   13568: =item *
                   13569: 
                   13570: reconlonc() : tries to reconnect lonc client processes.
                   13571: 
                   13572: =back
                   13573: 
                   13574: =head2 Resource Access Logging
                   13575: 
                   13576: =over 4
                   13577: 
                   13578: =item *
                   13579: 
                   13580: flushcourselogs() : flush (save) buffer logs and access logs
                   13581: 
                   13582: =item *
                   13583: 
                   13584: courselog($what) : save message for course in hash
                   13585: 
                   13586: =item *
                   13587: 
                   13588: courseacclog($what) : save message for course using &courselog().  Perform
                   13589: special processing for specific resource types (problems, exams, quizzes, etc).
                   13590: 
1.191     harris41 13591: =item *
                   13592: 
                   13593: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13594: as a PerlChildExitHandler
1.243     albertel 13595: 
                   13596: =back
                   13597: 
                   13598: =head2 Other
                   13599: 
                   13600: =over 4
                   13601: 
                   13602: =item *
                   13603: 
                   13604: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13605: 
                   13606: =back
                   13607: 
                   13608: =cut
1.877     foxr     13609: 

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