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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.100! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.99 2018/09/11 17:21:07 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.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
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.1172.2.79  raeburn    92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.1172.2.79  raeburn   105: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   145: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.1172.2.96  raeburn   157:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.1172.2.96  raeburn   170:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.1172.2.79  raeburn   391:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   439:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
1.1172.2.96  raeburn   479: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
1.1172.2.96  raeburn   488: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.96  raeburn   604:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.1172.2.96  raeburn   619:     if (!-e "$lonidsdir/$handle.id") {
                    620:         if ((ref($domref)) && ($name eq 'lonID') &&
                    621:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    622:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    623:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    624:                 $$domref = $possudom;
                    625:             }
                    626:         }
                    627:         return undef;
                    628:     }
1.916     albertel  629: 
1.917     albertel  630:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    631:     return undef if (!$opened);
1.916     albertel  632: 
                    633:     flock($idf,LOCK_SH);
                    634:     my %disk_env;
                    635:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    636: 	    &GDBM_READER(),0640)) {
                    637: 	return undef;	
                    638:     }
                    639: 
                    640:     if (!defined($disk_env{'user.name'})
                    641: 	|| !defined($disk_env{'user.domain'})) {
                    642: 	return undef;
                    643:     }
1.1172.2.18  raeburn   644: 
1.1172.2.36  raeburn   645:     if (ref($userhashref) eq 'HASH') {
                    646:         $userhashref->{'name'} = $disk_env{'user.name'};
                    647:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   648:     }
                    649: 
1.916     albertel  650:     return $handle;
                    651: }
                    652: 
1.830     albertel  653: sub timed_flock {
                    654:     my ($file,$lock_type) = @_;
                    655:     my $failed=0;
                    656:     eval {
                    657: 	local $SIG{__DIE__}='DEFAULT';
                    658: 	local $SIG{ALRM}=sub {
                    659: 	    $failed=1;
                    660: 	    die("failed lock");
                    661: 	};
                    662: 	alarm(13);
                    663: 	flock($file,$lock_type);
                    664: 	alarm(0);
                    665:     };
                    666:     if ($failed) {
                    667: 	return undef;
                    668:     } else {
                    669: 	return 1;
                    670:     }
                    671: }
                    672: 
1.5       www       673: # ---------------------------------------------------------- Append Environment
                    674: 
                    675: sub appenv {
1.949     raeburn   676:     my ($newenv,$roles) = @_;
                    677:     if (ref($newenv) eq 'HASH') {
                    678:         foreach my $key (keys(%{$newenv})) {
                    679:             my $refused = 0;
                    680: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    681:                 $refused = 1;
                    682:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   683:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   684:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    685:                         $refused = 0;
                    686:                     }
                    687:                 }
                    688:             }
                    689:             if ($refused) {
                    690:                 &logthis("<font color=\"blue\">WARNING: ".
                    691:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    692:                          .'</font>');
                    693: 	        delete($newenv->{$key});
                    694:             } else {
                    695:                 $env{$key}=$newenv->{$key};
                    696:             }
                    697:         }
1.1172.2.96  raeburn   698:         my $lonids = $perlvar{'lonIDsDir'};
                    699:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    700:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:             if ($opened
                    702: 	        && &timed_flock($env_file,LOCK_EX)
                    703: 	        &&
                    704: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    706: 	        while (my ($key,$value) = each(%{$newenv})) {
                    707: 	            $disk_env{$key} = $value;
                    708: 	        }
                    709: 	        untie(%disk_env);
                    710:             }
1.35      www       711:         }
1.191     harris41  712:     }
1.56      www       713:     return 'ok';
                    714: }
                    715: # ----------------------------------------------------- Delete from Environment
                    716: 
                    717: sub delenv {
1.1104    raeburn   718:     my ($delthis,$regexp,$roles) = @_;
                    719:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    720:         my $refused = 1;
                    721:         if (ref($roles) eq 'ARRAY') {
                    722:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    723:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    724:                 $refused = 0;
                    725:             }
                    726:         }
                    727:         if ($refused) {
                    728:             &logthis("<font color=\"blue\">WARNING: ".
                    729:                      "Attempt to delete from environment ".$delthis);
                    730:             return 'error';
                    731:         }
1.56      www       732:     }
1.917     albertel  733:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    734:     if ($opened
1.915     albertel  735: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  736: 	&&
                    737: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    738: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  739: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   740: 	    if ($regexp) {
                    741:                 if ($key=~/^$delthis/) {
                    742:                     delete($env{$key});
                    743:                     delete($disk_env{$key});
                    744:                 } 
                    745:             } else {
                    746:                 if ($key=~/^\Q$delthis\E/) {
                    747: 		    delete($env{$key});
                    748: 		    delete($disk_env{$key});
                    749: 	        }
                    750:             }
1.448     albertel  751: 	}
1.783     albertel  752: 	untie(%disk_env);
1.5       www       753:     }
                    754:     return 'ok';
1.369     albertel  755: }
                    756: 
1.790     albertel  757: sub get_env_multiple {
                    758:     my ($name) = @_;
                    759:     my @values;
                    760:     if (defined($env{$name})) {
                    761:         # exists is it an array
                    762:         if (ref($env{$name})) {
                    763:             @values=@{ $env{$name} };
                    764:         } else {
                    765:             $values[0]=$env{$name};
                    766:         }
                    767:     }
                    768:     return(@values);
                    769: }
                    770: 
1.958     www       771: # ------------------------------------------------------------------- Locking
                    772: 
                    773: sub set_lock {
                    774:     my ($text)=@_;
                    775:     $locknum++;
                    776:     my $id=$$.'-'.$locknum;
                    777:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    778:              'session.lock.'.$id => $text});
                    779:     return $id;
                    780: }
                    781: 
                    782: sub get_locks {
                    783:     my $num=0;
                    784:     my %texts=();
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if ($lock=~/\w/) {
                    787:           $num++;
                    788:           $texts{$lock}=$env{'session.lock.'.$lock};
                    789:        }
                    790:    }
                    791:    return ($num,%texts);
                    792: }
                    793: 
                    794: sub remove_lock {
                    795:     my ($id)=@_;
                    796:     my $newlocks='';
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if (($lock=~/\w/) && ($lock ne $id)) {
                    799:           $newlocks.=','.$lock;
                    800:        }
                    801:     }
                    802:     &appenv({'session.locks' => $newlocks});
                    803:     &delenv('session.lock.'.$id);
                    804: }
                    805: 
                    806: sub remove_all_locks {
                    807:     my $activelocks=$env{'session.locks'};
                    808:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    809:        if ($lock=~/\w/) {
                    810:           &remove_lock($lock);
                    811:        }
                    812:     }
                    813: }
                    814: 
                    815: 
1.369     albertel  816: # ------------------------------------------ Find out current server userload
                    817: sub userload {
                    818:     my $numusers=0;
                    819:     {
                    820: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    821: 	my $filename;
                    822: 	my $curtime=time;
                    823: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  824: 	    next if ($filename eq '.' || $filename eq '..');
                    825: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  826: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  827: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  828: 	}
                    829: 	closedir(LONIDS);
                    830:     }
                    831:     my $userloadpercent=0;
                    832:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    833:     if ($maxuserload) {
1.371     albertel  834: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  835:     }
1.372     albertel  836:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  837:     return $userloadpercent;
1.283     www       838: }
                    839: 
1.1       albertel  840: # ------------------------------ Find server with least workload from spare.tab
1.11      www       841: 
1.1       albertel  842: sub spareserver {
1.1083    raeburn   843:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  844:     my $spare_server;
1.370     albertel  845:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  846:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    847:                                                      :  $userloadpercent;
1.1083    raeburn   848:     my ($uint_dom,$remotesessions);
                    849:     if (($udom ne '') && (&domain($udom) ne '')) {
                    850:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    851:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    852:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    853:         $remotesessions = $udomdefaults{'remotesessions'};
                    854:     }
1.1123    raeburn   855:     my $spareshash = &this_host_spares($udom);
                    856:     if (ref($spareshash) eq 'HASH') {
                    857:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    858:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   859:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    860:                                              $try_server));
1.1123    raeburn   861: 	        ($spare_server, $lowest_load) =
                    862: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:             }
1.1083    raeburn   864:         }
1.784     albertel  865: 
1.1123    raeburn   866:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    867: 
                    868:         if (!$found_server) {
                    869:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    870: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   871:                     next unless (&spare_can_host($udom,$uint_dom,
                    872:                                                  $remotesessions,$try_server));
1.1123    raeburn   873: 	            ($spare_server, $lowest_load) =
                    874: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    875:                 }
                    876: 	    }
                    877:         }
1.784     albertel  878:     }
                    879: 
                    880:     if (!$want_server_name) {
1.968     raeburn   881:         my $protocol = 'http';
                    882:         if ($protocol{$spare_server} eq 'https') {
                    883:             $protocol = $protocol{$spare_server};
                    884:         }
1.1001    raeburn   885:         if (defined($spare_server)) {
                    886:             my $hostname = &hostname($spare_server);
1.1083    raeburn   887:             if (defined($hostname)) {
1.1001    raeburn   888: 	        $spare_server = $protocol.'://'.$hostname;
                    889:             }
                    890:         }
1.784     albertel  891:     }
                    892:     return $spare_server;
                    893: }
                    894: 
                    895: sub compare_server_load {
1.1172.2.41  raeburn   896:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    897: 
                    898:     if ($required) {
                    899:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    900:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    901:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    902:         if (($major eq '' && $minor eq '') ||
                    903:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    904:             return ($spare_server,$lowest_load);
                    905:         }
                    906:     }
1.784     albertel  907: 
                    908:     my $loadans     = &reply('load',    $try_server);
                    909:     my $userloadans = &reply('userload',$try_server);
                    910: 
                    911:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   912: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  913:     }
                    914: 
                    915:     my $load;
                    916:     if ($loadans =~ /\d/) {
                    917: 	if ($userloadans =~ /\d/) {
                    918: 	    #both are numbers, pick the bigger one
                    919: 	    $load = ($loadans > $userloadans) ? $loadans 
                    920: 		                              : $userloadans;
1.411     albertel  921: 	} else {
1.784     albertel  922: 	    $load = $loadans;
1.411     albertel  923: 	}
1.784     albertel  924:     } else {
                    925: 	$load = $userloadans;
                    926:     }
                    927: 
                    928:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    929: 	$spare_server = $try_server;
                    930: 	$lowest_load  = $load;
1.370     albertel  931:     }
1.784     albertel  932:     return ($spare_server,$lowest_load);
1.202     matthew   933: }
1.914     albertel  934: 
                    935: # --------------------------- ask offload servers if user already has a session
                    936: sub find_existing_session {
                    937:     my ($udom,$uname) = @_;
1.1123    raeburn   938:     my $spareshash = &this_host_spares($udom);
                    939:     if (ref($spareshash) eq 'HASH') {
                    940:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    941:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    942:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    943:             }
                    944:         }
                    945:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    946:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    947:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    948:             }
                    949:         }
1.914     albertel  950:     }
                    951:     return;
                    952: }
                    953: 
                    954: # -------------------------------- ask if server already has a session for user
                    955: sub has_user_session {
                    956:     my ($lonid,$udom,$uname) = @_;
                    957:     my $result = &reply(join(':','userhassession',
                    958: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    959:     return 1 if ($result eq 'ok');
                    960: 
                    961:     return 0;
                    962: }
                    963: 
1.1076    raeburn   964: # --------- determine least loaded server in a user's domain which allows login
                    965: 
                    966: sub choose_server {
1.1172.2.47  raeburn   967:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   968:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   969:     my %servers = &get_servers($udom);
1.1076    raeburn   970:     my $lowest_load = 30000;
1.1172.2.47  raeburn   971:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    972:     if ($skiploadbal) {
                    973:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    974:         unless (defined($cached)) {
                    975:             my $cachetime = 60*60*24;
                    976:             my %domconfig =
                    977:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    978:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    979:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    980:                                            $cachetime);
                    981:             }
                    982:         }
                    983:     }
1.1076    raeburn   984:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   985:         my $loginvia;
1.1172.2.47  raeburn   986:         if ($skiploadbal) {
                    987:             if (ref($balancers) eq 'HASH') {
                    988:                 next if (exists($balancers->{$lonhost}));
                    989:             }
                    990:         }
1.1115    raeburn   991:         if ($checkloginvia) {
                    992:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   993:             if ($loginvia) {
                    994:                 my ($server,$path) = split(/:/,$loginvia);
                    995:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   996:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $server) {
                    998:                     $portal_path = $path;
1.1151    raeburn   999:                     $isredirect = 1;
1.1116    raeburn  1000:                 }
                   1001:             } else {
                   1002:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1004:                 if ($login_host eq $lonhost) {
                   1005:                     $portal_path = '';
1.1151    raeburn  1006:                     $isredirect = ''; 
1.1116    raeburn  1007:                 }
                   1008:             }
                   1009:         } else {
1.1076    raeburn  1010:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1011:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1012:         }
                   1013:     }
                   1014:     if ($login_host ne '') {
1.1116    raeburn  1015:         $hostname = &hostname($login_host);
1.1076    raeburn  1016:     }
1.1172.2.88  raeburn  1017:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1018: }
                   1019: 
1.202     matthew  1020: # --------------------------------------------- Try to change a user's password
                   1021: 
                   1022: sub changepass {
1.799     raeburn  1023:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1024:     $currentpass = &escape($currentpass);
                   1025:     $newpass     = &escape($newpass);
1.1030    raeburn  1026:     my $lonhost = $perlvar{'lonHostID'};
                   1027:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1028: 		       $server);
                   1029:     if (! $answer) {
                   1030: 	&logthis("No reply on password change request to $server ".
                   1031: 		 "by $uname in domain $udom.");
                   1032:     } elsif ($answer =~ "^ok") {
                   1033:         &logthis("$uname in $udom successfully changed their password ".
                   1034: 		 "on $server.");
                   1035:     } elsif ($answer =~ "^pwchange_failure") {
                   1036: 	&logthis("$uname in $udom was unable to change their password ".
                   1037: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1038: 		 "or pwchange");
                   1039:     } elsif ($answer =~ "^non_authorized") {
                   1040:         &logthis("$uname in $udom did not get their password correct when ".
                   1041: 		 "attempting to change it on $server.");
                   1042:     } elsif ($answer =~ "^auth_mode_error") {
                   1043:         &logthis("$uname in $udom attempted to change their password despite ".
                   1044: 		 "not being locally or internally authenticated on $server.");
                   1045:     } elsif ($answer =~ "^unknown_user") {
                   1046:         &logthis("$uname in $udom attempted to change their password ".
                   1047: 		 "on $server but were unable to because $server is not ".
                   1048: 		 "their home server.");
                   1049:     } elsif ($answer =~ "^refused") {
                   1050: 	&logthis("$server refused to change $uname in $udom password because ".
                   1051: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1052:     } elsif ($answer =~ "invalid_client") {
                   1053:         &logthis("$server refused to change $uname in $udom password because ".
                   1054:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1055:     }
                   1056:     return $answer;
1.1       albertel 1057: }
                   1058: 
1.169     harris41 1059: # ----------------------- Try to determine user's current authentication scheme
                   1060: 
                   1061: sub queryauthenticate {
                   1062:     my ($uname,$udom)=@_;
1.456     albertel 1063:     my $uhome=&homeserver($uname,$udom);
                   1064:     if (!$uhome) {
                   1065: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1066: 	return 'no_host';
                   1067:     }
                   1068:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1069:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1070: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1071:     }
1.456     albertel 1072:     return $answer;
1.169     harris41 1073: }
                   1074: 
1.1       albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1076: 
1.1       albertel 1077: sub authenticate {
1.1073    raeburn  1078:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1079:     $upass=&escape($upass);
                   1080:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1081:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1082:     my $newhome;
1.836     www      1083:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1084: # Maybe the machine was offline and only re-appeared again recently?
                   1085:         &reconlonc();
                   1086: # One more
1.952     raeburn  1087: 	$uhome=&homeserver($uname,$udom,1);
                   1088:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1089:             if (defined(&domain($udom,'primary'))) {
                   1090:                 $newhome=&domain($udom,'primary');
                   1091:             }
                   1092:             if ($newhome ne '') {
                   1093:                 $uhome = $newhome;
                   1094:             }
                   1095:         }
1.836     www      1096: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1097: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1098: 	    return 'no_host';
                   1099:         }
1.1       albertel 1100:     }
1.1073    raeburn  1101:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1102:     if ($answer eq 'authorized') {
1.952     raeburn  1103:         if ($newhome) {
                   1104:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1105:             return 'no_account_on_host'; 
                   1106:         } else {
                   1107:             &logthis("User $uname at $udom authorized by $uhome");
                   1108:             return $uhome;
                   1109:         }
1.471     albertel 1110:     }
                   1111:     if ($answer eq 'non_authorized') {
                   1112: 	&logthis("User $uname at $udom rejected by $uhome");
                   1113: 	return 'no_host'; 
1.9       www      1114:     }
1.471     albertel 1115:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1116:     return 'no_host';
                   1117: }
                   1118: 
1.1073    raeburn  1119: sub can_host_session {
1.1074    raeburn  1120:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1121:     my $canhost = 1;
1.1074    raeburn  1122:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1123:     if (ref($remotesessions) eq 'HASH') {
                   1124:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 0;
                   1127:             } else {
                   1128:                 $canhost = 1;
                   1129:             }
                   1130:         }
                   1131:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1132:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1133:                 $canhost = 1;
                   1134:             } else {
                   1135:                 $canhost = 0;
                   1136:             }
                   1137:         }
                   1138:         if ($canhost) {
                   1139:             if ($remotesessions->{'version'} ne '') {
                   1140:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1141:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1142:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1143:                         my $major = $1;
                   1144:                         my $minor = $2;
                   1145:                         if (($major < $reqmajor ) ||
                   1146:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1147:                             $canhost = 0;
                   1148:                         }
                   1149:                     } else {
                   1150:                         $canhost = 0;
                   1151:                     }
                   1152:                 }
                   1153:             }
                   1154:         }
                   1155:     }
                   1156:     if ($canhost) {
                   1157:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1158:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1159:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1160:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 0;
                   1164:                 } else {
                   1165:                     $canhost = 1;
                   1166:                 }
                   1167:             }
                   1168:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1169:                 if (($uint_dom ne '') && 
                   1170:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1171:                     $canhost = 1;
                   1172:                 } else {
                   1173:                     $canhost = 0;
                   1174:                 }
                   1175:             }
                   1176:         }
                   1177:     }
                   1178:     return $canhost;
                   1179: }
                   1180: 
1.1083    raeburn  1181: sub spare_can_host {
                   1182:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1183:     my $canhost=1;
1.1172.2.62  raeburn  1184:     my $try_server_hostname = &hostname($try_server);
                   1185:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1186:     my $serverhomedom = &host_domain($serverhomeID);
                   1187:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1188:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1189:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1190:             $canhost = 0;
                   1191:         }
                   1192:     }
                   1193:     if (($canhost) && ($uint_dom)) {
                   1194:         my @intdoms;
                   1195:         my $internet_names = &get_internet_names($try_server);
                   1196:         if (ref($internet_names) eq 'ARRAY') {
                   1197:             @intdoms = @{$internet_names};
                   1198:         }
                   1199:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1200:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1201:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1202:                                          $remotesessions,
                   1203:                                          $defdomdefaults{'hostedsessions'});
                   1204:         }
1.1083    raeburn  1205:     }
                   1206:     return $canhost;
                   1207: }
                   1208: 
1.1123    raeburn  1209: sub this_host_spares {
                   1210:     my ($dom) = @_;
1.1126    raeburn  1211:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1212:     my @hosts = &current_machine_ids();
                   1213:     foreach my $lonhost (@hosts) {
                   1214:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1215:             $dom_in_use = $dom;
                   1216:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1217:             last;
                   1218:         }
                   1219:     }
1.1126    raeburn  1220:     if ($dom_in_use ne '') {
                   1221:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1222:     }
                   1223:     if (ref($result) ne 'HASH') {
                   1224:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1225:         $dom_in_use = &host_domain($lonhost_in_use);
                   1226:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1227:         if (ref($result) ne 'HASH') {
                   1228:             $result = \%spareid;
                   1229:         }
                   1230:     }
                   1231:     return $result;
                   1232: }
                   1233: 
                   1234: sub spares_for_offload  {
                   1235:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1236:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1237:     if (defined($cached)) {
                   1238:         return $result;
                   1239:     } else {
1.1126    raeburn  1240:         my $cachetime = 60*60*24;
                   1241:         my %domconfig =
                   1242:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1243:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1244:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1245:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1246:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1247:                 }
                   1248:             }
                   1249:         }
                   1250:     }
1.1126    raeburn  1251:     return;
1.1123    raeburn  1252: }
                   1253: 
1.1129    raeburn  1254: sub get_lonbalancer_config {
                   1255:     my ($servers) = @_;
                   1256:     my ($currbalancer,$currtargets);
                   1257:     if (ref($servers) eq 'HASH') {
                   1258:         foreach my $server (keys(%{$servers})) {
                   1259:             my %what = (
                   1260:                          spareid => 1,
                   1261:                          perlvar => 1,
                   1262:                        );
                   1263:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1264:             if ($result eq 'ok') {
                   1265:                 if (ref($returnhash) eq 'HASH') {
                   1266:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1267:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1268:                             $currbalancer = $server;
                   1269:                             $currtargets = {};
                   1270:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1271:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1272:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1273:                                 }
                   1274:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1275:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1276:                                 }
                   1277:                             }
                   1278:                             last;
                   1279:                         }
                   1280:                     }
                   1281:                 }
                   1282:             }
                   1283:         }
                   1284:     }
                   1285:     return ($currbalancer,$currtargets);
                   1286: }
                   1287: 
                   1288: sub check_loadbalancing {
1.1172.2.88  raeburn  1289:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1290:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1291:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1292:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1293:     my @hosts = &current_machine_ids();
1.1129    raeburn  1294:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1295:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1296:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1297:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1298:     my $domneedscache; 
1.1129    raeburn  1299:     my $cachetime = 60*60*24;
                   1300: 
                   1301:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1302:         $dom_in_use = $udom;
                   1303:         $homeintdom = 1;
                   1304:     } else {
                   1305:         $dom_in_use = $serverhomedom;
                   1306:     }
                   1307:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1308:     unless (defined($cached)) {
                   1309:         my %domconfig =
                   1310:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1311:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1312:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1313:         } else {
                   1314:             $domneedscache = $dom_in_use;
1.1129    raeburn  1315:         }
                   1316:     }
                   1317:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1318:         ($is_balancer,$currtargets,$currrules) =
                   1319:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1320:         if ($is_balancer) {
                   1321:             if (ref($currrules) eq 'HASH') {
                   1322:                 if ($homeintdom) {
                   1323:                     if ($uname ne '') {
                   1324:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1325:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1326:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1327:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1328:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1329:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1330:                             }
                   1331:                         }
                   1332:                         if ($rule_in_effect eq '') {
                   1333:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1334:                             if ($userenv{'inststatus'} ne '') {
                   1335:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1336:                                 my ($othertitle,$usertypes,$types) =
                   1337:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1338:                                 if (ref($types) eq 'ARRAY') {
                   1339:                                     foreach my $type (@{$types}) {
                   1340:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1341:                                             if (exists($currrules->{$type})) {
                   1342:                                                 $rule_in_effect = $currrules->{$type};
                   1343:                                             }
                   1344:                                         }
                   1345:                                     }
                   1346:                                 }
                   1347:                             } else {
                   1348:                                 if (exists($currrules->{'default'})) {
                   1349:                                     $rule_in_effect = $currrules->{'default'};
                   1350:                                 }
                   1351:                             }
                   1352:                         }
                   1353:                     } else {
                   1354:                         if (exists($currrules->{'default'})) {
                   1355:                             $rule_in_effect = $currrules->{'default'};
                   1356:                         }
                   1357:                     }
                   1358:                 } else {
                   1359:                     if ($currrules->{'_LC_external'} ne '') {
                   1360:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1361:                     }
                   1362:                 }
                   1363:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1364:                                                        $uname,$udom);
                   1365:             }
                   1366:         }
                   1367:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1368:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1369:         unless (defined($cached)) {
                   1370:             my %domconfig =
                   1371:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1372:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1373:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1374:             } else {
                   1375:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1376:             }
                   1377:         }
                   1378:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1379:             ($is_balancer,$currtargets,$currrules) =
                   1380:                 &check_balancer_result($result,@hosts);
                   1381:             if ($is_balancer) {
1.1129    raeburn  1382:                 if (ref($currrules) eq 'HASH') {
                   1383:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1384:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1385:                     }
                   1386:                 }
                   1387:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1388:                                                        $uname,$udom);
                   1389:             }
                   1390:         } else {
                   1391:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1392:                 $is_balancer = 1;
                   1393:                 $offloadto = &this_host_spares($dom_in_use);
                   1394:             }
1.1172.2.75  raeburn  1395:             unless (defined($cached)) {
                   1396:                 $domneedscache = $serverhomedom;
                   1397:             }
1.1129    raeburn  1398:         }
                   1399:     } else {
                   1400:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1401:             $is_balancer = 1;
                   1402:             $offloadto = &this_host_spares($dom_in_use);
                   1403:         }
1.1172.2.75  raeburn  1404:         unless (defined($cached)) {
                   1405:             $domneedscache = $serverhomedom;
                   1406:         }
                   1407:     }
                   1408:     if ($domneedscache) {
                   1409:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1410:     }
1.1172.2.5  raeburn  1411:     if ($is_balancer) {
                   1412:         my $lowest_load = 30000;
                   1413:         if (ref($offloadto) eq 'HASH') {
                   1414:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1415:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1416:                     ($otherserver,$lowest_load) =
                   1417:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1418:                 }
1.1129    raeburn  1419:             }
1.1172.2.5  raeburn  1420:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1421: 
1.1172.2.5  raeburn  1422:             if (!$found_server) {
                   1423:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1424:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1425:                         ($otherserver,$lowest_load) =
                   1426:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1431:             if (@{$offloadto} == 1) {
                   1432:                 $otherserver = $offloadto->[0];
                   1433:             } elsif (@{$offloadto} > 1) {
                   1434:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1435:                     ($otherserver,$lowest_load) =
                   1436:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1437:                 }
                   1438:             }
                   1439:         }
1.1172.2.88  raeburn  1440:         unless ($caller eq 'login') {
                   1441:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1442:                 $is_balancer = 0;
                   1443:                 if ($uname ne '' && $udom ne '') {
                   1444:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1445: 
1.1172.2.88  raeburn  1446:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1447:                                  'user.loadbalcheck.time' => time});
                   1448:                     }
1.1172.2.5  raeburn  1449:                 }
1.1129    raeburn  1450:             }
                   1451:         }
                   1452:     }
                   1453:     return ($is_balancer,$otherserver);
                   1454: }
                   1455: 
1.1172.2.12  raeburn  1456: sub check_balancer_result {
                   1457:     my ($result,@hosts) = @_;
                   1458:     my ($is_balancer,$currtargets,$currrules);
                   1459:     if (ref($result) eq 'HASH') {
                   1460:         if ($result->{'lonhost'} ne '') {
                   1461:             my $currbalancer = $result->{'lonhost'};
                   1462:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1463:                 $is_balancer = 1;
                   1464:                 $currtargets = $result->{'targets'};
                   1465:                 $currrules = $result->{'rules'};
                   1466:             }
                   1467:         } else {
                   1468:             foreach my $key (keys(%{$result})) {
                   1469:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1470:                     (ref($result->{$key}) eq 'HASH')) {
                   1471:                     $is_balancer = 1;
                   1472:                     $currrules = $result->{$key}{'rules'};
                   1473:                     $currtargets = $result->{$key}{'targets'};
                   1474:                     last;
                   1475:                 }
                   1476:             }
                   1477:         }
                   1478:     }
                   1479:     return ($is_balancer,$currtargets,$currrules);
                   1480: }
                   1481: 
1.1129    raeburn  1482: sub get_loadbalancer_targets {
                   1483:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1484:     my $offloadto;
1.1172.2.4  raeburn  1485:     if ($rule_in_effect eq 'none') {
                   1486:         return [$perlvar{'lonHostID'}];
                   1487:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1488:         $offloadto = $currtargets;
                   1489:     } else {
                   1490:         if ($rule_in_effect eq 'homeserver') {
                   1491:             my $homeserver = &homeserver($uname,$udom);
                   1492:             if ($homeserver ne 'no_host') {
                   1493:                 $offloadto = [$homeserver];
                   1494:             }
                   1495:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1496:             my %domconfig =
                   1497:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1498:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1499:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1500:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1501:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1502:                     }
                   1503:                 }
                   1504:             } else {
1.1172.2.7  raeburn  1505:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1506:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1507:                 if (&hostname($remotebalancer) ne '') {
                   1508:                     $offloadto = [$remotebalancer];
                   1509:                 }
                   1510:             }
                   1511:         } elsif (&hostname($rule_in_effect) ne '') {
                   1512:             $offloadto = [$rule_in_effect];
                   1513:         }
                   1514:     }
                   1515:     return $offloadto;
                   1516: }
                   1517: 
1.1127    raeburn  1518: sub internet_dom_servers {
                   1519:     my ($dom) = @_;
                   1520:     my (%uniqservers,%servers);
                   1521:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1522:     my @machinedoms = &machine_domains($primaryserver);
                   1523:     foreach my $mdom (@machinedoms) {
                   1524:         my %currservers = %servers;
                   1525:         my %server = &get_servers($mdom);
                   1526:         %servers = (%currservers,%server);
                   1527:     }
                   1528:     my %by_hostname;
                   1529:     foreach my $id (keys(%servers)) {
                   1530:         push(@{$by_hostname{$servers{$id}}},$id);
                   1531:     }
                   1532:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1533:         if (@{$by_hostname{$hostname}} > 1) {
                   1534:             my $match = 0;
                   1535:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1536:                 if (&host_domain($id) eq $dom) {
                   1537:                     $uniqservers{$id} = $hostname;
                   1538:                     $match = 1;
                   1539:                 }
                   1540:             }
                   1541:             unless ($match) {
                   1542:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1543:             }
                   1544:         } else {
                   1545:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1546:         }
                   1547:     }
                   1548:     return %uniqservers;
                   1549: }
                   1550: 
1.1       albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1552: 
1.599     albertel 1553: my %homecache;
1.1       albertel 1554: sub homeserver {
1.230     stredwic 1555:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1556:     my $index="$uname:$udom";
1.426     albertel 1557: 
1.599     albertel 1558:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1559: 
                   1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1562:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1563: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1564: 
                   1565: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1566: 	if ($answer eq 'found') {
                   1567: 	    delete($badServerCache{$tryserver}); 
                   1568: 	    return $homecache{$index}=$tryserver;
                   1569: 	} elsif ($answer eq 'no_host') {
                   1570: 	    $badServerCache{$tryserver}=1;
                   1571: 	}
1.1       albertel 1572:     }    
                   1573:     return 'no_host';
1.70      www      1574: }
                   1575: 
                   1576: # ------------------------------------- Find the usernames behind a list of IDs
                   1577: 
                   1578: sub idget {
                   1579:     my ($udom,@ids)=@_;
                   1580:     my %returnhash=();
                   1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1585: 	$idlist=~tr/A-Z/a-z/; 
                   1586: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1587: 	my @answer=();
                   1588: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1589: 	    @answer=split(/\&/,$reply);
                   1590: 	}                    ;
                   1591: 	my $i;
                   1592: 	for ($i=0;$i<=$#ids;$i++) {
                   1593: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1594: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1595: 	    } 
                   1596: 	}
                   1597:     } 
1.70      www      1598:     return %returnhash;
                   1599: }
                   1600: 
                   1601: # ------------------------------------- Find the IDs behind a list of usernames
                   1602: 
                   1603: sub idrget {
                   1604:     my ($udom,@unames)=@_;
                   1605:     my %returnhash=();
1.800     albertel 1606:     foreach my $uname (@unames) {
                   1607:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1608:     }
1.70      www      1609:     return %returnhash;
                   1610: }
                   1611: 
                   1612: # ------------------------------- Store away a list of names and associated IDs
                   1613: 
                   1614: sub idput {
                   1615:     my ($udom,%ids)=@_;
                   1616:     my %servers=();
1.800     albertel 1617:     foreach my $uname (keys(%ids)) {
                   1618: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1619:         my $uhom=&homeserver($uname,$udom);
1.70      www      1620:         if ($uhom ne 'no_host') {
1.800     albertel 1621:             my $id=&escape($ids{$uname});
1.70      www      1622:             $id=~tr/A-Z/a-z/;
1.800     albertel 1623:             my $esc_unam=&escape($uname);
1.70      www      1624: 	    if ($servers{$uhom}) {
1.800     albertel 1625: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1626:             } else {
1.800     albertel 1627:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1628:             }
                   1629:         }
1.191     harris41 1630:     }
1.800     albertel 1631:     foreach my $server (keys(%servers)) {
                   1632:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1633:     }
1.344     www      1634: }
                   1635: 
1.1172.2.30  raeburn  1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1637: 
                   1638: sub iddel {
                   1639:     my ($udom,$idshashref,$uhome)=@_;
                   1640:     my %result=();
                   1641:     unless (ref($idshashref) eq 'HASH') {
                   1642:         return %result;
                   1643:     }
                   1644:     my %servers=();
                   1645:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1646:         my $uhom;
                   1647:         if ($uhome) {
                   1648:             $uhom = $uhome;
                   1649:         } else {
                   1650:             $uhom=&homeserver($uname,$udom);
                   1651:         }
                   1652:         if ($uhom ne 'no_host') {
                   1653:             if ($servers{$uhom}) {
                   1654:                 $servers{$uhom}.='&'.&escape($id);
                   1655:             } else {
                   1656:                 $servers{$uhom}=&escape($id);
                   1657:             }
                   1658:         }
                   1659:     }
                   1660:     foreach my $server (keys(%servers)) {
                   1661:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1662:     }
                   1663:     return %result;
                   1664: }
                   1665: 
1.1023    raeburn  1666: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1667: sub dump_dom {
1.1165    droeschl 1668:     my ($namespace, $udom, $regexp) = @_;
                   1669: 
                   1670:     $udom ||= $env{'user.domain'};
                   1671: 
                   1672:     return () unless $udom;
                   1673: 
                   1674:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1675: }
                   1676: 
1.1023    raeburn  1677: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1678: 
                   1679: sub get_dom {
1.860     raeburn  1680:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1681:     return if ($udom eq 'public');
1.806     raeburn  1682:     my $items='';
                   1683:     foreach my $item (@$storearr) {
                   1684:         $items.=&escape($item).'&';
                   1685:     }
                   1686:     $items=~s/\&$//;
1.860     raeburn  1687:     if (!$udom) {
                   1688:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1689:         return if ($udom eq 'public');
1.860     raeburn  1690:         if (defined(&domain($udom,'primary'))) {
                   1691:             $uhome=&domain($udom,'primary');
                   1692:         } else {
1.874     albertel 1693:             undef($uhome);
1.860     raeburn  1694:         }
                   1695:     } else {
                   1696:         if (!$uhome) {
                   1697:             if (defined(&domain($udom,'primary'))) {
                   1698:                 $uhome=&domain($udom,'primary');
                   1699:             }
                   1700:         }
                   1701:     }
                   1702:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1703:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1704:         my %returnhash;
1.875     albertel 1705:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1706:             return %returnhash;
                   1707:         }
1.806     raeburn  1708:         my @pairs=split(/\&/,$rep);
                   1709:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1710:             return @pairs;
                   1711:         }
                   1712:         my $i=0;
                   1713:         foreach my $item (@$storearr) {
                   1714:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1715:             $i++;
                   1716:         }
                   1717:         return %returnhash;
                   1718:     } else {
1.880     banghart 1719:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1720:     }
                   1721: }
                   1722: 
                   1723: # -------------------------------------------- put items in domain db files 
                   1724: 
                   1725: sub put_dom {
1.860     raeburn  1726:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1727:     if (!$udom) {
                   1728:         $udom=$env{'user.domain'};
                   1729:         if (defined(&domain($udom,'primary'))) {
                   1730:             $uhome=&domain($udom,'primary');
                   1731:         } else {
1.874     albertel 1732:             undef($uhome);
1.860     raeburn  1733:         }
                   1734:     } else {
                   1735:         if (!$uhome) {
                   1736:             if (defined(&domain($udom,'primary'))) {
                   1737:                 $uhome=&domain($udom,'primary');
                   1738:             }
                   1739:         }
                   1740:     } 
                   1741:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1742:         my $items='';
                   1743:         foreach my $item (keys(%$storehash)) {
                   1744:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1745:         }
                   1746:         $items=~s/\&$//;
                   1747:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1748:     } else {
1.860     raeburn  1749:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1750:     }
                   1751: }
                   1752: 
1.1023    raeburn  1753: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1754: sub newput_dom {
1.1023    raeburn  1755:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1756:     my $result;
                   1757:     if (!$udom) {
                   1758:         $udom=$env{'user.domain'};
                   1759:     }
1.1023    raeburn  1760:     if ($udom) {
                   1761:         my $uname = &get_domainconfiguser($udom);
                   1762:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1763:     }
                   1764:     return $result;
                   1765: }
                   1766: 
1.1023    raeburn  1767: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1768: sub del_dom {
1.1023    raeburn  1769:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1770:     if (ref($storearr) eq 'ARRAY') {
                   1771:         if (!$udom) {
                   1772:             $udom=$env{'user.domain'};
                   1773:         }
1.1023    raeburn  1774:         if ($udom) {
                   1775:             my $uname = &get_domainconfiguser($udom); 
                   1776:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1777:         }
                   1778:     }
                   1779: }
                   1780: 
1.1023    raeburn  1781: # ----------------------------------construct domainconfig user for a domain 
                   1782: sub get_domainconfiguser {
                   1783:     my ($udom) = @_;
                   1784:     return $udom.'-domainconfig';
                   1785: }
                   1786: 
1.837     raeburn  1787: sub retrieve_inst_usertypes {
                   1788:     my ($udom) = @_;
                   1789:     my (%returnhash,@order);
1.989     raeburn  1790:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1791:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1792:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1793:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1794:     } else {
                   1795:         if (defined(&domain($udom,'primary'))) {
                   1796:             my $uhome=&domain($udom,'primary');
                   1797:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1798:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1799:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1800:                 return (\%returnhash,\@order);
                   1801:             }
                   1802:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1803:             my @pairs=split(/\&/,$hashitems);
                   1804:             foreach my $item (@pairs) {
                   1805:                 my ($key,$value)=split(/=/,$item,2);
                   1806:                 $key = &unescape($key);
                   1807:                 next if ($key =~ /^error: 2 /);
                   1808:                 $returnhash{$key}=&thaw_unescape($value);
                   1809:             }
                   1810:             my @esc_order = split(/\&/,$orderitems);
                   1811:             foreach my $item (@esc_order) {
                   1812:                 push(@order,&unescape($item));
                   1813:             }
                   1814:         } else {
1.1172.2.44  raeburn  1815:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1816:         }
1.1172.2.44  raeburn  1817:         return (\%returnhash,\@order);
1.837     raeburn  1818:     }
                   1819: }
                   1820: 
1.868     raeburn  1821: sub is_domainimage {
                   1822:     my ($url) = @_;
1.1172.2.74  raeburn  1823:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1824:         if (&domain($1) ne '') {
                   1825:             return '1';
                   1826:         }
                   1827:     }
                   1828:     return;
                   1829: }
                   1830: 
1.899     raeburn  1831: sub inst_directory_query {
                   1832:     my ($srch) = @_;
                   1833:     my $udom = $srch->{'srchdomain'};
                   1834:     my %results;
                   1835:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1836:     my $outcome;
1.899     raeburn  1837:     if ($homeserver ne '') {
1.904     albertel 1838: 	my $queryid=&reply("querysend:instdirsearch:".
                   1839: 			   &escape($srch->{'srchby'}).':'.
                   1840: 			   &escape($srch->{'srchterm'}).':'.
                   1841: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1842: 	my $host=&hostname($homeserver);
                   1843: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1844: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1845: 	    return;
                   1846: 	}
                   1847: 	my $response = &get_query_reply($queryid);
                   1848: 	my $maxtries = 5;
                   1849: 	my $tries = 1;
                   1850: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1851: 	    $response = &get_query_reply($queryid);
                   1852: 	    $tries ++;
                   1853: 	}
                   1854: 
                   1855:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  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).':'.$udom} = &thaw_unescape($value);
                   1864:                 }
1.899     raeburn  1865:             }
                   1866:         }
                   1867:     }
1.909     raeburn  1868:     return ($outcome,%results);
1.899     raeburn  1869: }
                   1870: 
                   1871: sub usersearch {
                   1872:     my ($srch) = @_;
                   1873:     my $dom = $srch->{'srchdomain'};
                   1874:     my %results;
                   1875:     my %libserv = &all_library();
                   1876:     my $query = 'usersearch';
                   1877:     foreach my $tryserver (keys(%libserv)) {
                   1878:         if (&host_domain($tryserver) eq $dom) {
                   1879:             my $host=&hostname($tryserver);
                   1880:             my $queryid=
1.911     raeburn  1881:                 &reply("querysend:".&escape($query).':'.
                   1882:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1883:                        &escape($srch->{'srchtype'}).':'.
                   1884:                        &escape($srch->{'srchterm'}),$tryserver);
                   1885:             if ($queryid !~/^\Q$host\E\_/) {
                   1886:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1887:                 next;
1.899     raeburn  1888:             }
                   1889:             my $reply = &get_query_reply($queryid);
                   1890:             my $maxtries = 1;
                   1891:             my $tries = 1;
                   1892:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1893:                 $reply = &get_query_reply($queryid);
                   1894:                 $tries ++;
                   1895:             }
                   1896:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1897:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1898:             } else {
1.911     raeburn  1899:                 my @matches;
                   1900:                 if ($reply =~ /\n/) {
                   1901:                     @matches = split(/\n/,$reply);
                   1902:                 } else {
                   1903:                     @matches = split(/\&/,$reply);
                   1904:                 }
1.899     raeburn  1905:                 foreach my $match (@matches) {
                   1906:                     my ($uname,$udom,%userhash);
1.911     raeburn  1907:                     foreach my $entry (split(/:/,$match)) {
                   1908:                         my ($key,$value) =
                   1909:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1910:                         $userhash{$key} = $value;
                   1911:                         if ($key eq 'username') {
                   1912:                             $uname = $value;
                   1913:                         } elsif ($key eq 'domain') {
                   1914:                             $udom = $value;
1.911     raeburn  1915:                         }
1.899     raeburn  1916:                     }
                   1917:                     $results{$uname.':'.$udom} = \%userhash;
                   1918:                 }
                   1919:             }
                   1920:         }
                   1921:     }
                   1922:     return %results;
                   1923: }
                   1924: 
1.912     raeburn  1925: sub get_instuser {
                   1926:     my ($udom,$uname,$id) = @_;
                   1927:     my $homeserver = &domain($udom,'primary');
                   1928:     my ($outcome,%results);
                   1929:     if ($homeserver ne '') {
                   1930:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1931:                            &escape($id).':'.&escape($udom),$homeserver);
                   1932:         my $host=&hostname($homeserver);
                   1933:         if ($queryid !~/^\Q$host\E\_/) {
                   1934:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1935:             return;
                   1936:         }
                   1937:         my $response = &get_query_reply($queryid);
                   1938:         my $maxtries = 5;
                   1939:         my $tries = 1;
                   1940:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1941:             $response = &get_query_reply($queryid);
                   1942:             $tries ++;
                   1943:         }
                   1944:         if (!&error($response) && $response ne 'refused') {
                   1945:             if ($response eq 'unavailable') {
                   1946:                 $outcome = $response;
                   1947:             } else {
                   1948:                 $outcome = 'ok';
                   1949:                 my @matches = split(/\n/,$response);
                   1950:                 foreach my $match (@matches) {
                   1951:                     my ($key,$value) = split(/=/,$match);
                   1952:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1953:                 }
                   1954:             }
                   1955:         }
                   1956:     }
                   1957:     my %userinfo;
                   1958:     if (ref($results{$uname}) eq 'HASH') {
                   1959:         %userinfo = %{$results{$uname}};
                   1960:     } 
                   1961:     return ($outcome,%userinfo);
                   1962: }
                   1963: 
1.1172.2.69  raeburn  1964: sub get_multiple_instusers {
                   1965:     my ($udom,$users,$caller) = @_;
                   1966:     my ($outcome,$results);
                   1967:     if (ref($users) eq 'HASH') {
                   1968:         my $count = keys(%{$users});
                   1969:         my $requested = &freeze_escape($users);
                   1970:         my $homeserver = &domain($udom,'primary');
                   1971:         if ($homeserver ne '') {
                   1972:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1973:             my $host=&hostname($homeserver);
                   1974:             if ($queryid !~/^\Q$host\E\_/) {
                   1975:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1976:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1977:                 return ($outcome,$results);
                   1978:             }
                   1979:             my $response = &get_query_reply($queryid);
                   1980:             my $maxtries = 5;
                   1981:             if ($count > 100) {
                   1982:                 $maxtries = 1+int($count/20);
                   1983:             }
                   1984:             my $tries = 1;
                   1985:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1986:                 $response = &get_query_reply($queryid);
                   1987:                 $tries ++;
                   1988:             }
                   1989:             if ($response eq '') {
                   1990:                 $results = {};
                   1991:                 foreach my $key (keys(%{$users})) {
                   1992:                     my ($uname,$id);
                   1993:                     if ($caller eq 'id') {
                   1994:                         $id = $key;
                   1995:                     } else {
                   1996:                         $uname = $key;
                   1997:                     }
                   1998:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1999:                     $outcome = $resp;
                   2000:                     if ($resp eq 'ok') {
                   2001:                         %{$results} = (%{$results}, %info);
                   2002:                     } else {
                   2003:                         last;
                   2004:                     }
                   2005:                 }
                   2006:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2007:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2008:                     $outcome = $response;
                   2009:                 } else {
                   2010:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2011:                     if ($outcome eq 'ok') {
                   2012:                         $results = &thaw_unescape($userdata);
                   2013:                     }
                   2014:                 }
                   2015:             }
                   2016:         }
                   2017:     }
                   2018:     return ($outcome,$results);
                   2019: }
                   2020: 
1.912     raeburn  2021: sub inst_rulecheck {
1.923     raeburn  2022:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2023:     my %returnhash;
                   2024:     if ($udom ne '') {
                   2025:         if (ref($rules) eq 'ARRAY') {
                   2026:             @{$rules} = map {&escape($_);} (@{$rules});
                   2027:             my $rulestr = join(':',@{$rules});
                   2028:             my $homeserver=&domain($udom,'primary');
                   2029:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2030:                 my $response;
                   2031:                 if ($item eq 'username') {                
                   2032:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2033:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2034:                                               $homeserver));
1.923     raeburn  2035:                 } elsif ($item eq 'id') {
                   2036:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2037:                                               ':'.&escape($id).':'.$rulestr,
                   2038:                                               $homeserver));
1.945     raeburn  2039:                 } elsif ($item eq 'selfcreate') {
                   2040:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2041:                                                &escape($udom).':'.&escape($uname).
                   2042:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2043:                 }
1.912     raeburn  2044:                 if ($response ne 'refused') {
                   2045:                     my @pairs=split(/\&/,$response);
                   2046:                     foreach my $item (@pairs) {
                   2047:                         my ($key,$value)=split(/=/,$item,2);
                   2048:                         $key = &unescape($key);
                   2049:                         next if ($key =~ /^error: 2 /);
                   2050:                         $returnhash{$key}=&thaw_unescape($value);
                   2051:                     }
                   2052:                 }
                   2053:             }
                   2054:         }
                   2055:     }
                   2056:     return %returnhash;
                   2057: }
                   2058: 
                   2059: sub inst_userrules {
1.923     raeburn  2060:     my ($udom,$check) = @_;
1.912     raeburn  2061:     my (%ruleshash,@ruleorder);
                   2062:     if ($udom ne '') {
                   2063:         my $homeserver=&domain($udom,'primary');
                   2064:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2065:             my $response;
                   2066:             if ($check eq 'id') {
                   2067:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2068:                                  $homeserver);
1.943     raeburn  2069:             } elsif ($check eq 'email') {
                   2070:                 $response=&reply('instemailrules:'.&escape($udom),
                   2071:                                  $homeserver);
1.923     raeburn  2072:             } else {
                   2073:                 $response=&reply('instuserrules:'.&escape($udom),
                   2074:                                  $homeserver);
                   2075:             }
1.912     raeburn  2076:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2077:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2078:                 ($response ne 'no_such_host')) {
                   2079:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2080:                 my @pairs=split(/\&/,$hashitems);
                   2081:                 foreach my $item (@pairs) {
                   2082:                     my ($key,$value)=split(/=/,$item,2);
                   2083:                     $key = &unescape($key);
                   2084:                     next if ($key =~ /^error: 2 /);
                   2085:                     $ruleshash{$key}=&thaw_unescape($value);
                   2086:                 }
                   2087:                 my @esc_order = split(/\&/,$orderitems);
                   2088:                 foreach my $item (@esc_order) {
                   2089:                     push(@ruleorder,&unescape($item));
                   2090:                 }
                   2091:             }
                   2092:         }
                   2093:     }
                   2094:     return (\%ruleshash,\@ruleorder);
                   2095: }
                   2096: 
1.976     raeburn  2097: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2098: 
                   2099: sub get_domain_defaults {
1.1172.2.35  raeburn  2100:     my ($domain,$ignore_cache) = @_;
                   2101:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2102:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2103:     unless ($ignore_cache) {
                   2104:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2105:         if (defined($cached)) {
                   2106:             if (ref($result) eq 'HASH') {
                   2107:                 return %{$result};
                   2108:             }
1.943     raeburn  2109:         }
                   2110:     }
                   2111:     my %domdefaults;
                   2112:     my %domconfig =
1.989     raeburn  2113:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2114:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2115:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2116:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2117:                                   'coursecategories','autoenroll',
                   2118:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2119:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2120:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2121:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2122:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2123:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2124:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2125:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2126:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2127:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2128:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2129:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2130:     } else {
                   2131:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2132:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2133:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2134:     }
1.976     raeburn  2135:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2136:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2137:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2138:         } else {
                   2139:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2140:         }
1.1172.2.6  raeburn  2141:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2142:         foreach my $item (@usertools) {
                   2143:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2144:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2145:             }
                   2146:         }
1.1172.2.29  raeburn  2147:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2148:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2149:         }
1.976     raeburn  2150:     }
1.985     raeburn  2151:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2152:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2153:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2154:         }
                   2155:     }
1.1172.2.9  raeburn  2156:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2157:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2158:     }
1.989     raeburn  2159:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2160:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2161:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2162:         }
                   2163:     }
1.1047    raeburn  2164:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2165:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2166:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2167:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2168:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2169:         }
1.1172.2.41  raeburn  2170:         foreach my $type (@coursetypes) {
                   2171:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2172:                 unless ($type eq 'community') {
                   2173:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2174:                 }
                   2175:             }
                   2176:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2177:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2178:             }
1.1172.2.60  raeburn  2179:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2180:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2181:                     $domdefaults{$type.'postsubtimeout'} =
                   2182:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2183:                 }
                   2184:             }
1.1172.2.30  raeburn  2185:         }
1.1172.2.67  raeburn  2186:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2187:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2188:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2189:                 if (@clonecodes) {
                   2190:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2191:                 }
                   2192:             }
                   2193:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2194:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2195:         }
1.1047    raeburn  2196:     }
1.1073    raeburn  2197:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2198:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2199:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2200:         }
                   2201:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2202:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2203:         }
1.1172.2.62  raeburn  2204:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2205:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2206:         }
1.1073    raeburn  2207:     }
1.1172.2.41  raeburn  2208:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2209:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2210:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2211:                             'approval','limit');
                   2212:             foreach my $type (@coursetypes) {
                   2213:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2214:                     my @mgrdc = ();
                   2215:                     foreach my $item (@settings) {
                   2216:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2217:                             push(@mgrdc,$item);
                   2218:                         }
                   2219:                     }
                   2220:                     if (@mgrdc) {
                   2221:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2222:                     }
                   2223:                 }
                   2224:             }
                   2225:         }
                   2226:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2227:             foreach my $type (@coursetypes) {
                   2228:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2229:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2230:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2231:                     }
                   2232:                 }
                   2233:             }
                   2234:         }
                   2235:     }
1.1172.2.46  raeburn  2236:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2237:         $domdefaults{'catauth'} = 'std';
                   2238:         $domdefaults{'catunauth'} = 'std';
                   2239:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2240:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2241:         }
                   2242:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2243:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2244:         }
                   2245:     }
1.1172.2.76  raeburn  2246:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2247:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2248:     }
1.1172.2.89  raeburn  2249:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2250:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2251:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2252:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2253:         }
                   2254:     }
1.1172.2.23  raeburn  2255:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2256:     return %domdefaults;
                   2257: }
                   2258: 
1.344     www      2259: # --------------------------------------------------- Assign a key to a student
                   2260: 
                   2261: sub assign_access_key {
1.364     www      2262: #
                   2263: # a valid key looks like uname:udom#comments
                   2264: # comments are being appended
                   2265: #
1.498     www      2266:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2267:     $kdom=
1.620     albertel 2268:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2269:     $knum=
1.620     albertel 2270:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2271:     $cdom=
1.620     albertel 2272:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2273:     $cnum=
1.620     albertel 2274:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2275:     $udom=$env{'user.name'} unless (defined($udom));
                   2276:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2277:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2278:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2279:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2280:                                                   # assigned to this person
                   2281:                                                   # - this should not happen,
1.345     www      2282:                                                   # unless something went wrong
                   2283:                                                   # the first time around
                   2284: # ready to assign
1.364     www      2285:         $logentry=$1.'; '.$logentry;
1.496     www      2286:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2287:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2288: # key now belongs to user
1.346     www      2289: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2290:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2291:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2292:                 return 'ok';
                   2293:             } else {
                   2294:                 return 
                   2295:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2296: 	    }
                   2297:         } else {
                   2298:             return 'error: Could not assign key, try again later.';
                   2299:         }
1.364     www      2300:     } elsif (!$existing{$ckey}) {
1.345     www      2301: # the key does not exist
                   2302: 	return 'error: The key does not exist';
                   2303:     } else {
                   2304: # the key is somebody else's
                   2305: 	return 'error: The key is already in use';
                   2306:     }
1.344     www      2307: }
                   2308: 
1.364     www      2309: # ------------------------------------------ put an additional comment on a key
                   2310: 
                   2311: sub comment_access_key {
                   2312: #
                   2313: # a valid key looks like uname:udom#comments
                   2314: # comments are being appended
                   2315: #
                   2316:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2317:     $cdom=
1.620     albertel 2318:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2319:     $cnum=
1.620     albertel 2320:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2321:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2322:     if ($existing{$ckey}) {
                   2323:         $existing{$ckey}.='; '.$logentry;
                   2324: # ready to assign
1.367     www      2325:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2326:                                                  $cdom,$cnum) eq 'ok') {
                   2327: 	    return 'ok';
                   2328:         } else {
                   2329: 	    return 'error: Count not store comment.';
                   2330:         }
                   2331:     } else {
                   2332: # the key does not exist
                   2333: 	return 'error: The key does not exist';
                   2334:     }
                   2335: }
                   2336: 
1.344     www      2337: # ------------------------------------------------------ Generate a set of keys
                   2338: 
                   2339: sub generate_access_keys {
1.364     www      2340:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2341:     $cdom=
1.620     albertel 2342:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2343:     $cnum=
1.620     albertel 2344:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2345:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2346:     unless (($cdom) && ($cnum)) { return 0; }
                   2347:     if ($number>10000) { return 0; }
                   2348:     sleep(2); # make sure don't get same seed twice
                   2349:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2350:     my $total=0;
                   2351:     for (my $i=1;$i<=$number;$i++) {
                   2352:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2353:                   sprintf("%lx",int(100000*rand)).'-'.
                   2354:                   sprintf("%lx",int(100000*rand));
                   2355:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2356:        $newkey=~s/0/h/g; # and also 0 and O
                   2357:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2358:        if ($existing{$newkey}) {
                   2359:            $i--;
                   2360:        } else {
1.364     www      2361: 	  if (&put('accesskeys',
                   2362:               { $newkey => '# generated '.localtime().
1.620     albertel 2363:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2364:                            '; '.$logentry },
                   2365: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2366:               $total++;
                   2367: 	  }
                   2368:        }
                   2369:     }
1.620     albertel 2370:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2371:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2372:     return $total;
                   2373: }
                   2374: 
                   2375: # ------------------------------------------------------- Validate an accesskey
                   2376: 
                   2377: sub validate_access_key {
                   2378:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2379:     $cdom=
1.620     albertel 2380:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2381:     $cnum=
1.620     albertel 2382:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2383:     $udom=$env{'user.domain'} unless (defined($udom));
                   2384:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2385:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2386:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2387: }
                   2388: 
                   2389: # ------------------------------------- Find the section of student in a course
1.652     albertel 2390: sub devalidate_getsection_cache {
                   2391:     my ($udom,$unam,$courseid)=@_;
                   2392:     my $hashid="$udom:$unam:$courseid";
                   2393:     &devalidate_cache_new('getsection',$hashid);
                   2394: }
1.298     matthew  2395: 
1.815     albertel 2396: sub courseid_to_courseurl {
                   2397:     my ($courseid) = @_;
                   2398:     #already url style courseid
                   2399:     return $courseid if ($courseid =~ m{^/});
                   2400: 
                   2401:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2402: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2403: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2404: 	return "/$cdom/$cnum";
                   2405:     }
                   2406: 
                   2407:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2408:     if (exists($courseinfo{'num'})) {
                   2409: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2410:     }
                   2411: 
                   2412:     return undef;
                   2413: }
                   2414: 
1.298     matthew  2415: sub getsection {
                   2416:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2417:     my $cachetime=1800;
1.551     albertel 2418: 
                   2419:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2420:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2421:     if (defined($cached)) { return $result; }
                   2422: 
1.298     matthew  2423:     my %Pending; 
                   2424:     my %Expired;
                   2425:     #
                   2426:     # Each role can either have not started yet (pending), be active, 
                   2427:     #    or have expired.
                   2428:     #
                   2429:     # If there is an active role, we are done.
                   2430:     #
                   2431:     # If there is more than one role which has not started yet, 
                   2432:     #     choose the one which will start sooner
                   2433:     # If there is one role which has not started yet, return it.
                   2434:     #
                   2435:     # If there is more than one expired role, choose the one which ended last.
                   2436:     # If there is a role which has expired, return it.
                   2437:     #
1.815     albertel 2438:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2439:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2440:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2441:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2442:         my $section=$1;
                   2443:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2444:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2445:         my $now=time;
1.548     albertel 2446:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2447:             $Expired{$end}=$section;
                   2448:             next;
                   2449:         }
1.548     albertel 2450:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2451:             $Pending{$start}=$section;
                   2452:             next;
                   2453:         }
1.599     albertel 2454:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2455:     }
                   2456:     #
                   2457:     # Presumedly there will be few matching roles from the above
                   2458:     # loop and the sorting time will be negligible.
                   2459:     if (scalar(keys(%Pending))) {
                   2460:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2461:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2462:     } 
                   2463:     if (scalar(keys(%Expired))) {
                   2464:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2465:         my $time = pop(@sorted);
1.599     albertel 2466:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2467:     }
1.599     albertel 2468:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2469: }
1.70      www      2470: 
1.599     albertel 2471: sub save_cache {
                   2472:     &purge_remembered();
1.722     albertel 2473:     #&Apache::loncommon::validate_page();
1.620     albertel 2474:     undef(%env);
1.780     albertel 2475:     undef($env_loaded);
1.599     albertel 2476: }
1.452     albertel 2477: 
1.599     albertel 2478: my $to_remember=-1;
                   2479: my %remembered;
                   2480: my %accessed;
                   2481: my $kicks=0;
                   2482: my $hits=0;
1.849     albertel 2483: sub make_key {
                   2484:     my ($name,$id) = @_;
1.872     albertel 2485:     if (length($id) > 65 
                   2486: 	&& length(&escape($id)) > 200) {
                   2487: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2488:     }
1.849     albertel 2489:     return &escape($name.':'.$id);
                   2490: }
                   2491: 
1.599     albertel 2492: sub devalidate_cache_new {
                   2493:     my ($name,$id,$debug) = @_;
                   2494:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2495:     my $remembered_id=$name.':'.$id;
1.849     albertel 2496:     $id=&make_key($name,$id);
1.599     albertel 2497:     $memcache->delete($id);
1.1172.2.81  raeburn  2498:     delete($remembered{$remembered_id});
                   2499:     delete($accessed{$remembered_id});
1.599     albertel 2500: }
                   2501: 
                   2502: sub is_cached_new {
                   2503:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2504:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2505:                                      # keys in %remembered hash, which persists for
                   2506:                                      # duration of request (no restriction on key length).
                   2507:     if (exists($remembered{$remembered_id})) {
                   2508: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2509: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2510: 	$hits++;
1.1172.2.81  raeburn  2511: 	return ($remembered{$remembered_id},1);
1.599     albertel 2512:     }
1.1172.2.81  raeburn  2513:     $id=&make_key($name,$id);
1.599     albertel 2514:     my $value = $memcache->get($id);
                   2515:     if (!(defined($value))) {
                   2516: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2517: 	return (undef,undef);
1.416     albertel 2518:     }
1.599     albertel 2519:     if ($value eq '__undef__') {
                   2520: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2521: 	$value=undef;
                   2522:     }
1.1172.2.81  raeburn  2523:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2524:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2525:     return ($value,1);
                   2526: }
                   2527: 
                   2528: sub do_cache_new {
                   2529:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2530:     my $remembered_id=$name.':'.$id;
1.849     albertel 2531:     $id=&make_key($name,$id);
1.599     albertel 2532:     my $setvalue=$value;
                   2533:     if (!defined($setvalue)) {
                   2534: 	$setvalue='__undef__';
                   2535:     }
1.623     albertel 2536:     if (!defined($time) ) {
                   2537: 	$time=600;
                   2538:     }
1.599     albertel 2539:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2540:     my $result = $memcache->set($id,$setvalue,$time);
                   2541:     if (! $result) {
1.872     albertel 2542: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2543: 	$memcache->disconnect_all();
1.872     albertel 2544:     }
1.600     albertel 2545:     # need to make a copy of $value
1.1172.2.81  raeburn  2546:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2547:     return $value;
                   2548: }
                   2549: 
                   2550: sub make_room {
1.1172.2.81  raeburn  2551:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2552: 
1.1172.2.81  raeburn  2553:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2554:                                     : $value;
1.599     albertel 2555:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2556:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2557:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2558:     my $to_kick;
                   2559:     my $max_time=0;
                   2560:     foreach my $other (keys(%accessed)) {
                   2561: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2562: 	    $to_kick=$other;
                   2563: 	    $max_time=&tv_interval($accessed{$other});
                   2564: 	}
                   2565:     }
                   2566:     delete($remembered{$to_kick});
                   2567:     delete($accessed{$to_kick});
                   2568:     $kicks++;
                   2569:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2570:     return;
                   2571: }
                   2572: 
1.599     albertel 2573: sub purge_remembered {
1.604     albertel 2574:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2575:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2576:     undef(%remembered);
                   2577:     undef(%accessed);
1.428     albertel 2578: }
1.70      www      2579: # ------------------------------------- Read an entry from a user's environment
                   2580: 
                   2581: sub userenvironment {
                   2582:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2583:     my $items;
                   2584:     foreach my $item (@what) {
                   2585:         $items.=&escape($item).'&';
                   2586:     }
                   2587:     $items=~s/\&$//;
1.70      www      2588:     my %returnhash=();
1.1009    raeburn  2589:     my $uhome = &homeserver($unam,$udom);
                   2590:     unless ($uhome eq 'no_host') {
                   2591:         my @answer=split(/\&/, 
                   2592:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2593:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2594:             return %returnhash;
                   2595:         }
1.1009    raeburn  2596:         my $i;
                   2597:         for ($i=0;$i<=$#what;$i++) {
                   2598: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2599:         }
1.70      www      2600:     }
                   2601:     return %returnhash;
1.1       albertel 2602: }
                   2603: 
1.617     albertel 2604: # ---------------------------------------------------------- Get a studentphoto
                   2605: sub studentphoto {
                   2606:     my ($udom,$unam,$ext) = @_;
                   2607:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2608:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2609:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2610:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2611:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2612:             } else {
                   2613:                 my ($result,$perm_reqd)=
1.707     albertel 2614: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2615:                 if ($result eq 'ok') {
                   2616:                     if (!($perm_reqd eq 'yes')) {
                   2617:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2618:                     }
                   2619:                 }
                   2620:             }
                   2621:         }
                   2622:     } else {
                   2623:         my ($result,$perm_reqd) = 
1.707     albertel 2624: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2625:         if ($result eq 'ok') {
                   2626:             if (!($perm_reqd eq 'yes')) {
                   2627:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2628:             }
                   2629:         }
                   2630:     }
                   2631:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2632: }
                   2633: 
                   2634: sub retrievestudentphoto {
                   2635:     my ($udom,$unam,$ext,$type) = @_;
                   2636:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2637:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2638:     if ($ret eq 'ok') {
                   2639:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2640:         if ($type eq 'thumbnail') {
                   2641:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2642:         }
                   2643:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2644:         return $tokenurl;
                   2645:     } else {
                   2646:         if ($type eq 'thumbnail') {
                   2647:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2648:         } else { 
                   2649:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2650:         }
1.617     albertel 2651:     }
                   2652: }
                   2653: 
1.263     www      2654: # -------------------------------------------------------------------- New chat
                   2655: 
                   2656: sub chatsend {
1.724     raeburn  2657:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2658:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2659:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2660:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2661:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2662: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2663: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2664: }
                   2665: 
                   2666: # ------------------------------------------ Find current version of a resource
                   2667: 
                   2668: sub getversion {
                   2669:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2670:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2671:     return &currentversion(&filelocation('',$fname));
                   2672: }
                   2673: 
                   2674: sub currentversion {
                   2675:     my $fname=shift;
                   2676:     my $author=$fname;
                   2677:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2678:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2679:     my $home=&homeserver($uname,$udom);
1.292     www      2680:     if ($home eq 'no_host') { 
                   2681:         return -1; 
                   2682:     }
1.1112    www      2683:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2684:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2685: 	return -1;
                   2686:     }
1.1112    www      2687:     return $answer;
1.263     www      2688: }
                   2689: 
1.1111    www      2690: #
                   2691: # Return special version number of resource if set by override, empty otherwise
                   2692: #
                   2693: sub usedversion {
                   2694:     my $fname=shift;
                   2695:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2696:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2697:     if ($urlversion) { return $urlversion; }
                   2698:     return '';
                   2699: }
                   2700: 
1.1       albertel 2701: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2702: 
1.1       albertel 2703: sub subscribe {
                   2704:     my $fname=shift;
1.761     raeburn  2705:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2706:     $fname=~s/[\n\r]//g;
1.1       albertel 2707:     my $author=$fname;
                   2708:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2709:     my ($udom,$uname)=split(/\//,$author);
                   2710:     my $home=homeserver($uname,$udom);
1.335     albertel 2711:     if ($home eq 'no_host') {
                   2712:         return 'not_found';
1.1       albertel 2713:     }
                   2714:     my $answer=reply("sub:$fname",$home);
1.64      www      2715:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2716: 	$answer.=' by '.$home;
                   2717:     }
1.1       albertel 2718:     return $answer;
                   2719: }
                   2720:     
1.8       www      2721: # -------------------------------------------------------------- Replicate file
                   2722: 
                   2723: sub repcopy {
                   2724:     my $filename=shift;
1.23      www      2725:     $filename=~s/\/+/\//g;
1.1142    raeburn  2726:     my $londocroot = $perlvar{'lonDocRoot'};
                   2727:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2728:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2729:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2730: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2731: 	return &repcopy_userfile($filename);
                   2732:     }
1.532     albertel 2733:     $filename=~s/[\n\r]//g;
1.8       www      2734:     my $transname="$filename.in.transfer";
1.828     www      2735: # FIXME: this should flock
1.607     raeburn  2736:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2737:     my $remoteurl=subscribe($filename);
1.64      www      2738:     if ($remoteurl =~ /^con_lost by/) {
                   2739: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2740:            return 'unavailable';
1.8       www      2741:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2742: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2743: 	   return 'not_found';
1.64      www      2744:     } elsif ($remoteurl =~ /^rejected by/) {
                   2745: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2746:            return 'forbidden';
1.20      www      2747:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2748:            return 'ok';
1.8       www      2749:     } else {
1.290     www      2750:         my $author=$filename;
                   2751:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2752:         my ($udom,$uname)=split(/\//,$author);
                   2753:         my $home=homeserver($uname,$udom);
                   2754:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2755:            my @parts=split(/\//,$filename);
                   2756:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2757:            if ($path ne "$londocroot/res") {
1.8       www      2758:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2759: 	       return 'bad_request';
1.8       www      2760:            }
                   2761:            my $count;
                   2762:            for ($count=5;$count<$#parts;$count++) {
                   2763:                $path.="/$parts[$count]";
                   2764:                if ((-e $path)!=1) {
                   2765: 		   mkdir($path,0777);
                   2766:                }
                   2767:            }
                   2768:            my $ua=new LWP::UserAgent;
                   2769:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2770:            my $response=$ua->request($request,$transname);
                   2771:            if ($response->is_error()) {
                   2772: 	       unlink($transname);
                   2773:                my $message=$response->status_line;
1.672     albertel 2774:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2775:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2776:                return 'unavailable';
1.8       www      2777:            } else {
1.16      www      2778: 	       if ($remoteurl!~/\.meta$/) {
                   2779:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2780:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2781:                   if ($mresponse->is_error()) {
                   2782: 		      unlink($filename.'.meta');
                   2783:                       &logthis(
1.672     albertel 2784:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2785:                   }
                   2786: 	       }
1.8       www      2787:                rename($transname,$filename);
1.607     raeburn  2788:                return 'ok';
1.8       www      2789:            }
1.290     www      2790:        }
1.8       www      2791:     }
1.330     www      2792: }
                   2793: 
                   2794: # ------------------------------------------------ Get server side include body
                   2795: sub ssi_body {
1.381     albertel 2796:     my ($filelink,%form)=@_;
1.606     matthew  2797:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2798:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2799:     }
1.953     www      2800:     my $output='';
                   2801:     my $response;
1.980     raeburn  2802:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2803:        ($output,$response)=&externalssi($filelink);
1.953     www      2804:     } else {
1.1004    droeschl 2805:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2806:        $filelink .= 'inhibitmenu=yes';
1.953     www      2807:        ($output,$response)=&ssi($filelink,%form);
                   2808:     }
1.778     albertel 2809:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2810:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2811:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2812:     if (wantarray) {
                   2813:         return ($output, $response);
                   2814:     } else {
                   2815:         return $output;
                   2816:     }
1.8       www      2817: }
                   2818: 
1.15      www      2819: # --------------------------------------------------------- Server Side Include
                   2820: 
1.782     albertel 2821: sub absolute_url {
                   2822:     my ($host_name) = @_;
                   2823:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2824:     if ($host_name eq '') {
                   2825: 	$host_name = $ENV{'SERVER_NAME'};
                   2826:     }
                   2827:     return $protocol.$host_name;
                   2828: }
                   2829: 
1.942     foxr     2830: #
                   2831: #   Server side include.
                   2832: # Parameters:
                   2833: #  fn     Possibly encrypted resource name/id.
                   2834: #  form   Hash that describes how the rendering should be done
                   2835: #         and other things.
1.944     foxr     2836: # Returns:
1.950     raeburn  2837: #   Scalar context: The content of the response.
                   2838: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2839: #     
1.15      www      2840: sub ssi {
                   2841: 
1.944     foxr     2842:     my ($fn,%form)=@_;
1.1172.2.100! raeburn  2843:     my ($request,$response);
1.711     albertel 2844: 
                   2845:     $form{'no_update_last_known'}=1;
1.895     albertel 2846:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2847:     if (%form) {
1.782     albertel 2848:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2849:       $request->content(join('&',map {
                   2850:             my $name = escape($_);
                   2851:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2852:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2853:             : &escape($form{$_}) );
                   2854:         } keys(%form)));
1.23      www      2855:     } else {
1.782     albertel 2856:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2857:     }
                   2858: 
1.15      www      2859:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100! raeburn  2860: 
        !          2861:     if ($islocal) {
        !          2862:         if (LWP::UserAgent->VERSION >= 5.834) {
        !          2863:             my $ua=new LWP::UserAgent;
        !          2864:             $ua->local_address('127.0.0.1');
        !          2865:             $response = $ua->request($request);
        !          2866:         } else {
        !          2867:             {
        !          2868:                 require LWP::Protocol::http;
        !          2869:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
        !          2870:                 my $ua=new LWP::UserAgent;
        !          2871:                 $response = $ua->request($request);
        !          2872:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
        !          2873:             }
        !          2874:         }
        !          2875:     } else {
        !          2876:         my $ua=new LWP::UserAgent;
        !          2877:         $response = $ua->request($request);
        !          2878:     }
1.944     foxr     2879:     if (wantarray) {
1.1172.2.3  raeburn  2880: 	return ($response->content, $response);
1.944     foxr     2881:     } else {
1.1172.2.3  raeburn  2882: 	return $response->content;
1.942     foxr     2883:     }
1.324     www      2884: }
                   2885: 
                   2886: sub externalssi {
                   2887:     my ($url)=@_;
                   2888:     my $ua=new LWP::UserAgent;
                   2889:     my $request=new HTTP::Request('GET',$url);
                   2890:     my $response=$ua->request($request);
1.954     raeburn  2891:     if (wantarray) {
                   2892:         return ($response->content, $response);
                   2893:     } else {
                   2894:         return $response->content;
                   2895:     }
1.15      www      2896: }
1.254     www      2897: 
1.1172.2.98  raeburn  2898: # If the local copy of a replicated resource is outdated, trigger a
                   2899: # connection from the homeserver to flush the delayed queue. If no update
                   2900: # happens, remove local copies of outdated resource (and corresponding
                   2901: # metadata file).
                   2902: 
                   2903: sub remove_stale_resfile {
                   2904:     my ($url) = @_;
                   2905:     my $removed;
                   2906:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   2907:         my $audom = $1;
                   2908:         my $auname = $2;
                   2909:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   2910:             my $homeserver = &homeserver($auname,$audom);
                   2911:             unless (($homeserver eq 'no_host') ||
                   2912:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   2913:                 my $fname = &filelocation('',$url);
                   2914:                 if (-e $fname) {
                   2915:                     my $ua=new LWP::UserAgent;
                   2916:                     $ua->timeout(5);
                   2917:                     my $protocol = $protocol{$homeserver};
                   2918:                     $protocol = 'http' if ($protocol ne 'https');
                   2919:                     my $hostname = &hostname($homeserver);
                   2920:                     if ($hostname) {
                   2921:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   2922:                         my $request=new HTTP::Request('HEAD',$uri);
                   2923:                         my $response=$ua->request($request);
                   2924:                         if ($response->is_success()) {
                   2925:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   2926:                             my $locmodtime = (stat($fname))[9];
                   2927:                             if ($locmodtime < $remmodtime) {
                   2928:                                 my $stale;
                   2929:                                 my $answer = &reply('pong',$homeserver);
                   2930:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   2931:                                     sleep(0.2);
                   2932:                                     $locmodtime = (stat($fname))[9];
                   2933:                                     if ($locmodtime < $remmodtime) {
                   2934:                                         my $posstransfer = $fname.'.in.transfer';
                   2935:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   2936:                                             $removed = 1;
                   2937:                                         } else {
                   2938:                                             $stale = 1;
                   2939:                                         }
                   2940:                                     } else {
                   2941:                                         $removed = 1;
                   2942:                                     }
                   2943:                                 } else {
                   2944:                                     $stale = 1;
                   2945:                                 }
                   2946:                                 if ($stale) {
                   2947:                                     unlink($fname);
                   2948:                                     if ($uri!~/\.meta$/) {
                   2949:                                         unlink($fname.'.meta');
                   2950:                                     }
                   2951:                                     &reply("unsub:$fname",$homeserver);
                   2952:                                     $removed = 1;
                   2953:                                 }
                   2954:                             }
                   2955:                         }
                   2956:                     }
                   2957:                 }
                   2958:             }
                   2959:         }
                   2960:     }
                   2961:     return $removed;
                   2962: }
                   2963: 
1.492     albertel 2964: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2965: 
                   2966: sub allowuploaded {
                   2967:     my ($srcurl,$url)=@_;
                   2968:     $url=&clutter(&declutter($url));
                   2969:     my $dir=$url;
                   2970:     $dir=~s/\/[^\/]+$//;
                   2971:     my %httpref=();
                   2972:     my $httpurl=&hreflocation('',$url);
                   2973:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2974:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2975: }
1.477     raeburn  2976: 
1.1172.2.13  raeburn  2977: #
                   2978: # Determine if the current user should be able to edit a particular resource,
                   2979: # when viewing in course context.
                   2980: # (a) When viewing resource used to determine if "Edit" item is included in
                   2981: #     Functions.
                   2982: # (b) When displaying folder contents in course editor, used to determine if
                   2983: #     "Edit" link will be displayed alongside resource.
                   2984: #
                   2985: #  input: six args -- filename (decluttered), course number, course domain,
                   2986: #                   url, symb (if registered) and group (if this is a group
                   2987: #                   item -- e.g., bulletin board, group page etc.).
                   2988: #  output: array of five scalars --
                   2989: #          $cfile -- url for file editing if editable on current server
                   2990: #          $home -- homeserver of resource (i.e., for author if published,
                   2991: #                                           or course if uploaded.).
                   2992: #          $switchserver --  1 if server switch will be needed.
                   2993: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2994: #          $forceview -- 1 if icon/link should be to go to view mode
                   2995: #
                   2996: 
                   2997: sub can_edit_resource {
                   2998:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2999:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3000: #
                   3001: # For aboutme pages user can only edit his/her own.
                   3002: #
                   3003:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3004:         my ($sdom,$sname) = ($1,$2);
                   3005:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3006:             $home = $env{'user.home'};
                   3007:             $cfile = $resurl;
                   3008:             if ($env{'form.forceedit'}) {
                   3009:                 $forceview = 1;
                   3010:             } else {
                   3011:                 $forceedit = 1;
                   3012:             }
                   3013:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3014:         } else {
                   3015:             return;
                   3016:         }
                   3017:     }
                   3018: 
                   3019:     if ($env{'request.course.id'}) {
                   3020:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3021:         if ($group ne '') {
                   3022: # if this is a group homepage or group bulletin board, check group privs
                   3023:             my $allowed = 0;
                   3024:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3025:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3026:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3027:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3028:                     $allowed = 1;
                   3029:                 }
                   3030:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3031:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3032:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3033:                     $allowed = 1;
                   3034:                 }
                   3035:             }
                   3036:             if ($allowed) {
                   3037:                 $home=&homeserver($cnum,$cdom);
                   3038:                 if ($env{'form.forceedit'}) {
                   3039:                     $forceview = 1;
                   3040:                 } else {
                   3041:                     $forceedit = 1;
                   3042:                 }
                   3043:                 $cfile = $resurl;
                   3044:             } else {
                   3045:                 return;
                   3046:             }
                   3047:         } else {
1.1172.2.15  raeburn  3048:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3049:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3050:                     return;
                   3051:                 }
                   3052:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3053: #
                   3054: # No edit allowed where CC has switched to student role.
                   3055: #
                   3056:                 return;
                   3057:             }
                   3058:         }
                   3059:     }
                   3060: 
                   3061:     if ($file ne '') {
                   3062:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3063:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3064:                 $uploaded = 1;
                   3065:                 $incourse = 1;
                   3066:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3067:                     $cfile = &hreflocation('',$file);
                   3068:                     if ($env{'form.forceedit'}) {
                   3069:                         $forceview = 1;
                   3070:                     } else {
                   3071:                         $forceedit = 1;
                   3072:                     }
                   3073:                 }
                   3074:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3075:                 $incourse = 1;
                   3076:                 if ($env{'form.forceedit'}) {
                   3077:                     $forceview = 1;
                   3078:                 } else {
                   3079:                     $forceedit = 1;
                   3080:                 }
                   3081:                 $cfile = $resurl;
                   3082:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3083:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3084:                     $incourse = 1;
                   3085:                     if ($env{'form.forceedit'}) {
                   3086:                         $forceview = 1;
                   3087:                     } else {
                   3088:                         $forceedit = 1;
                   3089:                     }
                   3090:                     $cfile = $resurl;
                   3091:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3092:                     $incourse = 1;
                   3093:                     $cfile = $resurl.'/smpedit';
                   3094:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3095:                     $incourse = 1;
                   3096:                     if ($env{'form.forceedit'}) {
                   3097:                         $forceview = 1;
                   3098:                     } else {
                   3099:                         $forceedit = 1;
                   3100:                     }
                   3101:                     $cfile = $resurl;
1.1172.2.15  raeburn  3102:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3103:                     $incourse = 1;
                   3104:                     if ($env{'form.forceedit'}) {
                   3105:                         $forceview = 1;
                   3106:                     } else {
                   3107:                         $forceedit = 1;
                   3108:                     }
                   3109:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3110:                 }
                   3111:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3112:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3113:                 if (&is_on_map($template)) {
                   3114:                     $incourse = 1;
                   3115:                     $forceview = 1;
                   3116:                     $cfile = $template;
                   3117:                 }
                   3118:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3119:                     $incourse = 1;
                   3120:                     if ($env{'form.forceedit'}) {
                   3121:                         $forceview = 1;
                   3122:                     } else {
                   3123:                         $forceedit = 1;
                   3124:                     }
                   3125:                     $cfile = $resurl;
                   3126:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3127:                 $incourse = 1;
                   3128:                 $forceview = 1;
                   3129:                 if ($symb) {
                   3130:                     my ($map,$id,$res)=&decode_symb($symb);
                   3131:                     $env{'request.symb'} = $symb;
                   3132:                     $cfile = &clutter($res);
                   3133:                 } else {
                   3134:                     $cfile = $env{'form.suppurl'};
                   3135:                     $cfile =~ s{^http://}{};
                   3136:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3137:                 }
1.1172.2.31  raeburn  3138:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3139:                 if ($env{'form.forceedit'}) {
                   3140:                     $forceview = 1;
                   3141:                 } else {
                   3142:                     $forceedit = 1;
                   3143:                 }
                   3144:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3145:             }
                   3146:         }
                   3147:         if ($uploaded || $incourse) {
                   3148:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3149:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3150:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3151:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3152:             # Check that the user has permission to edit this resource
                   3153:             my $setpriv = 1;
                   3154:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3155:             if (defined($cfudom)) {
                   3156:                 $home=&homeserver($cfuname,$cfudom);
                   3157:                 $cfile=$file;
                   3158:             }
                   3159:         }
                   3160:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3161:             (($home ne '') && ($home ne 'no_host'))) {
                   3162:             my @ids=&current_machine_ids();
                   3163:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3164:                 $switchserver=1;
                   3165:             }
                   3166:         }
                   3167:     }
                   3168:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3169: }
                   3170: 
                   3171: sub is_course_upload {
                   3172:     my ($file,$cnum,$cdom) = @_;
                   3173:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3174:     $uploadpath =~ s{^\/}{};
                   3175:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3176:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3177:         return 1;
                   3178:     }
                   3179:     return;
                   3180: }
                   3181: 
                   3182: sub in_course {
                   3183:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3184:     if ($hideprivileged) {
                   3185:         my $skipuser;
1.1172.2.23  raeburn  3186:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3187:         my @possdoms = ($cdom);
                   3188:         if ($coursehash{'checkforpriv'}) {
                   3189:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3190:         }
                   3191:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3192:             $skipuser = 1;
                   3193:             if ($coursehash{'nothideprivileged'}) {
                   3194:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3195:                     my $user;
                   3196:                     if ($item =~ /:/) {
                   3197:                         $user = $item;
                   3198:                     } else {
                   3199:                         $user = join(':',split(/[\@]/,$item));
                   3200:                     }
                   3201:                     if ($user eq $uname.':'.$udom) {
                   3202:                         undef($skipuser);
                   3203:                         last;
                   3204:                     }
                   3205:                 }
                   3206:             }
                   3207:             if ($skipuser) {
                   3208:                 return 0;
                   3209:             }
                   3210:         }
                   3211:     }
                   3212:     $type ||= 'any';
                   3213:     if (!defined($cdom) || !defined($cnum)) {
                   3214:         my $cid  = $env{'request.course.id'};
                   3215:         $cdom = $env{'course.'.$cid.'.domain'};
                   3216:         $cnum = $env{'course.'.$cid.'.num'};
                   3217:     }
                   3218:     my $typesref;
                   3219:     if (($type eq 'any') || ($type eq 'all')) {
                   3220:         $typesref = ['active','previous','future'];
                   3221:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3222:         $typesref = [$type];
                   3223:     }
                   3224:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3225:                               $typesref,undef,[$cdom]);
                   3226:     my ($tmp) = keys(%roles);
                   3227:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3228:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3229:     if (@course_roles > 0) {
                   3230:         return 1;
                   3231:     }
                   3232:     return 0;
                   3233: }
                   3234: 
1.478     albertel 3235: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3236: # input: action, courseID, current domain, intended
1.637     raeburn  3237: #        path to file, source of file, instruction to parse file for objects,
                   3238: #        ref to hash for embedded objects,
                   3239: #        ref to hash for codebase of java objects.
1.1095    raeburn  3240: #        reference to scalar to accommodate mime type determined
                   3241: #          from File::MMagic if $parser = parse.
1.637     raeburn  3242: #
1.485     raeburn  3243: # output: url to file (if action was uploaddoc), 
                   3244: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3245: #
1.478     albertel 3246: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3247: # course.
1.477     raeburn  3248: #
1.478     albertel 3249: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3250: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3251: #          course's home server.
1.477     raeburn  3252: #
1.478     albertel 3253: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3254: #          be copied from $source (current location) to 
                   3255: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3256: #         and will then be copied to
                   3257: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3258: #         course's home server.
1.485     raeburn  3259: #
1.481     raeburn  3260: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3261: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3262: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3263: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3264: #         in course's home server.
1.637     raeburn  3265: #
1.477     raeburn  3266: 
                   3267: sub process_coursefile {
1.1095    raeburn  3268:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3269:         $mimetype)=@_;
1.477     raeburn  3270:     my $fetchresult;
1.638     albertel 3271:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3272:     if ($action eq 'propagate') {
1.638     albertel 3273:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3274: 			     $home);
1.481     raeburn  3275:     } else {
1.477     raeburn  3276:         my $fpath = '';
                   3277:         my $fname = $file;
1.478     albertel 3278:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3279:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3280:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3281:         if ($action eq 'copy') {
                   3282:             if ($source eq '') {
                   3283:                 $fetchresult = 'no source file';
                   3284:                 return $fetchresult;
                   3285:             } else {
                   3286:                 my $destination = $filepath.'/'.$fname;
                   3287:                 rename($source,$destination);
                   3288:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3289:                                  $home);
1.481     raeburn  3290:             }
                   3291:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3292:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3293:             print $fh $env{'form.'.$source};
1.481     raeburn  3294:             close($fh);
1.637     raeburn  3295:             if ($parser eq 'parse') {
1.1024    raeburn  3296:                 my $mm = new File::MMagic;
1.1095    raeburn  3297:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3298:                 if ($type eq 'text/html') {
1.1024    raeburn  3299:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3300:                     unless ($parse_result eq 'ok') {
                   3301:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3302:                     }
1.637     raeburn  3303:                 }
1.1095    raeburn  3304:                 if (ref($mimetype)) {
                   3305:                     $$mimetype = $type;
                   3306:                 } 
1.637     raeburn  3307:             }
1.477     raeburn  3308:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3309:                                  $home);
1.481     raeburn  3310:             if ($fetchresult eq 'ok') {
                   3311:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3312:             } else {
                   3313:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3314:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3315:                 return '/adm/notfound.html';
                   3316:             }
1.477     raeburn  3317:         }
                   3318:     }
1.485     raeburn  3319:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3320:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3321:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3322:     }
                   3323:     return $fetchresult;
                   3324: }
                   3325: 
1.637     raeburn  3326: sub build_filepath {
                   3327:     my ($fpath) = @_;
                   3328:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3329:     unless ($fpath eq '') {
                   3330:         my @parts=split('/',$fpath);
                   3331:         foreach my $part (@parts) {
                   3332:             $filepath.= '/'.$part;
                   3333:             if ((-e $filepath)!=1) {
                   3334:                 mkdir($filepath,0777);
                   3335:             }
                   3336:         }
                   3337:     }
                   3338:     return $filepath;
                   3339: }
                   3340: 
                   3341: sub store_edited_file {
1.638     albertel 3342:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3343:     my $file = $primary_url;
                   3344:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3345:     my $fpath = '';
                   3346:     my $fname = $file;
                   3347:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3348:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3349:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3350:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3351:     print $fh $content;
                   3352:     close($fh);
1.638     albertel 3353:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3354:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3355: 			  $home);
1.637     raeburn  3356:     if ($$fetchresult eq 'ok') {
                   3357:         return '/uploaded/'.$fpath.'/'.$fname;
                   3358:     } else {
1.638     albertel 3359:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3360: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3361:         return '/adm/notfound.html';
                   3362:     }
                   3363: }
                   3364: 
1.531     albertel 3365: sub clean_filename {
1.831     albertel 3366:     my ($fname,$args)=@_;
1.315     www      3367: # Replace Windows backslashes by forward slashes
1.257     www      3368:     $fname=~s/\\/\//g;
1.831     albertel 3369:     if (!$args->{'keep_path'}) {
                   3370:         # Get rid of everything but the actual filename
                   3371: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3372:     }
1.315     www      3373: # Replace spaces by underscores
                   3374:     $fname=~s/\s+/\_/g;
                   3375: # Replace all other weird characters by nothing
1.831     albertel 3376:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3377: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3378: # numbers
                   3379:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3380:     return $fname;
                   3381: }
1.1051    raeburn  3382: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3383: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3384: # image with the same aspect ratio as the original, but with dimensions which do 
                   3385: # not exceed $resizewidth and $resizeheight.
                   3386:  
1.984     neumanie 3387: sub resizeImage {
1.1051    raeburn  3388:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3389:     my $ima = Image::Magick->new;
                   3390:     my $resized;
                   3391:     if (-e $img_path) {
                   3392:         $ima->Read($img_path);
                   3393:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3394:             my $width = $ima->Get('width');
                   3395:             my $height = $ima->Get('height');
                   3396:             if ($width > $resizewidth) {
                   3397: 	        my $factor = $width/$resizewidth;
                   3398:                 my $newheight = $height/$factor;
                   3399:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3400:                 $resized = 1;
                   3401:             }
                   3402:         }
                   3403:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3404:             my $width = $ima->Get('width');
                   3405:             my $height = $ima->Get('height');
                   3406:             if ($height > $resizeheight) {
                   3407:                 my $factor = $height/$resizeheight;
                   3408:                 my $newwidth = $width/$factor;
                   3409:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3410:                 $resized = 1;
                   3411:             }
                   3412:         }
                   3413:         if ($resized) {
                   3414:             $ima->Write($img_path);
                   3415:         }
                   3416:     }
                   3417:     return;
1.977     amueller 3418: }
                   3419: 
1.608     albertel 3420: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3421: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3422: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3423: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3424: #                                    canceloverwrite, or ''. 
                   3425: #                   if 'coursedoc': upload to the current course
                   3426: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3427: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3428: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3429: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3430: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3431: #        $allfiles - reference to hash for embedded objects
                   3432: #        $codebase - reference to hash for codebase of java objects
                   3433: #        $desuname - username for permanent storage of uploaded file
                   3434: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3435: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3436: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3437: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3438: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3439: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3440: #                    from File::MMagic.
1.858     raeburn  3441: # 
1.686     albertel 3442: # output: url of file in userspace, or error: <message> 
                   3443: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3444: 
1.531     albertel 3445: sub userfileupload {
1.1090    raeburn  3446:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3447:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3448:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3449:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3450:     $fname=&clean_filename($fname);
1.1090    raeburn  3451:     # See if there is anything left
1.257     www      3452:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3453:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3454:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3455:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3456:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3457:         my $now = time;
1.1090    raeburn  3458:         my $filepath;
1.1095    raeburn  3459:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3460:              $filepath = 'tmp/helprequests/'.$now;
                   3461:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3462:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3463:                          '_'.$env{'user.domain'}.'/pending';
                   3464:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3465:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3466:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3467:                 $docudom = $destudom;
                   3468:             } else {
                   3469:                 $docudom = $env{'user.domain'};
                   3470:             }
1.1172.2.96  raeburn  3471:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3472:                 $docuname = $destuname;
                   3473:             } else {
                   3474:                 $docuname = $env{'user.name'};
                   3475:             }
                   3476:             if (exists($env{'form.group'})) {
                   3477:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3478:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3479:             }
                   3480:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3481:             if ($context eq 'canceloverwrite') {
                   3482:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3483:                 if (-e  $tempfile) {
                   3484:                     my @info = stat($tempfile);
                   3485:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3486:                         unlink($tempfile);
                   3487:                     }
                   3488:                 }
                   3489:                 return;
1.523     raeburn  3490:             }
                   3491:         }
1.1090    raeburn  3492:         # Create the directory if not present
1.741     raeburn  3493:         my @parts=split(/\//,$filepath);
                   3494:         my $fullpath = $perlvar{'lonDaemons'};
                   3495:         for (my $i=0;$i<@parts;$i++) {
                   3496:             $fullpath .= '/'.$parts[$i];
                   3497:             if ((-e $fullpath)!=1) {
                   3498:                 mkdir($fullpath,0777);
                   3499:             }
                   3500:         }
1.1172.2.96  raeburn  3501:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3502:         print $fh $env{'form.'.$formname};
                   3503:         close($fh);
1.1090    raeburn  3504:         if ($context eq 'existingfile') {
                   3505:             my @info = stat($fullpath.'/'.$fname);
                   3506:             return ($fullpath.'/'.$fname,$info[9]);
                   3507:         } else {
                   3508:             return $fullpath.'/'.$fname;
                   3509:         }
1.523     raeburn  3510:     }
1.995     raeburn  3511:     if ($subdir eq 'scantron') {
                   3512:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3513:     } else {
1.995     raeburn  3514:         $fname="$subdir/$fname";
                   3515:     }
1.1090    raeburn  3516:     if ($context eq 'coursedoc') {
1.638     albertel 3517: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3518: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3519:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3520:             return &finishuserfileupload($docuname,$docudom,
                   3521: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3522: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3523:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3524:         } else {
1.1172.2.21  raeburn  3525:             if ($env{'form.folder'}) {
                   3526:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3527:             }
1.638     albertel 3528:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3529: 				       $fname,$formname,$parser,
1.1095    raeburn  3530: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3531:         }
1.719     banghart 3532:     } elsif (defined($destuname)) {
                   3533:         my $docuname=$destuname;
                   3534:         my $docudom=$destudom;
1.860     raeburn  3535: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3536: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3537:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3538:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3539:     } else {
1.638     albertel 3540:         my $docuname=$env{'user.name'};
                   3541:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3542:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3543:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3544:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3545:         }
1.860     raeburn  3546: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3547: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3548:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3549:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3550:     }
1.271     www      3551: }
                   3552: 
                   3553: sub finishuserfileupload {
1.860     raeburn  3554:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3555:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3556:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3557:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3558:   
1.860     raeburn  3559:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3560:     $file=$fname;
                   3561:     if ($fname=~m|/|) {
                   3562:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3563: 	$path.=$fnamepath.'/';
                   3564:     }
1.259     www      3565:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3566:     my $count;
                   3567:     for ($count=4;$count<=$#parts;$count++) {
                   3568:         $filepath.="/$parts[$count]";
                   3569:         if ((-e $filepath)!=1) {
                   3570: 	    mkdir($filepath,0777);
                   3571:         }
                   3572:     }
1.984     neumanie 3573: 
1.258     www      3574: # Save the file
                   3575:     {
1.1172.2.96  raeburn  3576: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3577: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3578: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3579: 	    return '/adm/notfound.html';
                   3580: 	}
1.1090    raeburn  3581:         if ($context eq 'overwrite') {
1.1117    foxr     3582:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3583:             my $target = $filepath.'/'.$file;
                   3584:             if (-e $source) {
                   3585:                 my @info = stat($source);
                   3586:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3587:                     unless (&File::Copy::move($source,$target)) {
                   3588:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3589:                         return "Moving from $source failed";
                   3590:                     }
                   3591:                 } else {
                   3592:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3593:                 }
                   3594:             } else {
                   3595:                 return "Temporary file: $source missing";
                   3596:             }
                   3597:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3598: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3599: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3600: 	    return '/adm/notfound.html';
                   3601: 	}
1.570     albertel 3602: 	close(FH);
1.1051    raeburn  3603:         if ($resizewidth && $resizeheight) {
                   3604:             my $mm = new File::MMagic;
                   3605:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3606:             if ($mime_type =~ m{^image/}) {
                   3607: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3608:             }  
1.977     amueller 3609: 	}
1.258     www      3610:     }
1.1152    raeburn  3611:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3612:         if (ref($mimetype)) {
                   3613:             if ($$mimetype eq '') {
                   3614:                 my $mm = new File::MMagic;
                   3615:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3616:                 $$mimetype = $type;
                   3617:             }
                   3618:         }
                   3619:     }
1.637     raeburn  3620:     if ($parser eq 'parse') {
1.1152    raeburn  3621:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3622:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3623:                                                        $allfiles,$codebase);
                   3624:             unless ($parse_result eq 'ok') {
                   3625:                 &logthis('Failed to parse '.$filepath.$file.
                   3626: 	   	         ' for embedded media: '.$parse_result); 
                   3627:             }
1.637     raeburn  3628:         }
                   3629:     }
1.860     raeburn  3630:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3631:         my $input = $filepath.'/'.$file;
                   3632:         my $output = $filepath.'/'.'tn-'.$file;
                   3633:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3634:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3635:         system({$args[0]} @args);
1.860     raeburn  3636:         if (-e $filepath.'/'.'tn-'.$file) {
                   3637:             $fetchthumb  = 1; 
                   3638:         }
                   3639:     }
1.858     raeburn  3640:  
1.259     www      3641: # Notify homeserver to grep it
                   3642: #
1.984     neumanie 3643:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3644:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3645:     if ($fetchresult eq 'ok') {
1.860     raeburn  3646:         if ($fetchthumb) {
                   3647:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3648:             if ($thumbresult ne 'ok') {
                   3649:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3650:                          $docuhome.': '.$thumbresult);
                   3651:             }
                   3652:         }
1.259     www      3653: #
1.258     www      3654: # Return the URL to it
1.494     albertel 3655:         return '/uploaded/'.$path.$file;
1.263     www      3656:     } else {
1.494     albertel 3657:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3658: 		 ': '.$fetchresult);
1.263     www      3659:         return '/adm/notfound.html';
1.858     raeburn  3660:     }
1.493     albertel 3661: }
                   3662: 
1.637     raeburn  3663: sub extract_embedded_items {
1.961     raeburn  3664:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3665:     my @state = ();
1.1164    raeburn  3666:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3667:     my %javafiles = (
                   3668:                       codebase => '',
                   3669:                       code => '',
                   3670:                       archive => ''
                   3671:                     );
                   3672:     my %mediafiles = (
                   3673:                       src => '',
                   3674:                       movie => '',
                   3675:                      );
1.648     raeburn  3676:     my $p;
                   3677:     if ($content) {
                   3678:         $p = HTML::LCParser->new($content);
                   3679:     } else {
1.961     raeburn  3680:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3681:     }
1.641     albertel 3682:     while (my $t=$p->get_token()) {
1.640     albertel 3683: 	if ($t->[0] eq 'S') {
                   3684: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3685: 	    push(@state, $tagname);
1.648     raeburn  3686:             if (lc($tagname) eq 'allow') {
                   3687:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3688:             }
1.640     albertel 3689: 	    if (lc($tagname) eq 'img') {
                   3690: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3691: 	    }
1.886     albertel 3692: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3693:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3694: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3695:                 }
1.886     albertel 3696: 	    }
1.645     raeburn  3697:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3698:                 my $src;
1.645     raeburn  3699:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3700:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3701:                 } else {
1.1164    raeburn  3702:                     if ($attr->{'src'} ne '') {
                   3703:                         $src = $attr->{'src'};
                   3704:                         &add_filetype($allfiles,$src,'src');
                   3705:                     }
                   3706:                 }
                   3707:                 my $text = $p->get_trimmed_text();
                   3708:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3709:                     my @swfargs = split(/,/,$1);
                   3710:                     foreach my $item (@swfargs) {
                   3711:                         $item =~ s/["']//g;
                   3712:                         $item =~ s/^\s+//;
                   3713:                         $item =~ s/\s+$//;
                   3714:                     }
                   3715:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3716:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3717:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3718:                         } else {
                   3719:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3720:                         }
                   3721:                     }
1.645     raeburn  3722:                 }
                   3723:             }
                   3724:             if (lc($tagname) eq 'link') {
                   3725:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3726:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3727:                 }
                   3728:             }
1.640     albertel 3729: 	    if (lc($tagname) eq 'object' ||
                   3730: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3731: 		foreach my $item (keys(%javafiles)) {
                   3732: 		    $javafiles{$item} = '';
                   3733: 		}
1.1164    raeburn  3734:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3735:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3736:                 }
1.640     albertel 3737: 	    }
                   3738: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3739: 		my $name = lc($attr->{'name'});
                   3740: 		foreach my $item (keys(%javafiles)) {
                   3741: 		    if ($name eq $item) {
                   3742: 			$javafiles{$item} = $attr->{'value'};
                   3743: 			last;
                   3744: 		    }
                   3745: 		}
1.1164    raeburn  3746:                 my $pathfrom;
1.640     albertel 3747: 		foreach my $item (keys(%mediafiles)) {
                   3748: 		    if ($name eq $item) {
1.1164    raeburn  3749:                         $pathfrom = $attr->{'value'};
                   3750:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3751: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3752: 			last;
                   3753: 		    }
                   3754: 		}
1.1164    raeburn  3755:                 if ($name eq 'flashvars') {
                   3756:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3757:                 }
                   3758:                 if ($pathfrom ne '') {
                   3759:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3760:                                          $pathfrom);
                   3761:                 }
1.640     albertel 3762: 	    }
                   3763: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3764: 		foreach my $item (keys(%javafiles)) {
                   3765: 		    if ($attr->{$item}) {
                   3766: 			$javafiles{$item} = $attr->{$item};
                   3767: 			last;
                   3768: 		    }
                   3769: 		}
                   3770: 		foreach my $item (keys(%mediafiles)) {
                   3771: 		    if ($attr->{$item}) {
                   3772: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3773: 			last;
                   3774: 		    }
                   3775: 		}
1.1164    raeburn  3776:                 if (lc($tagname) eq 'embed') {
                   3777:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3778:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3779:                                              $attr->{'src'});
                   3780:                     }
                   3781:                 }
1.640     albertel 3782: 	    }
1.1172.2.35  raeburn  3783:             if (lc($tagname) eq 'iframe') {
                   3784:                 my $src = $attr->{'src'} ;
                   3785:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3786:                     &add_filetype($allfiles,$src,'src');
                   3787:                 } elsif ($src =~ m{^/}) {
                   3788:                     if ($env{'request.course.id'}) {
                   3789:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3790:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3791:                         my $url = &hreflocation('',$fullpath);
                   3792:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3793:                             my $relpath = $1;
                   3794:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3795:                                 &add_filetype($allfiles,$1,'src');
                   3796:                             }
                   3797:                         }
                   3798:                     }
                   3799:                 }
                   3800:             }
1.1164    raeburn  3801:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3802:                 pop(@state);
1.1164    raeburn  3803:             }
1.640     albertel 3804: 	} elsif ($t->[0] eq 'E') {
                   3805: 	    my ($tagname) = ($t->[1]);
                   3806: 	    if ($javafiles{'codebase'} ne '') {
                   3807: 		$javafiles{'codebase'} .= '/';
                   3808: 	    }  
                   3809: 	    if (lc($tagname) eq 'applet' ||
                   3810: 		lc($tagname) eq 'object' ||
                   3811: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3812: 		) {
                   3813: 		foreach my $item (keys(%javafiles)) {
                   3814: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3815: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3816: 			&add_filetype($allfiles,$file,$item);
                   3817: 		    }
                   3818: 		}
                   3819: 	    } 
                   3820: 	    pop @state;
                   3821: 	}
                   3822:     }
1.1164    raeburn  3823:     foreach my $id (sort(keys(%flashvars))) {
                   3824:         if ($shockwave{$id} ne '') {
                   3825:             my @pairs = split(/\&/,$flashvars{$id});
                   3826:             foreach my $pair (@pairs) {
                   3827:                 my ($key,$value) = split(/\=/,$pair);
                   3828:                 if ($key eq 'thumb') {
                   3829:                     &add_filetype($allfiles,$value,$key);
                   3830:                 } elsif ($key eq 'content') {
                   3831:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3832:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3833:                     if ($ext ne '') {
                   3834:                         &add_filetype($allfiles,$path.$value,$ext);
                   3835:                     }
                   3836:                 }
                   3837:             }
                   3838:         }
                   3839:     }
1.637     raeburn  3840:     return 'ok';
                   3841: }
                   3842: 
1.639     albertel 3843: sub add_filetype {
                   3844:     my ($allfiles,$file,$type)=@_;
                   3845:     if (exists($allfiles->{$file})) {
                   3846: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3847: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3848: 	}
                   3849:     } else {
                   3850: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3851:     }
                   3852: }
                   3853: 
1.1164    raeburn  3854: sub embedded_dependency {
                   3855:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3856:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3857:         if (($identifier ne '') &&
                   3858:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3859:             ($pathfrom ne '')) {
                   3860:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3861:             foreach my $dep (@{$related->{$identifier}}) {
                   3862:                 &add_filetype($allfiles,$path.$dep,'object');
                   3863:             }
                   3864:         }
                   3865:     }
                   3866:     return;
                   3867: }
                   3868: 
1.493     albertel 3869: sub removeuploadedurl {
1.984     neumanie 3870:     my ($url)=@_;	
                   3871:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3872:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3873: }
                   3874: 
                   3875: sub removeuserfile {
                   3876:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3877:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3878:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3879:     if ($result eq 'ok') {	
1.798     raeburn  3880:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3881:             my $metafile = $fname.'.meta';
                   3882:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3883: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3884:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3885:             my $sqlresult = 
1.823     albertel 3886:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3887:                                         'portfolio_metadata',$group,
                   3888:                                         'delete');
1.798     raeburn  3889:         }
                   3890:     }
                   3891:     return $result;
1.257     www      3892: }
1.15      www      3893: 
1.530     albertel 3894: sub mkdiruserfile {
                   3895:     my ($docuname,$docudom,$dir)=@_;
                   3896:     my $home=&homeserver($docuname,$docudom);
                   3897:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3898: }
                   3899: 
1.531     albertel 3900: sub renameuserfile {
                   3901:     my ($docuname,$docudom,$old,$new)=@_;
                   3902:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3903:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3904:                         &escape("$old").':'.&escape("$new"),$home);
                   3905:     if ($result eq 'ok') {
                   3906:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3907:             my $oldmeta = $old.'.meta';
                   3908:             my $newmeta = $new.'.meta';
                   3909:             my $metaresult = 
                   3910:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3911: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3912:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3913:             my $sqlresult = 
1.823     albertel 3914:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3915:                                         'portfolio_metadata',$group,
                   3916:                                         'delete');
1.798     raeburn  3917:         }
                   3918:     }
                   3919:     return $result;
1.531     albertel 3920: }
                   3921: 
1.14      www      3922: # ------------------------------------------------------------------------- Log
                   3923: 
                   3924: sub log {
                   3925:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3926:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3927: }
                   3928: 
                   3929: # ------------------------------------------------------------------ Course Log
1.352     www      3930: #
                   3931: # This routine flushes several buffers of non-mission-critical nature
                   3932: #
1.157     www      3933: 
                   3934: sub flushcourselogs {
1.352     www      3935:     &logthis('Flushing log buffers');
                   3936: #
                   3937: # course logs
                   3938: # This is a log of all transactions in a course, which can be used
                   3939: # for data mining purposes
                   3940: #
                   3941: # It also collects the courseid database, which lists last transaction
                   3942: # times and course titles for all courseids
                   3943: #
                   3944:     my %courseidbuffer=();
1.921     raeburn  3945:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3946:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3947: 		          &escape($courselogs{$crsid}),
                   3948: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3949: 	    delete $courselogs{$crsid};
                   3950:         } else {
                   3951:             &logthis('Failed to flush log buffer for '.$crsid);
                   3952:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3953:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3954:                         " exceeded maximum size, deleting.</font>");
                   3955:                delete $courselogs{$crsid};
                   3956:             }
1.352     www      3957:         }
1.920     raeburn  3958:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3959:             'description' => $coursedescrbuf{$crsid},
                   3960:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3961:             'type'        => $coursetypebuf{$crsid},
                   3962:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3963:         };
1.191     harris41 3964:     }
1.352     www      3965: #
                   3966: # Write course id database (reverse lookup) to homeserver of courses 
                   3967: # Is used in pickcourse
                   3968: #
1.840     albertel 3969:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3970:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3971:                                     $courseidbuffer{$crs_home},
                   3972:                                     $crs_home,'timeonly');
1.352     www      3973:     }
                   3974: #
                   3975: # File accesses
                   3976: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3977: #
1.449     matthew  3978:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3979:         if ($entry =~ /___count$/) {
                   3980:             my ($dom,$name);
1.807     albertel 3981:             ($dom,$name,undef)=
1.811     albertel 3982: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3983:             if (! defined($dom) || $dom eq '' || 
                   3984:                 ! defined($name) || $name eq '') {
1.620     albertel 3985:                 my $cid = $env{'request.course.id'};
                   3986:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3987:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3988:             }
1.450     matthew  3989:             my $value = $accesshash{$entry};
                   3990:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3991:             my %temphash=($url => $value);
1.449     matthew  3992:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3993:             if ($result eq 'ok') {
                   3994:                 delete $accesshash{$entry};
                   3995:             }
                   3996:         } else {
1.811     albertel 3997:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3998:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3999:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4000:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4001:                 delete $accesshash{$entry};
                   4002:             }
1.185     www      4003:         }
1.191     harris41 4004:     }
1.352     www      4005: #
                   4006: # Roles
                   4007: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4008: #
1.800     albertel 4009:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4010:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4011: 	    split(/\:/,$entry);
                   4012:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4013:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4014:                 $rudom,$runame) eq 'ok') {
                   4015: 	    delete $userrolehash{$entry};
                   4016:         }
                   4017:     }
1.662     raeburn  4018: #
1.1172.2.90  raeburn  4019: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4020: #
                   4021:     my %domrolebuffer = ();
1.1000    raeburn  4022:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4023:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4024:         if ($domrolebuffer{$rudom}) {
                   4025:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4026:                       '='.&escape($domainrolehash{$entry});
                   4027:         } else {
                   4028:             $domrolebuffer{$rudom}.=&escape($entry).
                   4029:                       '='.&escape($domainrolehash{$entry});
                   4030:         }
                   4031:         delete $domainrolehash{$entry};
                   4032:     }
                   4033:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4034:         my %servers;
                   4035:         if (defined(&domain($dom,'primary'))) {
                   4036:             my $primary=&domain($dom,'primary');
                   4037:             my $hostname=&hostname($primary);
                   4038:             $servers{$primary} = $hostname;
                   4039:         } else {
                   4040:             %servers = &get_servers($dom,'library');
                   4041:         }
1.841     albertel 4042: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4043: 	    if (&reply('domroleput:'.$dom.':'.
                   4044: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4045: 	        last;
                   4046: 	    } else {
1.841     albertel 4047: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4048: 	    }
1.662     raeburn  4049:         }
                   4050:     }
1.186     www      4051:     $dumpcount++;
1.157     www      4052: }
                   4053: 
                   4054: sub courselog {
                   4055:     my $what=shift;
1.158     www      4056:     $what=time.':'.$what;
1.620     albertel 4057:     unless ($env{'request.course.id'}) { return ''; }
                   4058:     $coursedombuf{$env{'request.course.id'}}=
                   4059:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4060:     $coursenumbuf{$env{'request.course.id'}}=
                   4061:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4062:     $coursehombuf{$env{'request.course.id'}}=
                   4063:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4064:     $coursedescrbuf{$env{'request.course.id'}}=
                   4065:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4066:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4067:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4068:     $courseownerbuf{$env{'request.course.id'}}=
                   4069:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4070:     $coursetypebuf{$env{'request.course.id'}}=
                   4071:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4072:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4073: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4074:     } else {
1.620     albertel 4075: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4076:     }
1.620     albertel 4077:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4078: 	&flushcourselogs();
                   4079:     }
1.158     www      4080: }
                   4081: 
                   4082: sub courseacclog {
                   4083:     my $fnsymb=shift;
1.620     albertel 4084:     unless ($env{'request.course.id'}) { return ''; }
                   4085:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4086:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4087:         $what.=':POST';
1.583     matthew  4088:         # FIXME: Probably ought to escape things....
1.800     albertel 4089: 	foreach my $key (keys(%env)) {
                   4090:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4091:                 my $formitem = $1;
                   4092:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4093:                     $what.=':'.$formitem.'='.$env{$key};
                   4094:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4095:                     $what.=':'.$formitem.'='.$env{$key};
                   4096:                 }
1.158     www      4097:             }
1.191     harris41 4098:         }
1.583     matthew  4099:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4100:         # FIXME: We should not be depending on a form parameter that someone
                   4101:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4102:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4103:             $what.= ':POST';
                   4104:             # FIXME: Probably ought to escape things....
                   4105:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4106:                                  'crsdiscuss') {
1.620     albertel 4107:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4108:             }
                   4109:         }
1.158     www      4110:     }
                   4111:     &courselog($what);
1.149     www      4112: }
                   4113: 
1.185     www      4114: sub countacc {
                   4115:     my $url=&declutter(shift);
1.458     matthew  4116:     return if (! defined($url) || $url eq '');
1.620     albertel 4117:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4118: #
                   4119: # Mark that this url was used in this course
                   4120: #
1.620     albertel 4121:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4122: #
                   4123: # Increase the access count for this resource in this child process
                   4124: #
1.281     www      4125:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4126:     $accesshash{$key}++;
1.185     www      4127: }
1.349     www      4128: 
1.361     www      4129: sub linklog {
                   4130:     my ($from,$to)=@_;
                   4131:     $from=&declutter($from);
                   4132:     $to=&declutter($to);
                   4133:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4134:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4135: }
1.1160    www      4136: 
                   4137: sub statslog {
                   4138:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4139:     if ($users<2) { return; }
                   4140:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4141:             'course'       => $env{'request.course.id'},
                   4142:             'sections'     => '"all"',
                   4143:             'num_students' => $users,
                   4144:             'part'         => $part,
                   4145:             'symb'         => $symb,
                   4146:             'mean_tries'   => $av_attempts,
                   4147:             'deg_of_diff'  => $degdiff});
                   4148:     foreach my $key (keys(%dynstore)) {
                   4149:         $accesshash{$key}=$dynstore{$key};
                   4150:     }
                   4151: }
1.361     www      4152:   
1.349     www      4153: sub userrolelog {
                   4154:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4155:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4156:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4157:        $userrolehash
                   4158:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4159:                     =$tend.':'.$tstart;
1.662     raeburn  4160:     }
1.1169    droeschl 4161:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4162:        $userrolehash
                   4163:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4164:                     =$tend.':'.$tstart;
                   4165:     }
1.1172.2.90  raeburn  4166:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4167:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4168:        $domainrolehash
                   4169:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4170:                     = $tend.':'.$tstart;
                   4171:     }
1.351     www      4172: }
                   4173: 
1.957     raeburn  4174: sub courserolelog {
                   4175:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4176:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4177:         my $cdom = $1;
                   4178:         my $cnum = $2;
                   4179:         my $sec = $3;
                   4180:         my $namespace = 'rolelog';
                   4181:         my %storehash = (
                   4182:                            role    => $trole,
                   4183:                            start   => $tstart,
                   4184:                            end     => $tend,
                   4185:                            selfenroll => $selfenroll,
                   4186:                            context    => $context,
                   4187:                         );
                   4188:         if ($trole eq 'gr') {
                   4189:             $namespace = 'groupslog';
                   4190:             $storehash{'group'} = $sec;
                   4191:         } else {
                   4192:             $storehash{'section'} = $sec;
                   4193:         }
                   4194:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4195:                    $domain,$cnum,$cdom);
                   4196:         if (($trole ne 'st') || ($sec ne '')) {
                   4197:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4198:         }
                   4199:     }
                   4200:     return;
                   4201: }
                   4202: 
1.1172.2.9  raeburn  4203: sub domainrolelog {
                   4204:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4205:     if ($area =~ m{^/($match_domain)/$}) {
                   4206:         my $cdom = $1;
                   4207:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4208:         my $namespace = 'rolelog';
                   4209:         my %storehash = (
                   4210:                            role    => $trole,
                   4211:                            start   => $tstart,
                   4212:                            end     => $tend,
                   4213:                            context => $context,
                   4214:                         );
                   4215:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4216:                    $domain,$domconfiguser,$cdom);
                   4217:     }
                   4218:     return;
                   4219: 
                   4220: }
                   4221: 
                   4222: sub coauthorrolelog {
                   4223:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4224:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4225:         my $audom = $1;
                   4226:         my $auname = $2;
                   4227:         my $namespace = 'rolelog';
                   4228:         my %storehash = (
                   4229:                            role    => $trole,
                   4230:                            start   => $tstart,
                   4231:                            end     => $tend,
                   4232:                            context => $context,
                   4233:                         );
                   4234:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4235:                    $domain,$auname,$audom);
                   4236:     }
                   4237:     return;
                   4238: }
                   4239: 
1.351     www      4240: sub get_course_adv_roles {
1.948     raeburn  4241:     my ($cid,$codes) = @_;
1.620     albertel 4242:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4243:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4244:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4245:     my %nothide=();
1.800     albertel 4246:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4247:         if ($user !~ /:/) {
                   4248: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4249:         } else {
                   4250:             $nothide{$user}=1;
                   4251:         }
1.470     www      4252:     }
1.1172.2.23  raeburn  4253:     my @possdoms = ($coursehash{'domain'});
                   4254:     if ($coursehash{'checkforpriv'}) {
                   4255:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4256:     }
1.351     www      4257:     my %returnhash=();
                   4258:     my %dumphash=
                   4259:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4260:     my $now=time;
1.997     raeburn  4261:     my %privileged;
1.1000    raeburn  4262:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4263: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4264:         if (($tstart) && ($tstart<0)) { next; }
                   4265:         if (($tend) && ($tend<$now)) { next; }
                   4266:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4267:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4268: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4269:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4270:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4271: 	if ($role eq 'cr') { next; }
1.948     raeburn  4272:         if ($codes) {
                   4273:             if ($section) { $role .= ':'.$section; }
                   4274:             if ($returnhash{$role}) {
                   4275:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4276:             } else {
                   4277:                 $returnhash{$role}=$username.':'.$domain;
                   4278:             }
1.351     www      4279:         } else {
1.988     raeburn  4280:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4281:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4282:             if ($returnhash{$key}) {
                   4283: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4284:             } else {
                   4285:                 $returnhash{$key}=$username.':'.$domain;
                   4286:             }
1.351     www      4287:         }
1.948     raeburn  4288:     }
1.400     www      4289:     return %returnhash;
                   4290: }
                   4291: 
                   4292: sub get_my_roles {
1.937     raeburn  4293:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4294:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4295:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4296:     my (%dumphash,%nothide);
1.1086    raeburn  4297:     if ($context eq 'userroles') {
1.1166    raeburn  4298:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4299:     } else {
1.1172.2.23  raeburn  4300:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4301:         if ($hidepriv) {
                   4302:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4303:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4304:                 if ($user !~ /:/) {
                   4305:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4306:                 } else {
                   4307:                     $nothide{$user} = 1;
                   4308:                 }
                   4309:             }
                   4310:         }
1.858     raeburn  4311:     }
1.400     www      4312:     my %returnhash=();
                   4313:     my $now=time;
1.999     raeburn  4314:     my %privileged;
1.800     albertel 4315:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4316:         my ($role,$tend,$tstart);
                   4317:         if ($context eq 'userroles') {
1.1149    raeburn  4318:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4319: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4320:         } else {
                   4321:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4322:         }
1.400     www      4323:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4324:         my $status = 'active';
1.939     raeburn  4325:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4326:             $status = 'previous';
                   4327:         } 
                   4328:         if (($tstart) && ($now<$tstart)) {
                   4329:             $status = 'future';
                   4330:         }
                   4331:         if (ref($types) eq 'ARRAY') {
                   4332:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4333:                 next;
                   4334:             } 
                   4335:         } else {
                   4336:             if ($status ne 'active') {
                   4337:                 next;
                   4338:             }
                   4339:         }
1.867     raeburn  4340:         my ($rolecode,$username,$domain,$section,$area);
                   4341:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4342:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4343:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4344:         } else {
                   4345:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4346:         }
1.832     raeburn  4347:         if (ref($roledoms) eq 'ARRAY') {
                   4348:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4349:                 next;
                   4350:             }
                   4351:         }
                   4352:         if (ref($roles) eq 'ARRAY') {
                   4353:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4354:                 if ($role =~ /^cr\//) {
                   4355:                     if (!grep(/^cr$/,@{$roles})) {
                   4356:                         next;
                   4357:                     }
1.1104    raeburn  4358:                 } elsif ($role =~ /^gr\//) {
                   4359:                     if (!grep(/^gr$/,@{$roles})) {
                   4360:                         next;
                   4361:                     }
1.922     raeburn  4362:                 } else {
                   4363:                     next;
                   4364:                 }
1.832     raeburn  4365:             }
1.867     raeburn  4366:         }
1.937     raeburn  4367:         if ($hidepriv) {
1.1172.2.23  raeburn  4368:             my @privroles = ('dc','su');
1.999     raeburn  4369:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4370:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4371:             } else {
1.1172.2.23  raeburn  4372:                 my $possdoms = [$domain];
                   4373:                 if (ref($roledoms) eq 'ARRAY') {
                   4374:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4375:                 }
1.1172.2.23  raeburn  4376:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4377:                     if (!$nothide{$username.':'.$domain}) {
                   4378:                         next;
                   4379:                     }
                   4380:                 }
1.937     raeburn  4381:             }
                   4382:         }
1.933     raeburn  4383:         if ($withsec) {
                   4384:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4385:                 $tstart.':'.$tend;
                   4386:         } else {
                   4387:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4388:         }
1.832     raeburn  4389:     }
1.373     www      4390:     return %returnhash;
1.399     www      4391: }
                   4392: 
1.1172.2.89  raeburn  4393: sub get_all_adhocroles {
                   4394:     my ($dom) = @_;
                   4395:     my @roles_by_num = ();
                   4396:     my %domdefaults = &get_domain_defaults($dom);
                   4397:     my (%description,%access_in_dom,%access_info);
                   4398:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4399:         my $count = 0;
                   4400:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4401:         my %ordered;
                   4402:         foreach my $role (sort(keys(%domcurrent))) {
                   4403:             my ($order,$desc,$access_in_dom);
                   4404:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4405:                 $order = $domcurrent{$role}{'order'};
                   4406:                 $desc = $domcurrent{$role}{'desc'};
                   4407:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4408:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4409:             }
                   4410:             if ($order eq '') {
                   4411:                 $order = $count;
                   4412:             }
                   4413:             $ordered{$order} = $role;
                   4414:             if ($desc ne '') {
                   4415:                 $description{$role} = $desc;
                   4416:             } else {
                   4417:                 $description{$role}= $role;
                   4418:             }
                   4419:             $count++;
                   4420:         }
                   4421:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4422:             push(@roles_by_num,$ordered{$item});
                   4423:         }
                   4424:     }
                   4425:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4426: }
                   4427: 
                   4428: sub get_my_adhocroles {
                   4429:     my ($cid,$checkreg) = @_;
                   4430:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4431:     if ($env{'request.course.id'} eq $cid) {
                   4432:         $cdom = $env{'course.'.$cid.'.domain'};
                   4433:         $cnum = $env{'course.'.$cid.'.num'};
                   4434:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4435:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4436:         $cdom = $1;
                   4437:         $cnum = $2;
                   4438:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4439:                                      $cdom,$cnum);
                   4440:     }
                   4441:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4442:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4443:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4444:         if ($rosterhash{$user} ne '') {
                   4445:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4446:             return ([],{}) if ($type eq 'auto');
                   4447:         }
                   4448:     }
                   4449:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4450:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4451:             my $then=$env{'user.login.time'};
                   4452:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4453:             if (!$update) {
                   4454:                 $update = $then;
                   4455:             }
                   4456:             my @liveroles;
                   4457:             foreach my $role ('dh','da') {
                   4458:                 if ($env{"user.role.$role./$cdom/"}) {
                   4459:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4460:                     my $limit = $update;
                   4461:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4462:                         $limit = $then;
                   4463:                     }
                   4464:                     my $activerole = 1;
                   4465:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4466:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4467:                     if ($activerole) {
                   4468:                         push(@liveroles,$role);
                   4469:                     }
                   4470:                 }
                   4471:             }
                   4472:             if (@liveroles) {
1.1172.2.89  raeburn  4473:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4474:                     my ($accessref,$accessinfo,%access_in_dom);
                   4475:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4476:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4477:                         if (@{$roles_by_num}) {
                   4478:                             my %settings;
                   4479:                             if ($env{'request.course.id'} eq $cid) {
                   4480:                                 foreach my $envkey (keys(%env)) {
                   4481:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4482:                                         $settings{$1} = $env{$envkey};
                   4483:                                     }
                   4484:                                 }
                   4485:                             } else {
                   4486:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4487:                             }
                   4488:                             my %setincrs;
                   4489:                             if ($settings{'internal.adhocaccess'}) {
                   4490:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4491:                             }
                   4492:                             my @statuses;
                   4493:                             if ($env{'environment.inststatus'}) {
                   4494:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4495:                             }
                   4496:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4497:                             if (ref($accessref) eq 'HASH') {
                   4498:                                 %access_in_dom = %{$accessref};
                   4499:                             }
                   4500:                             foreach my $role (@{$roles_by_num}) {
                   4501:                                 my ($curraccess,@okstatus,@personnel);
                   4502:                                 if ($setincrs{$role}) {
                   4503:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4504:                                     if ($curraccess eq 'status') {
                   4505:                                         @okstatus = split(/\&/,$rest);
                   4506:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4507:                                         @personnel = split(/\&/,$rest);
                   4508:                                     }
                   4509:                                 } else {
                   4510:                                     $curraccess = $access_in_dom{$role};
                   4511:                                     if (ref($accessinfo) eq 'HASH') {
                   4512:                                         if ($curraccess eq 'status') {
                   4513:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4514:                                                 @okstatus = @{$accessinfo->{$role}};
                   4515:                                             }
                   4516:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4517:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4518:                                                 @personnel = @{$accessinfo->{$role}};
                   4519:                                             }
                   4520:                                         }
                   4521:                                     }
                   4522:                                 }
                   4523:                                 if ($curraccess eq 'none') {
                   4524:                                     next;
                   4525:                                 } elsif ($curraccess eq 'all') {
                   4526:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4527:                                 } elsif ($curraccess eq 'dh') {
                   4528:                                     if (grep(/^dh$/,@liveroles)) {
                   4529:                                         push(@possroles,$role);
                   4530:                                     } else {
                   4531:                                         next;
                   4532:                                     }
                   4533:                                 } elsif ($curraccess eq 'da') {
                   4534:                                     if (grep(/^da$/,@liveroles)) {
                   4535:                                         push(@possroles,$role);
                   4536:                                     } else {
                   4537:                                         next;
                   4538:                                     }
1.1172.2.89  raeburn  4539:                                 } elsif ($curraccess eq 'status') {
                   4540:                                     if (@okstatus) {
                   4541:                                         if (!@statuses) {
                   4542:                                             if (grep(/^default$/,@okstatus)) {
                   4543:                                                 push(@possroles,$role);
                   4544:                                             }
                   4545:                                         } else {
                   4546:                                             foreach my $status (@okstatus) {
                   4547:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4548:                                                     push(@possroles,$role);
                   4549:                                                     last;
                   4550:                                                 }
                   4551:                                             }
                   4552:                                         }
                   4553:                                     }
                   4554:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4555:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4556:                                         if ($curraccess eq 'exc') {
                   4557:                                             push(@possroles,$role);
                   4558:                                         }
                   4559:                                     } elsif ($curraccess eq 'inc') {
                   4560:                                         push(@possroles,$role);
                   4561:                                     }
                   4562:                                 }
                   4563:                             }
                   4564:                         }
                   4565:                     }
                   4566:                 }
                   4567:             }
                   4568:         }
                   4569:     }
                   4570:     unless (ref($description) eq 'HASH') {
                   4571:         if (ref($roles_by_num) eq 'ARRAY') {
                   4572:             my %desc;
                   4573:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4574:             $description = \%desc;
                   4575:         } else {
                   4576:             $description = {};
                   4577:         }
                   4578:     }
                   4579:     return (\@possroles,$description);
                   4580: }
                   4581: 
1.399     www      4582: # ----------------------------------------------------- Frontpage Announcements
                   4583: #
                   4584: #
                   4585: 
                   4586: sub postannounce {
                   4587:     my ($server,$text)=@_;
1.844     albertel 4588:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4589:     unless ($text=~/\w/) { $text=''; }
                   4590:     return &reply('setannounce:'.&escape($text),$server);
                   4591: }
                   4592: 
                   4593: sub getannounce {
1.448     albertel 4594: 
1.1172.2.96  raeburn  4595:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4596: 	my $announcement='';
1.800     albertel 4597: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4598: 	close($fh);
1.399     www      4599: 	if ($announcement=~/\w/) { 
                   4600: 	    return 
                   4601:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4602:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4603: 	} else {
                   4604: 	    return '';
                   4605: 	}
                   4606:     } else {
                   4607: 	return '';
                   4608:     }
1.351     www      4609: }
1.353     www      4610: 
                   4611: # ---------------------------------------------------------- Course ID routines
                   4612: # Deal with domain's nohist_courseid.db files
                   4613: #
                   4614: 
                   4615: sub courseidput {
1.921     raeburn  4616:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4617:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4618:     my $outcome;
                   4619:     if ($caller eq 'timeonly') {
                   4620:         my $cids = '';
                   4621:         foreach my $item (keys(%$storehash)) {
                   4622:             $cids.=&escape($item).'&';
                   4623:         }
                   4624:         $cids=~s/\&$//;
                   4625:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4626:                           $coursehome);       
                   4627:     } else {
                   4628:         my $items = '';
                   4629:         foreach my $item (keys(%$storehash)) {
                   4630:             $items.= &escape($item).'='.
                   4631:                      &freeze_escape($$storehash{$item}).'&';
                   4632:         }
                   4633:         $items=~s/\&$//;
                   4634:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4635:                           $coursehome);
1.918     raeburn  4636:     }
                   4637:     if ($outcome eq 'unknown_cmd') {
                   4638:         my $what;
                   4639:         foreach my $cid (keys(%$storehash)) {
                   4640:             $what .= &escape($cid).'=';
1.921     raeburn  4641:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4642:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4643:             }
                   4644:             $what =~ s/\:$/&/;
                   4645:         }
                   4646:         $what =~ s/\&$//;  
                   4647:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4648:     } else {
                   4649:         return $outcome;
                   4650:     }
1.353     www      4651: }
                   4652: 
                   4653: sub courseiddump {
1.921     raeburn  4654:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4655:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4656:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4657:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4658:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4659:     my $as_hash = 1;
                   4660:     my %returnhash;
                   4661:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4662:     my %libserv = &all_library();
                   4663:     foreach my $tryserver (keys(%libserv)) {
                   4664:         if ( (  $hostidflag == 1 
                   4665: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4666: 	     || (!defined($hostidflag)) ) {
                   4667: 
1.918     raeburn  4668: 	    if (($domfilter eq '') ||
                   4669: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4670:                 my $rep;
                   4671:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4672:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4673:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4674:                                 &escape($descfilter), &escape($instcodefilter),
                   4675:                                 &escape($ownerfilter), &escape($coursefilter),
                   4676:                                 &escape($typefilter), &escape($regexp_ok),
                   4677:                                 $as_hash, &escape($selfenrollonly),
                   4678:                                 &escape($catfilter), $showhidden, $caller,
                   4679:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4680:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4681:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4682:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4683:                 } else {
                   4684:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4685:                              $sincefilter.':'.&escape($descfilter).':'.
                   4686:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4687:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4688:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4689:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4690:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4691:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4692:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4693:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4694:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4695:                 }
                   4696: 
1.918     raeburn  4697:                 my @pairs=split(/\&/,$rep);
                   4698:                 foreach my $item (@pairs) {
                   4699:                     my ($key,$value)=split(/\=/,$item,2);
                   4700:                     $key = &unescape($key);
                   4701:                     next if ($key =~ /^error: 2 /);
                   4702:                     my $result = &thaw_unescape($value);
                   4703:                     if (ref($result) eq 'HASH') {
                   4704:                         $returnhash{$key}=$result;
                   4705:                     } else {
1.921     raeburn  4706:                         my @responses = split(/:/,$value);
                   4707:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4708:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4709:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4710:                         }
1.1008    raeburn  4711:                     }
1.353     www      4712:                 }
                   4713:             }
                   4714:         }
                   4715:     }
                   4716:     return %returnhash;
                   4717: }
                   4718: 
1.1055    raeburn  4719: sub courselastaccess {
                   4720:     my ($cdom,$cnum,$hostidref) = @_;
                   4721:     my %returnhash;
                   4722:     if ($cdom && $cnum) {
                   4723:         my $chome = &homeserver($cnum,$cdom);
                   4724:         if ($chome ne 'no_host') {
                   4725:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4726:             &extract_lastaccess(\%returnhash,$rep);
                   4727:         }
                   4728:     } else {
                   4729:         if (!$cdom) { $cdom=''; }
                   4730:         my %libserv = &all_library();
                   4731:         foreach my $tryserver (keys(%libserv)) {
                   4732:             if (ref($hostidref) eq 'ARRAY') {
                   4733:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4734:             } 
                   4735:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4736:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4737:                 &extract_lastaccess(\%returnhash,$rep);
                   4738:             }
                   4739:         }
                   4740:     }
                   4741:     return %returnhash;
                   4742: }
                   4743: 
                   4744: sub extract_lastaccess {
                   4745:     my ($returnhash,$rep) = @_;
                   4746:     if (ref($returnhash) eq 'HASH') {
                   4747:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4748:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4749:                  $rep eq '') {
                   4750:             my @pairs=split(/\&/,$rep);
                   4751:             foreach my $item (@pairs) {
                   4752:                 my ($key,$value)=split(/\=/,$item,2);
                   4753:                 $key = &unescape($key);
                   4754:                 next if ($key =~ /^error: 2 /);
                   4755:                 $returnhash->{$key} = &thaw_unescape($value);
                   4756:             }
                   4757:         }
                   4758:     }
                   4759:     return;
                   4760: }
                   4761: 
1.658     raeburn  4762: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4763: 
                   4764: sub dcmailput {
1.685     raeburn  4765:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4766:     my $status = &Apache::lonnet::critical(
1.740     www      4767:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4768:        &escape($message),$server);
1.662     raeburn  4769:     return $status;
                   4770: }
                   4771: 
1.658     raeburn  4772: sub dcmaildump {
                   4773:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4774:     my %returnhash=();
1.846     albertel 4775: 
                   4776:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4777:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4778:                                                          &escape($enddate).':';
                   4779: 	my @esc_senders=map { &escape($_)} @$senders;
                   4780: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4781: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4782:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4783:             if (($key) && ($value)) {
                   4784:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4785:             }
                   4786:         }
                   4787:     }
                   4788:     return %returnhash;
                   4789: }
1.662     raeburn  4790: # ---------------------------------------------------------- Domain roles
                   4791: 
                   4792: sub get_domain_roles {
                   4793:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4794:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4795:         $startdate = '.';
                   4796:     }
1.1018    raeburn  4797:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4798:         $enddate = '.';
                   4799:     }
1.922     raeburn  4800:     my $rolelist;
                   4801:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4802:         $rolelist = join('&',@{$roles});
1.922     raeburn  4803:     }
1.662     raeburn  4804:     my %personnel = ();
1.841     albertel 4805: 
                   4806:     my %servers = &get_servers($dom,'library');
                   4807:     foreach my $tryserver (keys(%servers)) {
                   4808: 	%{$personnel{$tryserver}}=();
                   4809: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4810: 					    &escape($startdate).':'.
                   4811: 					    &escape($enddate).':'.
                   4812: 					    &escape($rolelist), $tryserver))) {
                   4813: 	    my ($key,$value) = split(/\=/,$line,2);
                   4814: 	    if (($key) && ($value)) {
                   4815: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4816: 	    }
                   4817: 	}
1.662     raeburn  4818:     }
                   4819:     return %personnel;
                   4820: }
1.658     raeburn  4821: 
1.1172.2.89  raeburn  4822: sub get_active_domroles {
                   4823:     my ($dom,$roles) = @_;
                   4824:     return () unless (ref($roles) eq 'ARRAY');
                   4825:     my $now = time;
                   4826:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4827:     my %domroles;
                   4828:     foreach my $server (keys(%dompersonnel)) {
                   4829:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4830:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4831:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4832:         }
                   4833:     }
                   4834:     return %domroles;
                   4835: }
                   4836: 
1.1057    www      4837: # ----------------------------------------------------------- Interval timing 
1.149     www      4838: 
1.1153    www      4839: {
                   4840: # Caches needed for speedup of navmaps
                   4841: # We don't want to cache this for very long at all (5 seconds at most)
                   4842: # 
                   4843: # The user for whom we cache
                   4844: my $cachedkey='';
                   4845: # The cached times for this user
                   4846: my %cachedtimes=();
                   4847: # When this was last done
1.1172.2.66  raeburn  4848: my $cachedtime='';
1.1153    www      4849: 
                   4850: sub load_all_first_access {
1.1154    raeburn  4851:     my ($uname,$udom)=@_;
1.1156    www      4852:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4853:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4854:         return;
                   4855:     }
                   4856:     $cachedtime=time;
                   4857:     $cachedkey=$uname.':'.$udom;
                   4858:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4859: }
                   4860: 
1.504     albertel 4861: sub get_first_access {
1.1162    raeburn  4862:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4863:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4864:     if ($argsymb) { $symb=$argsymb; }
                   4865:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4866:     if ($argmap) { $map = $argmap; }
1.926     albertel 4867:     if ($type eq 'course') {
                   4868: 	$res='course';
                   4869:     } elsif ($type eq 'map') {
1.588     albertel 4870: 	$res=&symbread($map);
                   4871:     } else {
                   4872: 	$res=$symb;
                   4873:     }
1.1153    www      4874:     &load_all_first_access($uname,$udom);
                   4875:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4876: }
                   4877: 
                   4878: sub set_first_access {
1.1162    raeburn  4879:     my ($type,$interval)=@_;
1.790     albertel 4880:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4881:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4882:     if ($type eq 'course') {
                   4883: 	$res='course';
                   4884:     } elsif ($type eq 'map') {
1.588     albertel 4885: 	$res=&symbread($map);
                   4886:     } else {
                   4887: 	$res=$symb;
                   4888:     }
1.1153    www      4889:     $cachedkey='';
1.1162    raeburn  4890:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4891:     if (!$firstaccess) {
1.1162    raeburn  4892:         my $start = time;
                   4893: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4894:                           $udom,$uname);
                   4895:         if ($putres eq 'ok') {
                   4896:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4897:                  $udom,$uname); 
                   4898:             &appenv(
                   4899:                      {
                   4900:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4901:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4902:                      }
                   4903:                   );
1.1172.2.97  raeburn  4904:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   4905:                 $cachedtimes{"$courseid\0$res"} = $start;
                   4906:             }
1.1162    raeburn  4907:         }
                   4908:         return $putres;
1.505     albertel 4909:     }
                   4910:     return 'already_set';
1.504     albertel 4911: }
1.1153    www      4912: }
1.1172.2.32  raeburn  4913: 
                   4914: sub checkout {
                   4915:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4916:     my $now=time;
                   4917:     my $lonhost=$perlvar{'lonHostID'};
                   4918:     my $infostr=&escape(
                   4919:                  'CHECKOUTTOKEN&'.
                   4920:                  $tuname.'&'.
                   4921:                  $tudom.'&'.
                   4922:                  $tcrsid.'&'.
                   4923:                  $symb.'&'.
                   4924:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4925:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4926:     if ($token=~/^error\:/) {
                   4927:         &logthis("<font color=\"blue\">WARNING: ".
                   4928:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4929:                  "</font>");
                   4930:         return '';
                   4931:     }
                   4932: 
                   4933:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4934:     $token=~tr/a-z/A-Z/;
                   4935: 
                   4936:     my %infohash=('resource.0.outtoken' => $token,
                   4937:                   'resource.0.checkouttime' => $now,
                   4938:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4939: 
                   4940:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4941:        return '';
                   4942:     } else {
                   4943:         &logthis("<font color=\"blue\">WARNING: ".
                   4944:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4945:                  "</font>");
                   4946:     }
                   4947: 
                   4948:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4949:                          &escape('Checkout '.$infostr.' - '.
                   4950:                                                  $token)) ne 'ok') {
                   4951:         return '';
                   4952:     } else {
                   4953:         &logthis("<font color=\"blue\">WARNING: ".
                   4954:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4955:                  "</font>");
                   4956:     }
                   4957:     return $token;
                   4958: }
                   4959: 
                   4960: # ------------------------------------------------------------ Check in an item
                   4961: 
                   4962: sub checkin {
                   4963:     my $token=shift;
                   4964:     my $now=time;
                   4965:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4966:     $lonhost=~tr/A-Z/a-z/;
                   4967:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4968:     $dtoken=~s/\W/\_/g;
                   4969:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4970:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4971: 
                   4972:     unless (($tuname) && ($tudom)) {
                   4973:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4974:         return '';
                   4975:     }
                   4976: 
                   4977:     unless (&allowed('mgr',$tcrsid)) {
                   4978:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4979:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4980:         return '';
                   4981:     }
                   4982: 
                   4983:     my %infohash=('resource.0.intoken' => $token,
                   4984:                   'resource.0.checkintime' => $now,
                   4985:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4986: 
                   4987:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4988:        return '';
                   4989:     }
                   4990: 
                   4991:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4992:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4993:         return '';
                   4994:     }
                   4995: 
                   4996:     return ($symb,$tuname,$tudom,$tcrsid);
                   4997: }
                   4998: 
1.110     www      4999: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5000: 
                   5001: sub expirespread {
                   5002:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5003:     my $cid=$env{'request.course.id'}; 
1.110     www      5004:     if ($cid) {
                   5005:        my $now=time;
                   5006:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5007:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5008:                             $env{'course.'.$cid.'.num'}.
1.110     www      5009: 	        	    ':nohist_expirationdates:'.
                   5010:                             &escape($key).'='.$now,
1.620     albertel 5011:                             $env{'course.'.$cid.'.home'})
1.110     www      5012:     }
                   5013:     return 'ok';
1.14      www      5014: }
                   5015: 
1.109     www      5016: # ----------------------------------------------------- Devalidate Spreadsheets
                   5017: 
                   5018: sub devalidate {
1.325     www      5019:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5020:     my $cid=$env{'request.course.id'}; 
1.109     www      5021:     if ($cid) {
1.391     matthew  5022:         # delete the stored spreadsheets for
                   5023:         # - the student level sheet of this user in course's homespace
                   5024:         # - the assessment level sheet for this resource 
                   5025:         #   for this user in user's homespace
1.553     albertel 5026: 	# - current conditional state info
1.325     www      5027: 	my $key=$uname.':'.$udom.':';
1.109     www      5028:         my $status=
1.299     matthew  5029: 	    &del('nohist_calculatedsheets',
1.391     matthew  5030: 		 [$key.'studentcalc:'],
1.620     albertel 5031: 		 $env{'course.'.$cid.'.domain'},
                   5032: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5033: 		.' '.
                   5034: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5035: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5036:         unless ($status eq 'ok ok') {
                   5037:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5038:                     $uname.' at '.$udom.' for '.
1.109     www      5039: 		    $symb.': '.$status);
1.133     albertel 5040:         }
1.553     albertel 5041: 	&delenv('user.state.'.$cid);
1.109     www      5042:     }
                   5043: }
                   5044: 
1.265     albertel 5045: sub get_scalar {
                   5046:     my ($string,$end) = @_;
                   5047:     my $value;
                   5048:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5049: 	$value = $1;
                   5050:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5051: 	$value = $1;
                   5052:     }
                   5053:     return &unescape($value);
                   5054: }
                   5055: 
                   5056: sub array2str {
                   5057:   my (@array) = @_;
                   5058:   my $result=&arrayref2str(\@array);
                   5059:   $result=~s/^__ARRAY_REF__//;
                   5060:   $result=~s/__END_ARRAY_REF__$//;
                   5061:   return $result;
                   5062: }
                   5063: 
1.204     albertel 5064: sub arrayref2str {
                   5065:   my ($arrayref) = @_;
1.265     albertel 5066:   my $result='__ARRAY_REF__';
1.204     albertel 5067:   foreach my $elem (@$arrayref) {
1.265     albertel 5068:     if(ref($elem) eq 'ARRAY') {
                   5069:       $result.=&arrayref2str($elem).'&';
                   5070:     } elsif(ref($elem) eq 'HASH') {
                   5071:       $result.=&hashref2str($elem).'&';
                   5072:     } elsif(ref($elem)) {
                   5073:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5074:     } else {
                   5075:       $result.=&escape($elem).'&';
                   5076:     }
                   5077:   }
                   5078:   $result=~s/\&$//;
1.265     albertel 5079:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5080:   return $result;
                   5081: }
                   5082: 
1.168     albertel 5083: sub hash2str {
1.204     albertel 5084:   my (%hash) = @_;
                   5085:   my $result=&hashref2str(\%hash);
1.265     albertel 5086:   $result=~s/^__HASH_REF__//;
                   5087:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5088:   return $result;
                   5089: }
                   5090: 
                   5091: sub hashref2str {
                   5092:   my ($hashref)=@_;
1.265     albertel 5093:   my $result='__HASH_REF__';
1.800     albertel 5094:   foreach my $key (sort(keys(%$hashref))) {
                   5095:     if (ref($key) eq 'ARRAY') {
                   5096:       $result.=&arrayref2str($key).'=';
                   5097:     } elsif (ref($key) eq 'HASH') {
                   5098:       $result.=&hashref2str($key).'=';
                   5099:     } elsif (ref($key)) {
1.265     albertel 5100:       $result.='=';
1.800     albertel 5101:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5102:     } else {
1.1132    raeburn  5103: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5104:     }
                   5105: 
1.800     albertel 5106:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5107:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5108:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5109:       $result.=&hashref2str($hashref->{$key}).'&';
                   5110:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5111:        $result.='&';
1.800     albertel 5112:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5113:     } else {
1.800     albertel 5114:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5115:     }
                   5116:   }
1.168     albertel 5117:   $result=~s/\&$//;
1.265     albertel 5118:   $result .= '__END_HASH_REF__';
1.168     albertel 5119:   return $result;
                   5120: }
                   5121: 
                   5122: sub str2hash {
1.265     albertel 5123:     my ($string)=@_;
                   5124:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5125:     return %$hash;
                   5126: }
                   5127: 
                   5128: sub str2hashref {
1.168     albertel 5129:   my ($string) = @_;
1.265     albertel 5130: 
                   5131:   my %hash;
                   5132: 
                   5133:   if($string !~ /^__HASH_REF__/) {
                   5134:       if (! ($string eq '' || !defined($string))) {
                   5135: 	  $hash{'error'}='Not hash reference';
                   5136:       }
                   5137:       return (\%hash, $string);
                   5138:   }
                   5139: 
                   5140:   $string =~ s/^__HASH_REF__//;
                   5141: 
                   5142:   while($string !~ /^__END_HASH_REF__/) {
                   5143:       #key
                   5144:       my $key='';
                   5145:       if($string =~ /^__HASH_REF__/) {
                   5146:           ($key, $string)=&str2hashref($string);
                   5147:           if(defined($key->{'error'})) {
                   5148:               $hash{'error'}='Bad data';
                   5149:               return (\%hash, $string);
                   5150:           }
                   5151:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5152:           ($key, $string)=&str2arrayref($string);
                   5153:           if($key->[0] eq 'Array reference error') {
                   5154:               $hash{'error'}='Bad data';
                   5155:               return (\%hash, $string);
                   5156:           }
                   5157:       } else {
                   5158:           $string =~ s/^(.*?)=//;
1.267     albertel 5159: 	  $key=&unescape($1);
1.265     albertel 5160:       }
                   5161:       $string =~ s/^=//;
                   5162: 
                   5163:       #value
                   5164:       my $value='';
                   5165:       if($string =~ /^__HASH_REF__/) {
                   5166:           ($value, $string)=&str2hashref($string);
                   5167:           if(defined($value->{'error'})) {
                   5168:               $hash{'error'}='Bad data';
                   5169:               return (\%hash, $string);
                   5170:           }
                   5171:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5172:           ($value, $string)=&str2arrayref($string);
                   5173:           if($value->[0] eq 'Array reference error') {
                   5174:               $hash{'error'}='Bad data';
                   5175:               return (\%hash, $string);
                   5176:           }
                   5177:       } else {
                   5178: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5179:       }
                   5180:       $string =~ s/^&//;
                   5181: 
                   5182:       $hash{$key}=$value;
1.204     albertel 5183:   }
1.265     albertel 5184: 
                   5185:   $string =~ s/^__END_HASH_REF__//;
                   5186: 
                   5187:   return (\%hash, $string);
1.204     albertel 5188: }
                   5189: 
                   5190: sub str2array {
1.265     albertel 5191:     my ($string)=@_;
                   5192:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5193:     return @$array;
                   5194: }
                   5195: 
                   5196: sub str2arrayref {
1.204     albertel 5197:   my ($string) = @_;
1.265     albertel 5198:   my @array;
                   5199: 
                   5200:   if($string !~ /^__ARRAY_REF__/) {
                   5201:       if (! ($string eq '' || !defined($string))) {
                   5202: 	  $array[0]='Array reference error';
                   5203:       }
                   5204:       return (\@array, $string);
                   5205:   }
                   5206: 
                   5207:   $string =~ s/^__ARRAY_REF__//;
                   5208: 
                   5209:   while($string !~ /^__END_ARRAY_REF__/) {
                   5210:       my $value='';
                   5211:       if($string =~ /^__HASH_REF__/) {
                   5212:           ($value, $string)=&str2hashref($string);
                   5213:           if(defined($value->{'error'})) {
                   5214:               $array[0] ='Array reference error';
                   5215:               return (\@array, $string);
                   5216:           }
                   5217:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5218:           ($value, $string)=&str2arrayref($string);
                   5219:           if($value->[0] eq 'Array reference error') {
                   5220:               $array[0] ='Array reference error';
                   5221:               return (\@array, $string);
                   5222:           }
                   5223:       } else {
                   5224: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5225:       }
                   5226:       $string =~ s/^&//;
                   5227: 
                   5228:       push(@array, $value);
1.191     harris41 5229:   }
1.265     albertel 5230: 
                   5231:   $string =~ s/^__END_ARRAY_REF__//;
                   5232: 
                   5233:   return (\@array, $string);
1.168     albertel 5234: }
                   5235: 
1.167     albertel 5236: # -------------------------------------------------------------------Temp Store
                   5237: 
1.168     albertel 5238: sub tmpreset {
                   5239:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5240:   if (!$symb) {
                   5241:     $symb=&symbread();
1.620     albertel 5242:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5243:   }
                   5244:   $symb=escape($symb);
                   5245: 
1.620     albertel 5246:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5247:   $namespace=~s/\//\_/g;
                   5248:   $namespace=~s/\W//g;
                   5249: 
1.620     albertel 5250:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5251:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5252:   if ($domain eq 'public' && $stuname eq 'public') {
                   5253:       $stuname=$ENV{'REMOTE_ADDR'};
                   5254:   }
1.1117    foxr     5255:   my $path=LONCAPA::tempdir();
1.168     albertel 5256:   my %hash;
                   5257:   if (tie(%hash,'GDBM_File',
                   5258: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5259: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5260:     foreach my $key (keys(%hash)) {
1.180     albertel 5261:       if ($key=~ /:$symb/) {
1.168     albertel 5262: 	delete($hash{$key});
                   5263:       }
                   5264:     }
                   5265:   }
                   5266: }
                   5267: 
1.167     albertel 5268: sub tmpstore {
1.168     albertel 5269:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5270: 
                   5271:   if (!$symb) {
                   5272:     $symb=&symbread();
1.620     albertel 5273:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5274:   }
                   5275:   $symb=escape($symb);
                   5276: 
                   5277:   if (!$namespace) {
                   5278:     # I don't think we would ever want to store this for a course.
                   5279:     # it seems this will only be used if we don't have a course.
1.620     albertel 5280:     #$namespace=$env{'request.course.id'};
1.168     albertel 5281:     #if (!$namespace) {
1.620     albertel 5282:       $namespace=$env{'request.state'};
1.168     albertel 5283:     #}
                   5284:   }
                   5285:   $namespace=~s/\//\_/g;
                   5286:   $namespace=~s/\W//g;
1.620     albertel 5287:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5288:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5289:   if ($domain eq 'public' && $stuname eq 'public') {
                   5290:       $stuname=$ENV{'REMOTE_ADDR'};
                   5291:   }
1.168     albertel 5292:   my $now=time;
                   5293:   my %hash;
1.1117    foxr     5294:   my $path=LONCAPA::tempdir();
1.168     albertel 5295:   if (tie(%hash,'GDBM_File',
                   5296: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5297: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5298:     $hash{"version:$symb"}++;
                   5299:     my $version=$hash{"version:$symb"};
                   5300:     my $allkeys=''; 
                   5301:     foreach my $key (keys(%$storehash)) {
                   5302:       $allkeys.=$key.':';
1.591     albertel 5303:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5304:     }
                   5305:     $hash{"$version:$symb:timestamp"}=$now;
                   5306:     $allkeys.='timestamp';
                   5307:     $hash{"$version:keys:$symb"}=$allkeys;
                   5308:     if (untie(%hash)) {
                   5309:       return 'ok';
                   5310:     } else {
                   5311:       return "error:$!";
                   5312:     }
                   5313:   } else {
                   5314:     return "error:$!";
                   5315:   }
                   5316: }
1.167     albertel 5317: 
1.168     albertel 5318: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5319: 
1.168     albertel 5320: sub tmprestore {
                   5321:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5322: 
1.168     albertel 5323:   if (!$symb) {
                   5324:     $symb=&symbread();
1.620     albertel 5325:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5326:   }
                   5327:   $symb=escape($symb);
                   5328: 
1.620     albertel 5329:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5330: 
1.620     albertel 5331:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5332:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5333:   if ($domain eq 'public' && $stuname eq 'public') {
                   5334:       $stuname=$ENV{'REMOTE_ADDR'};
                   5335:   }
1.168     albertel 5336:   my %returnhash;
                   5337:   $namespace=~s/\//\_/g;
                   5338:   $namespace=~s/\W//g;
                   5339:   my %hash;
1.1117    foxr     5340:   my $path=LONCAPA::tempdir();
1.168     albertel 5341:   if (tie(%hash,'GDBM_File',
                   5342: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5343: 	  &GDBM_READER(),0640)) {
1.168     albertel 5344:     my $version=$hash{"version:$symb"};
                   5345:     $returnhash{'version'}=$version;
                   5346:     my $scope;
                   5347:     for ($scope=1;$scope<=$version;$scope++) {
                   5348:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5349:       my @keys=split(/:/,$vkeys);
                   5350:       my $key;
                   5351:       $returnhash{"$scope:keys"}=$vkeys;
                   5352:       foreach $key (@keys) {
1.591     albertel 5353: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5354: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5355:       }
                   5356:     }
1.168     albertel 5357:     if (!(untie(%hash))) {
                   5358:       return "error:$!";
                   5359:     }
                   5360:   } else {
                   5361:     return "error:$!";
                   5362:   }
                   5363:   return %returnhash;
1.167     albertel 5364: }
                   5365: 
1.9       www      5366: # ----------------------------------------------------------------------- Store
                   5367: 
                   5368: sub store {
1.1172.2.64  raeburn  5369:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5370:     my $home='';
                   5371: 
1.168     albertel 5372:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5373: 
1.213     www      5374:     $symb=&symbclean($symb);
1.122     albertel 5375:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5376: 
1.620     albertel 5377:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5378:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5379: 
                   5380:     &devalidate($symb,$stuname,$domain);
1.109     www      5381: 
                   5382:     $symb=escape($symb);
1.187     www      5383:     if (!$namespace) { 
1.620     albertel 5384:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5385:           return ''; 
                   5386:        } 
                   5387:     }
1.620     albertel 5388:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5389: 
                   5390:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5391:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5392: 
1.12      www      5393:     my $namevalue='';
1.800     albertel 5394:     foreach my $key (keys(%$storehash)) {
                   5395:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5396:     }
1.12      www      5397:     $namevalue=~s/\&$//;
1.187     www      5398:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5399:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5400: }
                   5401: 
1.47      www      5402: # -------------------------------------------------------------- Critical Store
                   5403: 
                   5404: sub cstore {
1.1172.2.64  raeburn  5405:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5406:     my $home='';
                   5407: 
1.168     albertel 5408:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5409: 
1.213     www      5410:     $symb=&symbclean($symb);
1.122     albertel 5411:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5412: 
1.620     albertel 5413:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5414:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5415: 
                   5416:     &devalidate($symb,$stuname,$domain);
1.109     www      5417: 
                   5418:     $symb=escape($symb);
1.187     www      5419:     if (!$namespace) { 
1.620     albertel 5420:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5421:           return ''; 
                   5422:        } 
                   5423:     }
1.620     albertel 5424:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5425: 
                   5426:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5427:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5428: 
1.47      www      5429:     my $namevalue='';
1.800     albertel 5430:     foreach my $key (keys(%$storehash)) {
                   5431:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5432:     }
1.47      www      5433:     $namevalue=~s/\&$//;
1.187     www      5434:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5435:     return critical
1.1172.2.64  raeburn  5436:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5437: }
                   5438: 
1.9       www      5439: # --------------------------------------------------------------------- Restore
                   5440: 
                   5441: sub restore {
1.124     www      5442:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5443:     my $home='';
                   5444: 
1.168     albertel 5445:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5446: 
1.122     albertel 5447:     if (!$symb) {
1.1172.2.26  raeburn  5448:         return if ($namespace eq 'courserequests');
                   5449:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5450:     } else {
1.1172.2.26  raeburn  5451:         unless ($namespace eq 'courserequests') {
                   5452:             $symb=&escape(&symbclean($symb));
                   5453:         }
1.122     albertel 5454:     }
1.188     www      5455:     if (!$namespace) { 
1.620     albertel 5456:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5457:           return ''; 
                   5458:        } 
                   5459:     }
1.620     albertel 5460:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5461:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5462:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5463:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5464: 
1.12      www      5465:     my %returnhash=();
1.800     albertel 5466:     foreach my $line (split(/\&/,$answer)) {
                   5467: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5468:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5469:     }
1.75      www      5470:     my $version;
                   5471:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5472:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5473:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5474:        }
1.75      www      5475:     }
1.13      www      5476:     return %returnhash;
1.34      www      5477: }
                   5478: 
                   5479: # ---------------------------------------------------------- Course Description
1.1118    foxr     5480: #
                   5481: #  
1.34      www      5482: 
                   5483: sub coursedescription {
1.731     albertel 5484:     my ($courseid,$args)=@_;
1.34      www      5485:     $courseid=~s/^\///;
1.49      www      5486:     $courseid=~s/\_/\//g;
1.34      www      5487:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5488:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5489:     my $normalid=$cdomain.'_'.$cnum;
                   5490:     # need to always cache even if we get errors otherwise we keep 
                   5491:     # trying and trying and trying to get the course description.
                   5492:     my %envhash=();
                   5493:     my %returnhash=();
1.731     albertel 5494:     
                   5495:     my $expiretime=600;
                   5496:     if ($env{'request.course.id'} eq $normalid) {
                   5497: 	$expiretime=120;
                   5498:     }
                   5499: 
                   5500:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5501:     if (!$args->{'freshen_cache'}
                   5502: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5503: 	foreach my $key (keys(%env)) {
                   5504: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5505: 	    my ($setting) = $1;
                   5506: 	    $returnhash{$setting} = $env{$key};
                   5507: 	}
                   5508: 	return %returnhash;
                   5509:     }
                   5510: 
1.1118    foxr     5511:     # get the data again
                   5512: 
1.731     albertel 5513:     if (!$args->{'one_time'}) {
                   5514: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5515:     }
1.811     albertel 5516: 
1.34      www      5517:     if ($chome ne 'no_host') {
1.302     albertel 5518:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5519:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5520: 	   my $username = $env{'user.name'}; # Defult username
                   5521: 	   if(defined $args->{'user'}) {
                   5522: 	       $username = $args->{'user'};
                   5523: 	   }
1.129     albertel 5524:            $returnhash{'home'}= $chome;
                   5525: 	   $returnhash{'domain'} = $cdomain;
                   5526: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5527:            if (!defined($returnhash{'type'})) {
                   5528:                $returnhash{'type'} = 'Course';
                   5529:            }
1.130     albertel 5530:            while (my ($name,$value) = each %returnhash) {
1.53      www      5531:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5532:            }
1.270     www      5533:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5534:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5535: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5536:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5537:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5538:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5539:        }
                   5540:     }
1.731     albertel 5541:     if (!$args->{'one_time'}) {
1.949     raeburn  5542: 	&appenv(\%envhash);
1.731     albertel 5543:     }
1.302     albertel 5544:     return %returnhash;
1.461     www      5545: }
                   5546: 
1.1080    raeburn  5547: sub update_released_required {
                   5548:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5549:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5550:         $cid = $env{'request.course.id'};
                   5551:         $cdom = $env{'course.'.$cid.'.domain'};
                   5552:         $cnum = $env{'course.'.$cid.'.num'};
                   5553:         $chome = $env{'course.'.$cid.'.home'};
                   5554:     }
                   5555:     if ($needsrelease) {
                   5556:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5557:         my $needsupdate;
                   5558:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5559:             $needsupdate = 1;
                   5560:         } else {
                   5561:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5562:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5563:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5564:                 $needsupdate = 1;
                   5565:             }
                   5566:         }
                   5567:         if ($needsupdate) {
                   5568:             my %needshash = (
                   5569:                              'internal.releaserequired' => $needsrelease,
                   5570:                             );
                   5571:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5572:             if ($putresult eq 'ok') {
                   5573:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5574:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5575:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5576:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5577:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5578:                 }
                   5579:             }
                   5580:         }
                   5581:     }
                   5582:     return;
                   5583: }
                   5584: 
1.461     www      5585: # -------------------------------------------------See if a user is privileged
                   5586: 
                   5587: sub privileged {
1.1172.2.23  raeburn  5588:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5589:     my $now = time;
1.1172.2.23  raeburn  5590:     my $roles;
                   5591:     if (ref($possroles) eq 'ARRAY') {
                   5592:         $roles = $possroles;
                   5593:     } else {
                   5594:         $roles = ['dc','su'];
                   5595:     }
                   5596:     if (ref($possdomains) eq 'ARRAY') {
                   5597:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5598:         foreach my $dom (@{$possdomains}) {
                   5599:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5600:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5601:                 foreach my $role (@{$roles}) {
                   5602:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5603:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5604:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5605:                             return 1 unless (($end && $end < $now) ||
                   5606:                                              ($start && $start > $now));
                   5607:                         }
                   5608:                     }
                   5609:                 }
                   5610:             }
                   5611:         }
                   5612:     } else {
                   5613:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5614:         my $now = time;
1.1170    droeschl 5615: 
1.1172.2.58  raeburn  5616:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5617:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5618:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5619:                 return 1 unless ($tend && $tend < $now)
                   5620:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5621:             }
1.1172.2.23  raeburn  5622:         }
                   5623:     }
1.461     www      5624:     return 0;
1.9       www      5625: }
1.1       albertel 5626: 
1.1172.2.23  raeburn  5627: sub privileged_by_domain {
                   5628:     my ($domains,$roles) = @_;
                   5629:     my %privileged = ();
                   5630:     my $cachetime = 60*60*24;
                   5631:     my $now = time;
                   5632:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5633:         return %privileged;
                   5634:     }
                   5635:     foreach my $dom (@{$domains}) {
                   5636:         next if (ref($privileged{$dom}) eq 'HASH');
                   5637:         my $needroles;
                   5638:         foreach my $role (@{$roles}) {
                   5639:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5640:             if (defined($cached)) {
                   5641:                 if (ref($result) eq 'HASH') {
                   5642:                     $privileged{$dom}{$role} = $result;
                   5643:                 }
                   5644:             } else {
                   5645:                 $needroles = 1;
                   5646:             }
                   5647:         }
                   5648:         if ($needroles) {
                   5649:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5650:             $privileged{$dom} = {};
                   5651:             foreach my $server (keys(%dompersonnel)) {
                   5652:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5653:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5654:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5655:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5656:                         next if ($end && $end < $now);
                   5657:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5658:                             $dompersonnel{$server}{$item};
                   5659:                     }
                   5660:                 }
                   5661:             }
                   5662:             if (ref($privileged{$dom}) eq 'HASH') {
                   5663:                 foreach my $role (@{$roles}) {
                   5664:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5665:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5666:                     } else {
                   5667:                         my %hash = ();
                   5668:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5669:                     }
                   5670:                 }
                   5671:             }
                   5672:         }
                   5673:     }
                   5674:     return %privileged;
                   5675: }
                   5676: 
1.103     harris41 5677: # -------------------------------------------------------- Get user privileges
1.11      www      5678: 
                   5679: sub rolesinit {
1.1169    droeschl 5680:     my ($domain, $username) = @_;
                   5681:     my %userroles = ('user.login.time' => time);
                   5682:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5683: 
                   5684:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5685:     # also, blocking can be triggered by an activating timer
                   5686:     # it's saved in the user's %env.
                   5687:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5688:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5689:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5690:         %timerintchk, %timerintenv);
                   5691: 
1.1162    raeburn  5692:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5693:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5694:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5695:     }
1.1169    droeschl 5696: 
1.1162    raeburn  5697:     foreach my $key (keys(%timerinterval)) {
                   5698:         my ($cid,$rest) = split(/\0/,$key);
                   5699:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5700:     }
1.1169    droeschl 5701: 
1.11      www      5702:     my %allroles=();
1.1162    raeburn  5703:     my %allgroups=();
1.11      www      5704: 
1.1172.2.58  raeburn  5705:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5706:         my $role = $rolesdump{$area};
                   5707:         $area =~ s/\_\w\w$//;
                   5708: 
                   5709:         my ($trole, $tend, $tstart, $group_privs);
                   5710: 
                   5711:         if ($role =~ /^cr/) {
                   5712:         # Custom role, defined by a user 
                   5713:         # e.g., user.role.cr/msu/smith/mynewrole
                   5714:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5715:                 $trole = $1;
                   5716:                 ($tend, $tstart) = split('_', $2);
                   5717:             } else {
                   5718:                 $trole = $role;
                   5719:             }
                   5720:         } elsif ($role =~ m|^gr/|) {
                   5721:         # Role of member in a group, defined within a course/community
                   5722:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5723:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5724:             next if $tstart eq '-1';
                   5725:             ($trole, $group_privs) = split(/\//, $trole);
                   5726:             $group_privs = &unescape($group_privs);
                   5727:         } else {
                   5728:         # Just a normal role, defined in roles.tab
                   5729:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5730:         }
                   5731: 
                   5732:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5733:                  $username);
                   5734:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5735: 
                   5736:         # role expired or not available yet?
                   5737:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5738:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5739: 
                   5740:         next if $area eq '' or $trole eq '';
                   5741: 
                   5742:         my $spec = "$trole.$area";
                   5743:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5744: 
                   5745:         if ($trole =~ /^cr\//) {
                   5746:         # Custom role, defined by a user
                   5747:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5748:         } elsif ($trole eq 'gr') {
                   5749:         # Role of a member in a group, defined within a course/community
                   5750:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5751:             next;
                   5752:         } else {
                   5753:         # Normal role, defined in roles.tab
                   5754:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5755:         }
                   5756: 
                   5757:         my $cid = $tdomain.'_'.$trest;
                   5758:         unless ($firstaccchk{$cid}) {
                   5759:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5760:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5761:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5762:                         $coursetimerstarts{$cid}{$item}; 
                   5763:                 }
                   5764:             }
                   5765:             $firstaccchk{$cid} = 1;
                   5766:         }
                   5767:         unless ($timerintchk{$cid}) {
                   5768:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5769:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5770:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5771:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5772:                 }
1.12      www      5773:             }
1.1169    droeschl 5774:             $timerintchk{$cid} = 1;
1.191     harris41 5775:         }
1.11      www      5776:     }
1.1169    droeschl 5777: 
1.1172.2.91  raeburn  5778:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5779:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5780:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5781:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5782: 
1.1162    raeburn  5783:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5784: }
                   5785: 
1.567     raeburn  5786: sub set_arearole {
1.1172.2.19  raeburn  5787:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5788:     unless ($nolog) {
1.567     raeburn  5789: # log the associated role with the area
1.1172.2.19  raeburn  5790:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5791:     }
1.743     albertel 5792:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5793: }
                   5794: 
                   5795: sub custom_roleprivs {
                   5796:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5797:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5798:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5799:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5800:         my ($rdummy,$roledef)=
                   5801:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5802:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5803:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5804:             if (defined($syspriv)) {
1.1043    raeburn  5805:                 if ($trest =~ /^$match_community$/) {
                   5806:                     $syspriv =~ s/bre\&S//; 
                   5807:                 }
1.567     raeburn  5808:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5809:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5810:             }
                   5811:             if ($tdomain ne '') {
                   5812:                 if (defined($dompriv)) {
                   5813:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5814:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5815:                 }
                   5816:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5817:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5818:                         my $rolename = $1;
                   5819:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5820:                     }
1.567     raeburn  5821:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5822:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5823:                 }
                   5824:             }
                   5825:         }
                   5826:     }
                   5827: }
                   5828: 
1.1172.2.89  raeburn  5829: sub course_adhocrole_privs {
                   5830:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5831:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5832:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5833:         my (%currprivs,%storeprivs);
                   5834:         foreach my $item (split(/:/,$coursepriv)) {
                   5835:             my ($priv,$restrict) = split(/\&/,$item);
                   5836:             $currprivs{$priv} = $restrict;
                   5837:         }
                   5838:         my (%possadd,%possremove,%full);
                   5839:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5840:             my ($priv,$restrict)=split(/\&/,$item);
                   5841:             $full{$priv} = $restrict;
                   5842:         }
                   5843:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5844:              next if ($item eq '');
                   5845:              my ($rule,$rest) = split(/=/,$item);
                   5846:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5847:              foreach my $priv (split(/:/,$rest)) {
                   5848:                  if ($priv ne '') {
                   5849:                      if ($rule eq 'off') {
                   5850:                          $possremove{$priv} = 1;
                   5851:                      } else {
                   5852:                          $possadd{$priv} = 1;
                   5853:                      }
                   5854:                  }
                   5855:              }
                   5856:          }
                   5857:          foreach my $priv (sort(keys(%full))) {
                   5858:              if (exists($currprivs{$priv})) {
                   5859:                  unless (exists($possremove{$priv})) {
                   5860:                      $storeprivs{$priv} = $currprivs{$priv};
                   5861:                  }
                   5862:              } elsif (exists($possadd{$priv})) {
                   5863:                  $storeprivs{$priv} = $full{$priv};
                   5864:              }
                   5865:          }
                   5866:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5867:      }
                   5868:      return $coursepriv;
                   5869: }
                   5870: 
1.678     raeburn  5871: sub group_roleprivs {
                   5872:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5873:     my $access = 1;
                   5874:     my $now = time;
                   5875:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5876:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5877:     if ($access) {
1.811     albertel 5878:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5879:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5880:     }
                   5881: }
1.567     raeburn  5882: 
                   5883: sub standard_roleprivs {
                   5884:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5885:     if (defined($pr{$trole.':s'})) {
                   5886:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5887:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5888:     }
                   5889:     if ($tdomain ne '') {
                   5890:         if (defined($pr{$trole.':d'})) {
                   5891:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5892:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5893:         }
                   5894:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5895:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5896:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5897:         }
                   5898:     }
                   5899: }
                   5900: 
                   5901: sub set_userprivs {
1.1064    raeburn  5902:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5903:     my $author=0;
                   5904:     my $adv=0;
1.1172.2.91  raeburn  5905:     my $rar=0;
1.678     raeburn  5906:     my %grouproles = ();
                   5907:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5908:         my @groupkeys; 
1.1000    raeburn  5909:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5910:             push(@groupkeys,$role);
                   5911:         }
                   5912:         if (ref($groups_roles) eq 'HASH') {
                   5913:             foreach my $key (keys(%{$groups_roles})) {
                   5914:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5915:                     push(@groupkeys,$key);
                   5916:                 }
                   5917:             }
                   5918:         }
                   5919:         if (@groupkeys > 0) {
                   5920:             foreach my $role (@groupkeys) {
                   5921:                 my ($trole,$area,$sec,$extendedarea);
                   5922:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5923:                     $trole = $1;
                   5924:                     $area = $2;
                   5925:                     $sec = $3;
                   5926:                     $extendedarea = $area.$sec;
                   5927:                     if (exists($$allgroups{$area})) {
                   5928:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5929:                             my $spec = $trole.'.'.$extendedarea;
                   5930:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5931:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5932:                         }
1.678     raeburn  5933:                     }
                   5934:                 }
                   5935:             }
                   5936:         }
                   5937:     }
1.800     albertel 5938:     foreach my $group (keys(%grouproles)) {
                   5939:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5940:     }
1.800     albertel 5941:     foreach my $role (keys(%{$allroles})) {
                   5942:         my %thesepriv;
1.941     raeburn  5943:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5944:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5945:             if ($item ne '') {
                   5946:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5947:                 if ($restrictions eq '') {
                   5948:                     $thesepriv{$privilege}='F';
                   5949:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5950:                     $thesepriv{$privilege}.=$restrictions;
                   5951:                 }
                   5952:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5953:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5954:             }
                   5955:         }
                   5956:         my $thesestr='';
1.1104    raeburn  5957:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5958: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5959: 	}
                   5960:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5961:     }
1.1172.2.91  raeburn  5962:     return ($author,$adv,$rar);
1.567     raeburn  5963: }
                   5964: 
1.994     raeburn  5965: sub role_status {
1.1104    raeburn  5966:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5967:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5968:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5969:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5970:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5971:             $$where = '/'.$two;
1.994     raeburn  5972:             $$trolecode=$$role.'.'.$$where;
                   5973:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5974:             $$tstatus='is';
1.1104    raeburn  5975:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5976:                 $$tstatus='future';
1.1034    raeburn  5977:                 if ($$tstart<$now) {
                   5978:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5979:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5980:                             my (%allroles,%allgroups,$group_privs,
                   5981:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5982:                             my %userroles = (
                   5983:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5984:                             );
1.1064    raeburn  5985:                             @rolecodes = ('cm'); 
1.1002    raeburn  5986:                             my $spec=$$role.'.'.$$where;
                   5987:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5988:                             if ($$role =~ /^cr\//) {
                   5989:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5990:                                 push(@rolecodes,'cr');
1.1002    raeburn  5991:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5992:                                 push(@rolecodes,$$role);
1.1002    raeburn  5993:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5994:                                                     $env{'user.name'});
1.1064    raeburn  5995:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5996:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5997:                                 $group_privs = &unescape($group_privs);
                   5998:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5999:                                 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  6000:                                 &get_groups_roles($tdomain,$trest,
                   6001:                                                   \%course_roles,\@rolecodes,
                   6002:                                                   \%groups_roles);
1.1002    raeburn  6003:                             } else {
1.1064    raeburn  6004:                                 push(@rolecodes,$$role);
1.1002    raeburn  6005:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6006:                             }
1.1172.2.91  raeburn  6007:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6008:                                                                    \%groups_roles);
1.1064    raeburn  6009:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6010:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6011:                         }
                   6012:                     }
1.1034    raeburn  6013:                     $$tstatus = 'is';
1.1002    raeburn  6014:                 }
1.994     raeburn  6015:             }
                   6016:             if ($$tend) {
1.1104    raeburn  6017:                 if ($$tend<$update) {
1.994     raeburn  6018:                     $$tstatus='expired';
                   6019:                 } elsif ($$tend<$now) {
                   6020:                     $$tstatus='will_not';
                   6021:                 }
                   6022:             }
                   6023:         }
                   6024:     }
                   6025: }
                   6026: 
1.1104    raeburn  6027: sub get_groups_roles {
                   6028:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6029:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6030:                   (ref($rolecodes) eq 'ARRAY') && 
                   6031:                   (ref($groups_roles) eq 'HASH')); 
                   6032:     if (keys(%{$cdom_courseroles}) > 0) {
                   6033:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6034:         if ($cdom ne '' && $cnum ne '') {
                   6035:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6036:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6037:                     my $crsrole = $1;
                   6038:                     my $crssec = $2;
                   6039:                     if ($crsrole =~ /^cr/) {
                   6040:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6041:                             push(@{$rolecodes},'cr');
                   6042:                         }
                   6043:                     } else {
                   6044:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6045:                             push(@{$rolecodes},$crsrole);
                   6046:                         }
                   6047:                     }
                   6048:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6049:                     if ($crssec ne '') {
                   6050:                         $rolekey .= "/$crssec";
                   6051:                     }
                   6052:                     $rolekey .= './';
                   6053:                     $groups_roles->{$rolekey} = $rolecodes;
                   6054:                 }
                   6055:             }
                   6056:         }
                   6057:     }
                   6058:     return;
                   6059: }
                   6060: 
                   6061: sub delete_env_groupprivs {
                   6062:     my ($where,$courseroles,$possroles) = @_;
                   6063:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6064:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6065:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6066:         %{$courseroles->{$udom}} =
                   6067:             &get_my_roles('','','userroles',['active'],
                   6068:                           $possroles,[$udom],1);
                   6069:     }
                   6070:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6071:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6072:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6073:             my $area = '/'.$cdom.'/'.$cnum;
                   6074:             my $privkey = "user.priv.$crsrole.$area";
                   6075:             if ($crssec ne '') {
                   6076:                 $privkey .= '/'.$crssec;
                   6077:             }
                   6078:             $privkey .= ".$area/$group";
                   6079:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6080:         }
                   6081:     }
                   6082:     return;
                   6083: }
                   6084: 
1.994     raeburn  6085: sub check_adhoc_privs {
1.1172.2.86  raeburn  6086:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6087:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6088:     if ($sec) {
                   6089:         $cckey .= '/'.$sec;
                   6090:     }
1.1172.2.9  raeburn  6091:     my $setprivs;
1.994     raeburn  6092:     if ($env{$cckey}) {
                   6093:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6094:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6095:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6096:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6097:             $setprivs = 1;
1.994     raeburn  6098:         }
                   6099:     } else {
1.1172.2.87  raeburn  6100:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6101:         $setprivs = 1;
1.994     raeburn  6102:     }
1.1172.2.9  raeburn  6103:     return $setprivs;
1.994     raeburn  6104: }
                   6105: 
                   6106: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6107: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6108:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6109:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6110:     if ($sec ne '') {
                   6111:         $area .= '/'.$sec;
                   6112:     }
1.994     raeburn  6113:     my $spec = $role.'.'.$area;
                   6114:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6115:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6116:     my %rolehash = ();
1.1172.2.89  raeburn  6117:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6118:         my $rolename = $1;
1.1172.2.84  raeburn  6119:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6120:         my %domdef = &get_domain_defaults($dcdom);
                   6121:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6122:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6123:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6124:             }
                   6125:         }
1.1172.2.84  raeburn  6126:     } else {
                   6127:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6128:     }
1.1172.2.91  raeburn  6129:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6130:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6132:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6133:         &appenv( {'request.role'        => $spec,
                   6134:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6135:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6136:                  }
                   6137:                );
                   6138:         my $tadv=0;
                   6139:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6140:         &appenv({'request.role.adv'    => $tadv});
                   6141:     }
1.994     raeburn  6142: }
                   6143: 
1.12      www      6144: # --------------------------------------------------------------- get interface
                   6145: 
                   6146: sub get {
1.131     albertel 6147:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6148:    my $items='';
1.800     albertel 6149:    foreach my $item (@$storearr) {
                   6150:        $items.=&escape($item).'&';
1.191     harris41 6151:    }
1.12      www      6152:    $items=~s/\&$//;
1.620     albertel 6153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6154:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6155:    my $uhome=&homeserver($uname,$udomain);
                   6156: 
1.133     albertel 6157:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6158:    my @pairs=split(/\&/,$rep);
1.273     albertel 6159:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6160:      return @pairs;
                   6161:    }
1.15      www      6162:    my %returnhash=();
1.42      www      6163:    my $i=0;
1.800     albertel 6164:    foreach my $item (@$storearr) {
                   6165:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6166:       $i++;
1.191     harris41 6167:    }
1.15      www      6168:    return %returnhash;
1.27      www      6169: }
                   6170: 
                   6171: # --------------------------------------------------------------- del interface
                   6172: 
                   6173: sub del {
1.133     albertel 6174:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6175:    my $items='';
1.800     albertel 6176:    foreach my $item (@$storearr) {
                   6177:        $items.=&escape($item).'&';
1.191     harris41 6178:    }
1.984     neumanie 6179: 
1.27      www      6180:    $items=~s/\&$//;
1.620     albertel 6181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6182:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6183:    my $uhome=&homeserver($uname,$udomain);
                   6184:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6185: }
                   6186: 
                   6187: # -------------------------------------------------------------- dump interface
                   6188: 
1.1172.2.22  raeburn  6189: sub unserialize {
                   6190:     my ($rep, $escapedkeys) = @_;
                   6191: 
                   6192:     return {} if $rep =~ /^error/;
                   6193: 
                   6194:     my %returnhash=();
                   6195:     foreach my $item (split(/\&/,$rep)) {
                   6196:         my ($key, $value) = split(/=/, $item, 2);
                   6197:         $key = unescape($key) unless $escapedkeys;
                   6198:         next if $key =~ /^error: 2 /;
                   6199:         $returnhash{$key} = &thaw_unescape($value);
                   6200:     }
                   6201:     return \%returnhash;
                   6202: }
                   6203: 
                   6204: # see Lond::dump_with_regexp
                   6205: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6206: sub dump {
1.1172.2.22  raeburn  6207:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6208:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6209:     if (!$uname) { $uname=$env{'user.name'}; }
                   6210:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6211: 
1.1172.2.55  raeburn  6212:     if ($regexp) {
                   6213:         $regexp=&escape($regexp);
                   6214:     } else {
                   6215:         $regexp='.';
                   6216:     }
1.1172.2.22  raeburn  6217:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6218:         # user is hosted on this machine
1.1172.2.55  raeburn  6219:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6220:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6221:         return %{&unserialize($reply, $escapedkeys)};
                   6222:     }
1.1166    raeburn  6223:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6224:     my @pairs=split(/\&/,$rep);
                   6225:     my %returnhash=();
1.1098    foxr     6226:     if (!($rep =~ /^error/ )) {
                   6227: 	foreach my $item (@pairs) {
                   6228: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6229:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6230: 	    next if ($key =~ /^error: 2 /);
                   6231: 	    $returnhash{$key}=&thaw_unescape($value);
                   6232: 	}
1.755     albertel 6233:     }
                   6234:     return %returnhash;
1.407     www      6235: }
                   6236: 
1.1098    foxr     6237: 
1.717     albertel 6238: # --------------------------------------------------------- dumpstore interface
                   6239: 
                   6240: sub dumpstore {
                   6241:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6242:    # same as dump but keys must be escaped. They may contain colon separated
                   6243:    # lists of values that may themself contain colons (e.g. symbs).
                   6244:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6245: }
                   6246: 
1.407     www      6247: # -------------------------------------------------------------- keys interface
                   6248: 
                   6249: sub getkeys {
                   6250:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6252:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6253:    my $uhome=&homeserver($uname,$udomain);
                   6254:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6255:    my @keyarray=();
1.800     albertel 6256:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6257:       next if ($key =~ /^error: 2 /);
1.800     albertel 6258:       push(@keyarray,&unescape($key));
1.407     www      6259:    }
                   6260:    return @keyarray;
1.318     matthew  6261: }
                   6262: 
1.319     matthew  6263: # --------------------------------------------------------------- currentdump
                   6264: sub currentdump {
1.328     matthew  6265:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6266:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6267:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6268:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6269:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6270:    my $rep;
                   6271: 
                   6272:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6273:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6274:                    $courseid)));
                   6275:    } else {
                   6276:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6277:    }
                   6278: 
1.318     matthew  6279:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6280:    #
1.318     matthew  6281:    my %returnhash=();
1.319     matthew  6282:    #
                   6283:    if ($rep eq "unknown_cmd") { 
                   6284:        # an old lond will not know currentdump
                   6285:        # Do a dump and make it look like a currentdump
1.822     albertel 6286:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6287:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6288:        my %hash = @tmp;
                   6289:        @tmp=();
1.424     matthew  6290:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6291:    } else {
                   6292:        my @pairs=split(/\&/,$rep);
1.800     albertel 6293:        foreach my $pair (@pairs) {
                   6294:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6295:            my ($symb,$param) = split(/:/,$key);
                   6296:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6297:                                                         &thaw_unescape($value);
1.319     matthew  6298:        }
1.191     harris41 6299:    }
1.12      www      6300:    return %returnhash;
1.424     matthew  6301: }
                   6302: 
                   6303: sub convert_dump_to_currentdump{
                   6304:     my %hash = %{shift()};
                   6305:     my %returnhash;
                   6306:     # Code ripped from lond, essentially.  The only difference
                   6307:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6308:     # we might run in to problems with parameter names =~ /^v\./
                   6309:     while (my ($key,$value) = each(%hash)) {
                   6310:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6311: 	$symb  = &unescape($symb);
                   6312: 	$param = &unescape($param);
1.424     matthew  6313:         next if ($v eq 'version' || $symb eq 'keys');
                   6314:         next if (exists($returnhash{$symb}) &&
                   6315:                  exists($returnhash{$symb}->{$param}) &&
                   6316:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6317:         $returnhash{$symb}->{$param}=$value;
                   6318:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6319:     }
                   6320:     #
                   6321:     # Remove all of the keys in the hashes which keep track of
                   6322:     # the version of the parameter.
                   6323:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6324:         # use a foreach because we are going to delete from the hash.
                   6325:         foreach my $key (keys(%$param_hash)) {
                   6326:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6327:         }
                   6328:     }
                   6329:     return \%returnhash;
1.12      www      6330: }
                   6331: 
1.627     albertel 6332: # ------------------------------------------------------ critical inc interface
                   6333: 
                   6334: sub cinc {
                   6335:     return &inc(@_,'critical');
                   6336: }
                   6337: 
1.449     matthew  6338: # --------------------------------------------------------------- inc interface
                   6339: 
                   6340: sub inc {
1.627     albertel 6341:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6342:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6343:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6344:     my $uhome=&homeserver($uname,$udomain);
                   6345:     my $items='';
                   6346:     if (! ref($store)) {
                   6347:         # got a single value, so use that instead
                   6348:         $items = &escape($store).'=&';
                   6349:     } elsif (ref($store) eq 'SCALAR') {
                   6350:         $items = &escape($$store).'=&';        
                   6351:     } elsif (ref($store) eq 'ARRAY') {
                   6352:         $items = join('=&',map {&escape($_);} @{$store});
                   6353:     } elsif (ref($store) eq 'HASH') {
                   6354:         while (my($key,$value) = each(%{$store})) {
                   6355:             $items.= &escape($key).'='.&escape($value).'&';
                   6356:         }
                   6357:     }
                   6358:     $items=~s/\&$//;
1.627     albertel 6359:     if ($critical) {
                   6360: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6361:     } else {
                   6362: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6363:     }
1.449     matthew  6364: }
                   6365: 
1.12      www      6366: # --------------------------------------------------------------- put interface
                   6367: 
                   6368: sub put {
1.134     albertel 6369:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6370:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6371:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6372:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6373:    my $items='';
1.800     albertel 6374:    foreach my $item (keys(%$storehash)) {
                   6375:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6376:    }
1.12      www      6377:    $items=~s/\&$//;
1.134     albertel 6378:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6379: }
                   6380: 
1.631     albertel 6381: # ------------------------------------------------------------ newput interface
                   6382: 
                   6383: sub newput {
                   6384:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6385:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6386:    if (!$uname) { $uname=$env{'user.name'}; }
                   6387:    my $uhome=&homeserver($uname,$udomain);
                   6388:    my $items='';
                   6389:    foreach my $key (keys(%$storehash)) {
                   6390:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6391:    }
                   6392:    $items=~s/\&$//;
                   6393:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6394: }
                   6395: 
                   6396: # ---------------------------------------------------------  putstore interface
                   6397: 
1.524     raeburn  6398: sub putstore {
1.1172.2.59  raeburn  6399:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6401:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6402:    my $uhome=&homeserver($uname,$udomain);
                   6403:    my $items='';
1.715     albertel 6404:    foreach my $key (keys(%$storehash)) {
                   6405:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6406:    }
1.715     albertel 6407:    $items=~s/\&$//;
1.716     albertel 6408:    my $esc_symb=&escape($symb);
                   6409:    my $esc_v=&escape($version);
1.715     albertel 6410:    my $reply =
1.716     albertel 6411:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6412: 	      $uhome);
1.1172.2.59  raeburn  6413:    if (($tolog) && ($reply eq 'ok')) {
                   6414:        my $namevalue='';
                   6415:        foreach my $key (keys(%{$storehash})) {
                   6416:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6417:        }
                   6418:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6419:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6420:                      '&version='.$esc_v.
                   6421:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6422:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6423:    }
1.715     albertel 6424:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6425:        # gfall back to way things use to be done
1.715     albertel 6426:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6427: 			    $uname);
1.524     raeburn  6428:    }
1.715     albertel 6429:    return $reply;
                   6430: }
                   6431: 
                   6432: sub old_putstore {
1.716     albertel 6433:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6434:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6435:     if (!$uname) { $uname=$env{'user.name'}; }
                   6436:     my $uhome=&homeserver($uname,$udomain);
                   6437:     my %newstorehash;
1.800     albertel 6438:     foreach my $item (keys(%$storehash)) {
                   6439: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6440: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6441:     }
                   6442:     my $items='';
                   6443:     my %allitems = ();
1.800     albertel 6444:     foreach my $item (keys(%newstorehash)) {
                   6445: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6446: 	    my $key = $1.':keys:'.$2;
                   6447: 	    $allitems{$key} .= $3.':';
                   6448: 	}
1.800     albertel 6449: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6450:     }
1.800     albertel 6451:     foreach my $item (keys(%allitems)) {
                   6452: 	$allitems{$item} =~ s/\:$//;
                   6453: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6454:     }
                   6455:     $items=~s/\&$//;
                   6456:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6457: }
                   6458: 
1.47      www      6459: # ------------------------------------------------------ critical put interface
                   6460: 
                   6461: sub cput {
1.134     albertel 6462:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6463:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6464:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6465:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6466:    my $items='';
1.800     albertel 6467:    foreach my $item (keys(%$storehash)) {
                   6468:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6469:    }
1.47      www      6470:    $items=~s/\&$//;
1.134     albertel 6471:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6472: }
                   6473: 
                   6474: # -------------------------------------------------------------- eget interface
                   6475: 
                   6476: sub eget {
1.133     albertel 6477:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6478:    my $items='';
1.800     albertel 6479:    foreach my $item (@$storearr) {
                   6480:        $items.=&escape($item).'&';
1.191     harris41 6481:    }
1.12      www      6482:    $items=~s/\&$//;
1.620     albertel 6483:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6484:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6485:    my $uhome=&homeserver($uname,$udomain);
                   6486:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6487:    my @pairs=split(/\&/,$rep);
                   6488:    my %returnhash=();
1.42      www      6489:    my $i=0;
1.800     albertel 6490:    foreach my $item (@$storearr) {
                   6491:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6492:       $i++;
1.191     harris41 6493:    }
1.12      www      6494:    return %returnhash;
                   6495: }
                   6496: 
1.667     albertel 6497: # ------------------------------------------------------------ tmpput interface
                   6498: sub tmpput {
1.802     raeburn  6499:     my ($storehash,$server,$context)=@_;
1.667     albertel 6500:     my $items='';
1.800     albertel 6501:     foreach my $item (keys(%$storehash)) {
                   6502: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6503:     }
                   6504:     $items=~s/\&$//;
1.802     raeburn  6505:     if (defined($context)) {
                   6506:         $items .= ':'.&escape($context);
                   6507:     }
1.667     albertel 6508:     return &reply("tmpput:$items",$server);
                   6509: }
                   6510: 
                   6511: # ------------------------------------------------------------ tmpget interface
                   6512: sub tmpget {
1.688     albertel 6513:     my ($token,$server)=@_;
                   6514:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6515:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6516:     my %returnhash;
1.1172.2.85  raeburn  6517:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6518:         return %returnhash;
                   6519:     }
1.667     albertel 6520:     foreach my $item (split(/\&/,$rep)) {
                   6521: 	my ($key,$value)=split(/=/,$item);
                   6522: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6523:     }
                   6524:     return %returnhash;
                   6525: }
                   6526: 
1.1113    raeburn  6527: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6528: sub tmpdel {
                   6529:     my ($token,$server)=@_;
                   6530:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6531:     return &reply("tmpdel:$token",$server);
                   6532: }
                   6533: 
1.1172.2.13  raeburn  6534: # ------------------------------------------------------------ get_timebased_id
                   6535: 
                   6536: sub get_timebased_id {
                   6537:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6538:         $maxtries) = @_;
                   6539:     my ($newid,$error,$dellock);
                   6540:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6541:         return ('','ok','invalid call to get suffix');
                   6542:     }
                   6543: 
                   6544: # set defaults for any optional args for which values were not supplied
                   6545:     if ($who eq '') {
                   6546:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6547:     }
                   6548:     if (!$locktries) {
                   6549:         $locktries = 3;
                   6550:     }
                   6551:     if (!$maxtries) {
                   6552:         $maxtries = 10;
                   6553:     }
                   6554: 
                   6555:     if (($cdom eq '') || ($cnum eq '')) {
                   6556:         if ($env{'request.course.id'}) {
                   6557:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6558:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6559:         }
                   6560:         if (($cdom eq '') || ($cnum eq '')) {
                   6561:             return ('','ok','call to get suffix not in course context');
                   6562:         }
                   6563:     }
                   6564: 
                   6565: # construct locking item
                   6566:     my $lockhash = {
                   6567:                       $prefix."\0".'locked_'.$keyid => $who,
                   6568:                    };
                   6569:     my $tries = 0;
                   6570: 
                   6571: # attempt to get lock on nohist_$namespace file
                   6572:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6573:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6574:         $tries ++;
                   6575:         sleep 1;
                   6576:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6577:     }
                   6578: 
                   6579: # attempt to get unique identifier, based on current timestamp
                   6580:     if ($gotlock eq 'ok') {
                   6581:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6582:         my $id = time;
                   6583:         $newid = $id;
1.1172.2.56  raeburn  6584:         if ($idtype eq 'addcode') {
                   6585:             $newid .= &sixnum_code();
                   6586:         }
1.1172.2.13  raeburn  6587:         my $idtries = 0;
                   6588:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6589:             if ($idtype eq 'concat') {
                   6590:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6591:             } elsif ($idtype eq 'addcode') {
                   6592:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6593:             } else {
                   6594:                 $newid ++;
                   6595:             }
                   6596:             $idtries ++;
                   6597:         }
                   6598:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6599:             my %new_item =  (
                   6600:                               $prefix."\0".$newid => $who,
                   6601:                             );
                   6602:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6603:                                                  $cdom,$cnum);
                   6604:             if ($putresult ne 'ok') {
                   6605:                 undef($newid);
                   6606:                 $error = 'error saving new item: '.$putresult;
                   6607:             }
                   6608:         } else {
1.1172.2.56  raeburn  6609:              undef($newid);
1.1172.2.13  raeburn  6610:              $error = ('error: no unique suffix available for the new item ');
                   6611:         }
                   6612: #  remove lock
                   6613:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6614:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6615:     } else {
                   6616:         $error = "error: could not obtain lockfile\n";
                   6617:         $dellock = 'ok';
1.1172.2.58  raeburn  6618:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6619:             $dellock = 'nolock';
                   6620:         }
1.1172.2.13  raeburn  6621:     }
                   6622:     return ($newid,$dellock,$error);
                   6623: }
                   6624: 
1.1172.2.56  raeburn  6625: sub sixnum_code {
                   6626:     my $code;
                   6627:     for (0..6) {
                   6628:         $code .= int( rand(9) );
                   6629:     }
                   6630:     return $code;
                   6631: }
                   6632: 
1.765     albertel 6633: # -------------------------------------------------- portfolio access checking
                   6634: 
                   6635: sub portfolio_access {
1.1172.2.77  raeburn  6636:     my ($requrl,$clientip) = @_;
1.765     albertel 6637:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6638:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6639:     if ($result) {
                   6640:         my %setters;
                   6641:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6642:             my ($startblock,$endblock) =
                   6643:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6644:             if ($startblock && $endblock) {
                   6645:                 return 'B';
                   6646:             }
                   6647:         } else {
                   6648:             my ($startblock,$endblock) =
                   6649:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6650:             if ($startblock && $endblock) {
                   6651:                 return 'B';
                   6652:             }
                   6653:         }
                   6654:     }
1.765     albertel 6655:     if ($result eq 'ok') {
1.766     albertel 6656:        return 'F';
1.765     albertel 6657:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6658:        return 'A';
1.765     albertel 6659:     }
1.766     albertel 6660:     return '';
1.765     albertel 6661: }
                   6662: 
                   6663: sub get_portfolio_access {
1.1172.2.77  raeburn  6664:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6665: 
                   6666:     if (!ref($access_hash)) {
                   6667: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6668: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6669: 						   $file_name);
                   6670: 	$access_hash = $access_controls{$file_name};
                   6671:     }
                   6672: 
1.1172.2.77  raeburn  6673:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6674:     my $now = time;
                   6675:     if (ref($access_hash) eq 'HASH') {
                   6676:         foreach my $key (keys(%{$access_hash})) {
                   6677:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6678:             if ($start > $now) {
                   6679:                 next;
                   6680:             }
                   6681:             if ($end && $end<$now) {
                   6682:                 next;
                   6683:             }
                   6684:             if ($scope eq 'public') {
                   6685:                 $public = $key;
                   6686:                 last;
                   6687:             } elsif ($scope eq 'guest') {
                   6688:                 $guest = $key;
                   6689:             } elsif ($scope eq 'domains') {
                   6690:                 push(@domains,$key);
                   6691:             } elsif ($scope eq 'users') {
                   6692:                 push(@users,$key);
                   6693:             } elsif ($scope eq 'course') {
                   6694:                 push(@courses,$key);
                   6695:             } elsif ($scope eq 'group') {
                   6696:                 push(@groups,$key);
1.1172.2.77  raeburn  6697:             } elsif ($scope eq 'ip') {
                   6698:                 push(@ips,$key);
1.765     albertel 6699:             }
                   6700:         }
                   6701:         if ($public) {
                   6702:             return 'ok';
1.1172.2.77  raeburn  6703:         } elsif (@ips > 0) {
                   6704:             my $allowed;
                   6705:             foreach my $ipkey (@ips) {
                   6706:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6707:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6708:                         $allowed = 1;
                   6709:                         last;
                   6710:                     }
                   6711:                 }
                   6712:             }
                   6713:             if ($allowed) {
                   6714:                 return 'ok';
                   6715:             }
1.765     albertel 6716:         }
                   6717:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6718:             if ($guest) {
                   6719:                 return $guest;
                   6720:             }
                   6721:         } else {
                   6722:             if (@domains > 0) {
                   6723:                 foreach my $domkey (@domains) {
                   6724:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6725:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6726:                             return 'ok';
                   6727:                         }
                   6728:                     }
                   6729:                 }
                   6730:             }
                   6731:             if (@users > 0) {
                   6732:                 foreach my $userkey (@users) {
1.865     raeburn  6733:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6734:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6735:                             if (ref($item) eq 'HASH') {
                   6736:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6737:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6738:                                     return 'ok';
                   6739:                                 }
                   6740:                             }
                   6741:                         }
                   6742:                     } 
1.765     albertel 6743:                 }
                   6744:             }
                   6745:             my %roleshash;
                   6746:             my @courses_and_groups = @courses;
                   6747:             push(@courses_and_groups,@groups); 
                   6748:             if (@courses_and_groups > 0) {
                   6749:                 my (%allgroups,%allroles); 
                   6750:                 my ($start,$end,$role,$sec,$group);
                   6751:                 foreach my $envkey (%env) {
1.1060    raeburn  6752:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6753:                         my $cid = $2.'_'.$3; 
                   6754:                         if ($1 eq 'gr') {
                   6755:                             $group = $4;
                   6756:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6757:                         } else {
                   6758:                             if ($4 eq '') {
                   6759:                                 $sec = 'none';
                   6760:                             } else {
                   6761:                                 $sec = $4;
                   6762:                             }
                   6763:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6764:                         }
1.811     albertel 6765:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6766:                         my $cid = $2.'_'.$3;
                   6767:                         if ($4 eq '') {
                   6768:                             $sec = 'none';
                   6769:                         } else {
                   6770:                             $sec = $4;
                   6771:                         }
                   6772:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6773:                     }
                   6774:                 }
                   6775:                 if (keys(%allroles) == 0) {
                   6776:                     return;
                   6777:                 }
                   6778:                 foreach my $key (@courses_and_groups) {
                   6779:                     my %content = %{$$access_hash{$key}};
                   6780:                     my $cnum = $content{'number'};
                   6781:                     my $cdom = $content{'domain'};
                   6782:                     my $cid = $cdom.'_'.$cnum;
                   6783:                     if (!exists($allroles{$cid})) {
                   6784:                         next;
                   6785:                     }    
                   6786:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6787:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6788:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6789:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6790:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6791:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6792:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6793:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6794:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6795:                                         if (grep/^all$/,@sections) {
                   6796:                                             return 'ok';
                   6797:                                         } else {
                   6798:                                             if (grep/^$sec$/,@sections) {
                   6799:                                                 return 'ok';
                   6800:                                             }
                   6801:                                         }
                   6802:                                     }
                   6803:                                 }
                   6804:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6805:                                     if (grep/^none$/,@groups) {
                   6806:                                         return 'ok';
                   6807:                                     }
                   6808:                                 } else {
                   6809:                                     if (grep/^all$/,@groups) {
                   6810:                                         return 'ok';
                   6811:                                     } 
                   6812:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6813:                                         if (grep/^$group$/,@groups) {
                   6814:                                             return 'ok';
                   6815:                                         }
                   6816:                                     }
                   6817:                                 } 
                   6818:                             }
                   6819:                         }
                   6820:                     }
                   6821:                 }
                   6822:             }
                   6823:             if ($guest) {
                   6824:                 return $guest;
                   6825:             }
                   6826:         }
                   6827:     }
                   6828:     return;
                   6829: }
                   6830: 
                   6831: sub course_group_datechecker {
                   6832:     my ($dates,$now,$status) = @_;
                   6833:     my ($start,$end) = split(/\./,$dates);
                   6834:     if (!$start && !$end) {
                   6835:         return 'ok';
                   6836:     }
                   6837:     if (grep/^active$/,@{$status}) {
                   6838:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6839:             return 'ok';
                   6840:         }
                   6841:     }
                   6842:     if (grep/^previous$/,@{$status}) {
                   6843:         if ($end > $now ) {
                   6844:             return 'ok';
                   6845:         }
                   6846:     }
                   6847:     if (grep/^future$/,@{$status}) {
                   6848:         if ($start > $now) {
                   6849:             return 'ok';
                   6850:         }
                   6851:     }
                   6852:     return; 
                   6853: }
                   6854: 
                   6855: sub parse_portfolio_url {
                   6856:     my ($url) = @_;
                   6857: 
                   6858:     my ($type,$udom,$unum,$group,$file_name);
                   6859:     
1.823     albertel 6860:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6861: 	$type = 1;
                   6862:         $udom = $1;
                   6863:         $unum = $2;
                   6864:         $file_name = $3;
1.823     albertel 6865:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6866: 	$type = 2;
                   6867:         $udom = $1;
                   6868:         $unum = $2;
                   6869:         $group = $3;
                   6870:         $file_name = $3.'/'.$4;
                   6871:     }
                   6872:     if (wantarray) {
                   6873: 	return ($type,$udom,$unum,$file_name,$group);
                   6874:     }
                   6875:     return $type;
                   6876: }
                   6877: 
                   6878: sub is_portfolio_url {
                   6879:     my ($url) = @_;
                   6880:     return scalar(&parse_portfolio_url($url));
                   6881: }
                   6882: 
1.798     raeburn  6883: sub is_portfolio_file {
                   6884:     my ($file) = @_;
1.820     raeburn  6885:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6886:         return 1;
                   6887:     }
                   6888:     return;
                   6889: }
                   6890: 
1.976     raeburn  6891: sub usertools_access {
1.1084    raeburn  6892:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6893:     my ($access,%tools);
                   6894:     if ($context eq '') {
                   6895:         $context = 'tools';
                   6896:     }
                   6897:     if ($context eq 'requestcourses') {
                   6898:         %tools = (
                   6899:                       official   => 1,
                   6900:                       unofficial => 1,
1.1006    raeburn  6901:                       community  => 1,
1.1172.2.37  raeburn  6902:                       textbook   => 1,
1.985     raeburn  6903:                  );
1.1172.2.9  raeburn  6904:     } elsif ($context eq 'requestauthor') {
                   6905:         %tools = (
                   6906:                       requestauthor => 1,
                   6907:                  );
1.985     raeburn  6908:     } else {
                   6909:         %tools = (
                   6910:                       aboutme   => 1,
                   6911:                       blog      => 1,
1.1172.2.6  raeburn  6912:                       webdav    => 1,
1.985     raeburn  6913:                       portfolio => 1,
                   6914:                  );
                   6915:     }
1.976     raeburn  6916:     return if (!defined($tools{$tool}));
                   6917: 
1.1172.2.35  raeburn  6918:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6919:         $udom = $env{'user.domain'};
                   6920:         $uname = $env{'user.name'};
                   6921:     }
                   6922: 
1.978     raeburn  6923:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6924:         if ($action ne 'reload') {
1.985     raeburn  6925:             if ($context eq 'requestcourses') {
                   6926:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6927:             } elsif ($context eq 'requestauthor') {
                   6928:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6929:             } else {
                   6930:                 return $env{'environment.availabletools.'.$tool};
                   6931:             }
                   6932:         }
1.976     raeburn  6933:     }
                   6934: 
1.1172.2.9  raeburn  6935:     my ($toolstatus,$inststatus,$envkey);
                   6936:     if ($context eq 'requestauthor') {
                   6937:         $envkey = $context;
                   6938:     } else {
                   6939:         $envkey = $context.'.'.$tool;
                   6940:     }
1.976     raeburn  6941: 
1.985     raeburn  6942:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6943:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6944:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6945:         $inststatus = $env{'environment.inststatus'};
                   6946:     } else {
1.1084    raeburn  6947:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6948:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6949:             $inststatus = $userenvref->{'inststatus'};
                   6950:         } else {
1.1172.2.9  raeburn  6951:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6952:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6953:             $inststatus = $userenv{'inststatus'};
                   6954:         }
1.976     raeburn  6955:     }
                   6956: 
                   6957:     if ($toolstatus ne '') {
                   6958:         if ($toolstatus) {
                   6959:             $access = 1;
                   6960:         } else {
                   6961:             $access = 0;
                   6962:         }
                   6963:         return $access;
                   6964:     }
                   6965: 
1.1084    raeburn  6966:     my ($is_adv,%domdef);
                   6967:     if (ref($is_advref) eq 'HASH') {
                   6968:         $is_adv = $is_advref->{'is_adv'};
                   6969:     } else {
                   6970:         $is_adv = &is_advanced_user($udom,$uname);
                   6971:     }
                   6972:     if (ref($domdefref) eq 'HASH') {
                   6973:         %domdef = %{$domdefref};
                   6974:     } else {
                   6975:         %domdef = &get_domain_defaults($udom);
                   6976:     }
1.976     raeburn  6977:     if (ref($domdef{$tool}) eq 'HASH') {
                   6978:         if ($is_adv) {
                   6979:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6980:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6981:                     $access = 1;
                   6982:                 } else {
                   6983:                     $access = 0;
                   6984:                 }
                   6985:                 return $access;
                   6986:             }
                   6987:         }
                   6988:         if ($inststatus ne '') {
                   6989:             my ($hasaccess,$hasnoaccess);
                   6990:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6991:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6992:                     if ($domdef{$tool}{$affiliation}) {
                   6993:                         $hasaccess = 1;
                   6994:                     } else {
                   6995:                         $hasnoaccess = 1;
                   6996:                     }
                   6997:                 }
                   6998:             }
                   6999:             if ($hasaccess || $hasnoaccess) {
                   7000:                 if ($hasaccess) {
                   7001:                     $access = 1;
                   7002:                 } elsif ($hasnoaccess) {
                   7003:                     $access = 0; 
                   7004:                 }
                   7005:                 return $access;
                   7006:             }
                   7007:         } else {
                   7008:             if ($domdef{$tool}{'default'} ne '') {
                   7009:                 if ($domdef{$tool}{'default'}) {
                   7010:                     $access = 1;
                   7011:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7012:                     $access = 0;
                   7013:                 }
                   7014:                 return $access;
                   7015:             }
                   7016:         }
                   7017:     } else {
1.1172.2.6  raeburn  7018:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7019:             $access = 1;
                   7020:         } else {
                   7021:             $access = 0;
                   7022:         }
1.976     raeburn  7023:         return $access;
                   7024:     }
                   7025: }
                   7026: 
1.1050    raeburn  7027: sub is_course_owner {
                   7028:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7029:     if (($udom eq '') || ($uname eq '')) {
                   7030:         $udom = $env{'user.domain'};
                   7031:         $uname = $env{'user.name'};
                   7032:     }
                   7033:     unless (($udom eq '') || ($uname eq '')) {
                   7034:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7035:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7036:                 return 1;
                   7037:             } else {
                   7038:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7039:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7040:                     return 1;
                   7041:                 }
                   7042:             }
                   7043:         }
                   7044:     }
                   7045:     return;
                   7046: }
                   7047: 
1.976     raeburn  7048: sub is_advanced_user {
                   7049:     my ($udom,$uname) = @_;
1.1085    raeburn  7050:     if ($udom ne '' && $uname ne '') {
                   7051:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7052:             if (wantarray) {
                   7053:                 return ($env{'user.adv'},$env{'user.author'});
                   7054:             } else {
                   7055:                 return $env{'user.adv'};
                   7056:             }
1.1085    raeburn  7057:         }
                   7058:     }
1.976     raeburn  7059:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7060:     my %allroles;
1.1128    raeburn  7061:     my ($is_adv,$is_author);
1.976     raeburn  7062:     foreach my $role (keys(%roleshash)) {
                   7063:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7064:         my $area = '/'.$tdomain.'/'.$trest;
                   7065:         if ($sec ne '') {
                   7066:             $area .= '/'.$sec;
                   7067:         }
                   7068:         if (($area ne '') && ($trole ne '')) {
                   7069:             my $spec=$trole.'.'.$area;
                   7070:             if ($trole =~ /^cr\//) {
                   7071:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7072:             } elsif ($trole ne 'gr') {
                   7073:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7074:             }
1.1128    raeburn  7075:             if ($trole eq 'au') {
                   7076:                 $is_author = 1;
                   7077:             }
1.976     raeburn  7078:         }
                   7079:     }
                   7080:     foreach my $role (keys(%allroles)) {
                   7081:         last if ($is_adv);
                   7082:         foreach my $item (split(/:/,$allroles{$role})) {
                   7083:             if ($item ne '') {
                   7084:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7085:                 if ($privilege eq 'adv') {
                   7086:                     $is_adv = 1;
                   7087:                     last;
                   7088:                 }
                   7089:             }
                   7090:         }
                   7091:     }
1.1128    raeburn  7092:     if (wantarray) {
                   7093:         return ($is_adv,$is_author);
                   7094:     }
1.976     raeburn  7095:     return $is_adv;
                   7096: }
1.798     raeburn  7097: 
1.1035    raeburn  7098: sub check_can_request {
1.1036    raeburn  7099:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7100:     my $canreq = 0;
                   7101:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7102:     my @options = ('approval','validate','autolimit');
                   7103:     my $optregex = join('|',@options);
                   7104:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7105:         foreach my $type (@{$types}) {
                   7106:             if (&usertools_access($env{'user.name'},
                   7107:                                   $env{'user.domain'},
                   7108:                                   $type,undef,'requestcourses')) {
                   7109:                 $canreq ++;
1.1036    raeburn  7110:                 if (ref($request_domains) eq 'HASH') {
                   7111:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7112:                 }
1.1035    raeburn  7113:                 if ($dom eq $env{'user.domain'}) {
                   7114:                     $can_request->{$type} = 1;
                   7115:                 }
                   7116:             }
                   7117:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7118:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7119:                 if (@curr > 0) {
1.1036    raeburn  7120:                     foreach my $item (@curr) {
                   7121:                         if (ref($request_domains) eq 'HASH') {
                   7122:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7123:                             if ($otherdom ne '') {
                   7124:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7125:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7126:                                         push(@{$request_domains->{$type}},$otherdom);
                   7127:                                     }
                   7128:                                 } else {
                   7129:                                     push(@{$request_domains->{$type}},$otherdom);
                   7130:                                 }
                   7131:                             }
                   7132:                         }
                   7133:                     }
                   7134:                     unless($dom eq $env{'user.domain'}) {
                   7135:                         $canreq ++;
1.1035    raeburn  7136:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7137:                             $can_request->{$type} = 1;
                   7138:                         }
                   7139:                     }
                   7140:                 }
                   7141:             }
                   7142:         }
                   7143:     }
                   7144:     return $canreq;
                   7145: }
                   7146: 
1.341     www      7147: # ---------------------------------------------- Custom access rule evaluation
                   7148: 
                   7149: sub customaccess {
                   7150:     my ($priv,$uri)=@_;
1.807     albertel 7151:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7152:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7153:     $udom = &LONCAPA::clean_domain($udom);
                   7154:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7155:     my $access=0;
1.800     albertel 7156:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7157: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7158: 	if ($type eq 'user') {
                   7159: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7160: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7161: 		if ($tdom) {
                   7162: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7163: 		}
1.896     albertel 7164: 		if ($tuname) {
                   7165: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7166: 		}
                   7167: 		$access=($effect eq 'allow');
                   7168: 		last;
                   7169: 	    }
                   7170: 	} else {
                   7171: 	    if ($role) {
                   7172: 		if ($role ne $urole) { next; }
                   7173: 	    }
                   7174: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7175: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7176: 		if ($tdom) {
                   7177: 		    if ($tdom ne $udom) { next; }
                   7178: 		}
                   7179: 		if ($tcrs) {
                   7180: 		    if ($tcrs ne $ucrs) { next; }
                   7181: 		}
                   7182: 		if ($tsec) {
                   7183: 		    if ($tsec ne $usec) { next; }
                   7184: 		}
                   7185: 		$access=($effect eq 'allow');
                   7186: 		last;
                   7187: 	    }
                   7188: 	    if ($realm eq '' && $role eq '') {
                   7189: 		$access=($effect eq 'allow');
                   7190: 	    }
1.402     bowersj2 7191: 	}
1.341     www      7192:     }
                   7193:     return $access;
                   7194: }
                   7195: 
1.103     harris41 7196: # ------------------------------------------------- Check for a user privilege
1.12      www      7197: 
                   7198: sub allowed {
1.1172.2.65  raeburn  7199:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7200:     my $ver_orguri=$uri;
1.439     www      7201:     $uri=&deversion($uri);
1.152     www      7202:     my $orguri=$uri;
1.52      www      7203:     $uri=&declutter($uri);
1.809     raeburn  7204: 
1.810     raeburn  7205:     if ($priv eq 'evb') {
                   7206: # Evade communication block restrictions for specified role in a course
                   7207:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7208:             return $1;
                   7209:         } else {
                   7210:             return;
                   7211:         }
                   7212:     }
                   7213: 
1.620     albertel 7214:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7215: # Free bre access to adm and meta resources
1.775     albertel 7216:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7217: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7218: 	&& ($priv eq 'bre')) {
1.14      www      7219: 	return 'F';
1.159     www      7220:     }
                   7221: 
1.545     banghart 7222: # Free bre access to user's own portfolio contents
1.714     raeburn  7223:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7224:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7225: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7226:         my %setters;
                   7227:         my ($startblock,$endblock) = 
                   7228:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7229:         if ($startblock && $endblock) {
                   7230:             return 'B';
                   7231:         } else {
                   7232:             return 'F';
                   7233:         }
1.545     banghart 7234:     }
                   7235: 
1.762     raeburn  7236: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7237:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7238:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7239:         if (exists($env{'request.course.id'})) {
                   7240:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7241:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7242:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7243:                 my $courseprivid=$env{'request.course.id'};
                   7244:                 $courseprivid=~s/\_/\//;
                   7245:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7246:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7247:                     return $1; 
1.762     raeburn  7248:                 } else {
                   7249:                     if ($env{'request.course.sec'}) {
                   7250:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7251:                     }
                   7252:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7253:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7254:                         return $2;
                   7255:                     }
1.714     raeburn  7256:                 }
                   7257:             }
                   7258:         }
                   7259:     }
                   7260: 
1.159     www      7261: # Free bre to public access
                   7262: 
                   7263:     if ($priv eq 'bre') {
1.238     www      7264:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7265: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7266:            return 'F'; 
                   7267:         }
1.238     www      7268:         if ($copyright eq 'priv') {
                   7269:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7270: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7271: 		return '';
                   7272:             }
                   7273:         }
                   7274:         if ($copyright eq 'domain') {
                   7275:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7276: 	    unless (($env{'user.domain'} eq $1) ||
                   7277:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7278: 		return '';
                   7279:             }
1.262     matthew  7280:         }
1.620     albertel 7281:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7282:             # Library role, so allow browsing of resources in this domain.
                   7283:             return 'F';
1.238     www      7284:         }
1.341     www      7285:         if ($copyright eq 'custom') {
                   7286: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7287:         }
1.14      www      7288:     }
1.264     matthew  7289:     # Domain coordinator is trying to create a course
1.620     albertel 7290:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7291:         # uri is the requested domain in this case.
                   7292:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7293:         # a role of dc for the domain in question.
1.620     albertel 7294:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7295:     }
1.29      www      7296: 
1.52      www      7297:     my $thisallowed='';
                   7298:     my $statecond=0;
                   7299:     my $courseprivid='';
                   7300: 
1.1039    raeburn  7301:     my $ownaccess;
1.1043    raeburn  7302:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7303:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7304:         if ($uri eq '') {
                   7305:             $ownaccess = 1;
                   7306:         } else {
                   7307:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7308:                 my $udom = $env{'user.domain'};
                   7309:                 my $uname = $env{'user.name'};
                   7310:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7311:                     $ownaccess = 1;
1.1040    raeburn  7312:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7313:                     unless ($uri =~ m{\.\./}) {
                   7314:                         $ownaccess = 1;
                   7315:                     }
                   7316:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7317:                     my $now = time;
                   7318:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7319:                         my $adom = $1;
                   7320:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7321:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7322:                                 my ($start,$end) = split('.',$env{$key});
                   7323:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7324:                                     $ownaccess = 1;
                   7325:                                     last;
                   7326:                                 }
                   7327:                             }
                   7328:                         }
                   7329:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7330:                         my $adom = $1;
                   7331:                         my $aname = $2;
1.1042    raeburn  7332:                         foreach my $role ('ca','aa') { 
                   7333:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7334:                                 my ($start,$end) =
                   7335:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7336:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7337:                                     $ownaccess = 1;
                   7338:                                     last;
                   7339:                                 }
1.1039    raeburn  7340:                             }
                   7341:                         }
                   7342:                     }
                   7343:                 }
                   7344:             }
                   7345:         }
                   7346:     }
                   7347: 
1.52      www      7348: # Course
                   7349: 
1.620     albertel 7350:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7351:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7352:             $thisallowed.=$1;
                   7353:         }
1.52      www      7354:     }
1.29      www      7355: 
1.52      www      7356: # Domain
                   7357: 
1.620     albertel 7358:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7359:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7360:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7361:             $thisallowed.=$1;
                   7362:         }
1.12      www      7363:     }
1.52      www      7364: 
1.1141    raeburn  7365: # User who is not author or co-author might still be able to edit
                   7366: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7367:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7368:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7369:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7370:             $thisallowed.=$1;
                   7371:         }
                   7372:     }
                   7373: 
1.52      www      7374: # Course: uri itself is a course
1.66      www      7375:     my $courseuri=$uri;
                   7376:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7377:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7378: 
1.620     albertel 7379:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7380:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7381:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7382:             $thisallowed.=$1;
                   7383:         }
1.12      www      7384:     }
1.29      www      7385: 
1.665     albertel 7386: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7387: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7388:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7389: 	$thisallowed='';
1.671     raeburn  7390:         my ($match)=&is_on_map($uri);
                   7391:         if ($match) {
                   7392:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7393:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7394:                 my $value = $1;
                   7395:                 if ($noblockcheck) {
                   7396:                     $thisallowed.=$value;
1.1162    raeburn  7397:                 } else {
1.1172.2.65  raeburn  7398:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7399:                     if (@blockers > 0) {
                   7400:                         $thisallowed = 'B';
                   7401:                     } else {
                   7402:                         $thisallowed.=$value;
                   7403:                     }
1.1162    raeburn  7404:                 }
1.671     raeburn  7405:             }
                   7406:         } else {
1.705     albertel 7407:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7408:             if ($refuri) {
                   7409:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7410:                     $thisallowed='F';
1.671     raeburn  7411:                 } else {
                   7412:                     $refuri=&declutter($refuri);
                   7413:                     my ($match) = &is_on_map($refuri);
                   7414:                     if ($match) {
1.1172.2.65  raeburn  7415:                         if ($noblockcheck) {
1.1162    raeburn  7416:                             $thisallowed='F';
1.1172.2.65  raeburn  7417:                         } else {
                   7418:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7419:                             if (@blockers > 0) {
                   7420:                                 $thisallowed = 'B';
                   7421:                             } else {
                   7422:                                 $thisallowed='F';
                   7423:                             }
1.1162    raeburn  7424:                         }
1.671     raeburn  7425:                     }
1.669     raeburn  7426:                 }
1.671     raeburn  7427:             }
                   7428:         }
1.314     www      7429:     }
1.492     albertel 7430: 
1.766     albertel 7431:     if ($priv eq 'bre'
                   7432: 	&& $thisallowed ne 'F' 
                   7433: 	&& $thisallowed ne '2'
                   7434: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7435: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7436:     }
                   7437:     
1.52      www      7438: # Full access at system, domain or course-wide level? Exit.
1.29      www      7439:     if ($thisallowed=~/F/) {
                   7440: 	return 'F';
                   7441:     }
                   7442: 
1.52      www      7443: # If this is generating or modifying users, exit with special codes
1.29      www      7444: 
1.643     www      7445:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7446: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7447: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7448: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7449: 	    unless ($auname) { return $thisallowed; }
                   7450: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7451: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7452: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7453: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7454: 	}
1.52      www      7455: 	return $thisallowed;
                   7456:     }
                   7457: #
1.103     harris41 7458: # Gathered so far: system, domain and course wide privileges
1.52      www      7459: #
                   7460: # Course: See if uri or referer is an individual resource that is part of 
                   7461: # the course
                   7462: 
1.620     albertel 7463:     if ($env{'request.course.id'}) {
1.232     www      7464: 
1.620     albertel 7465:        $courseprivid=$env{'request.course.id'};
                   7466:        if ($env{'request.course.sec'}) {
                   7467:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7468:        }
                   7469:        $courseprivid=~s/\_/\//;
                   7470:        my $checkreferer=1;
1.232     www      7471:        my ($match,$cond)=&is_on_map($uri);
                   7472:        if ($match) {
                   7473:            $statecond=$cond;
1.620     albertel 7474:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7475:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7476:                my $value = $1;
                   7477:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7478:                    if ($noblockcheck) {
1.1162    raeburn  7479:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7480:                    } else {
                   7481:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7482:                        if (@blockers > 0) {
                   7483:                            $thisallowed = 'B';
                   7484:                        } else {
                   7485:                            $thisallowed.=$value;
                   7486:                        }
1.1162    raeburn  7487:                    }
                   7488:                } else {
                   7489:                    $thisallowed.=$value;
                   7490:                }
1.52      www      7491:                $checkreferer=0;
                   7492:            }
1.29      www      7493:        }
1.83      www      7494:        
1.148     www      7495:        if ($checkreferer) {
1.620     albertel 7496: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7497:             unless ($refuri) {
1.800     albertel 7498:                 foreach my $key (keys(%env)) {
                   7499: 		    if ($key=~/^httpref\..*\*/) {
                   7500: 			my $pattern=$key;
1.156     www      7501:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7502:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7503:                         $pattern=~s/\//\\\//g;
1.152     www      7504:                         if ($orguri=~/$pattern/) {
1.800     albertel 7505: 			    $refuri=$env{$key};
1.148     www      7506:                         }
                   7507:                     }
1.191     harris41 7508:                 }
1.148     www      7509:             }
1.232     www      7510: 
1.148     www      7511:          if ($refuri) { 
1.152     www      7512: 	  $refuri=&declutter($refuri);
1.232     www      7513:           my ($match,$cond)=&is_on_map($refuri);
                   7514:             if ($match) {
                   7515:               my $refstatecond=$cond;
1.620     albertel 7516:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7517:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7518:                   my $value = $1;
                   7519:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7520:                       if ($noblockcheck) {
1.1162    raeburn  7521:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7522:                       } else {
                   7523:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7524:                           if (@blockers > 0) {
                   7525:                               $thisallowed = 'B';
                   7526:                           } else {
                   7527:                               $thisallowed.=$value;
                   7528:                           }
1.1162    raeburn  7529:                       }
                   7530:                   } else {
                   7531:                       $thisallowed.=$value;
                   7532:                   }
1.53      www      7533:                   $uri=$refuri;
                   7534:                   $statecond=$refstatecond;
1.52      www      7535:               }
                   7536:           }
1.148     www      7537:         }
1.29      www      7538:        }
1.52      www      7539:    }
1.29      www      7540: 
1.52      www      7541: #
1.103     harris41 7542: # Gathered now: all privileges that could apply, and condition number
1.52      www      7543: # 
                   7544: #
                   7545: # Full or no access?
                   7546: #
1.29      www      7547: 
1.52      www      7548:     if ($thisallowed=~/F/) {
                   7549: 	return 'F';
                   7550:     }
1.29      www      7551: 
1.52      www      7552:     unless ($thisallowed) {
                   7553:         return '';
                   7554:     }
1.29      www      7555: 
1.52      www      7556: # Restrictions exist, deal with them
                   7557: #
                   7558: #   C:according to course preferences
                   7559: #   R:according to resource settings
                   7560: #   L:unless locked
                   7561: #   X:according to user session state
                   7562: #
                   7563: 
                   7564: # Possibly locked functionality, check all courses
1.54      www      7565: # Locks might take effect only after 10 minutes cache expiration for other
                   7566: # courses, and 2 minutes for current course
1.52      www      7567: 
                   7568:     my $envkey;
                   7569:     if ($thisallowed=~/L/) {
1.1000    raeburn  7570:         foreach $envkey (keys(%env)) {
1.54      www      7571:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7572:                my $courseid=$2;
                   7573:                my $roleid=$1.'.'.$2;
1.92      www      7574:                $courseid=~s/^\///;
1.54      www      7575:                my $expiretime=600;
1.620     albertel 7576:                if ($env{'request.role'} eq $roleid) {
1.54      www      7577: 		  $expiretime=120;
                   7578:                }
                   7579: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7580:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7581:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7582: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7583:                }
1.620     albertel 7584:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7585:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7586: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7587:                        &log($env{'user.domain'},$env{'user.name'},
                   7588:                             $env{'user.home'},
1.57      www      7589:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7590:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7591:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7592: 		       return '';
                   7593:                    }
                   7594:                }
1.620     albertel 7595:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7596:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7597: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7598:                        &log($env{'user.domain'},$env{'user.name'},
                   7599:                             $env{'user.home'},
1.57      www      7600:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7601:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7602:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7603: 		       return '';
                   7604:                    }
                   7605:                }
                   7606: 	   }
1.29      www      7607:        }
1.52      www      7608:     }
                   7609:    
                   7610: #
                   7611: # Rest of the restrictions depend on selected course
                   7612: #
                   7613: 
1.620     albertel 7614:     unless ($env{'request.course.id'}) {
1.766     albertel 7615: 	if ($thisallowed eq 'A') {
                   7616: 	    return 'A';
1.814     raeburn  7617:         } elsif ($thisallowed eq 'B') {
                   7618:             return 'B';
1.766     albertel 7619: 	} else {
                   7620: 	    return '1';
                   7621: 	}
1.52      www      7622:     }
1.29      www      7623: 
1.52      www      7624: #
                   7625: # Now user is definitely in a course
                   7626: #
1.53      www      7627: 
                   7628: 
                   7629: # Course preferences
                   7630: 
                   7631:    if ($thisallowed=~/C/) {
1.620     albertel 7632:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7633:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7634:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7635: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7636: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7637: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7638: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7639: 			$env{'request.course.id'});
                   7640: 	   }
1.237     www      7641:            return '';
                   7642:        }
                   7643: 
1.620     albertel 7644:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7645: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7646: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7647: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7648: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7649: 			$env{'request.course.id'});
                   7650: 	   }
1.54      www      7651:            return '';
                   7652:        }
1.53      www      7653:    }
                   7654: 
                   7655: # Resource preferences
                   7656: 
                   7657:    if ($thisallowed=~/R/) {
1.620     albertel 7658:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7659:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7660: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7661: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7662: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7663: 	   }
                   7664: 	   return '';
1.54      www      7665:        }
1.53      www      7666:    }
1.30      www      7667: 
1.246     www      7668: # Restricted by state or randomout?
1.30      www      7669: 
1.52      www      7670:    if ($thisallowed=~/X/) {
1.620     albertel 7671:       if ($env{'acc.randomout'}) {
1.579     albertel 7672: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7673:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7674:             return ''; 
                   7675:          }
1.247     www      7676:       }
                   7677:       if (&condval($statecond)) {
1.52      www      7678: 	 return '2';
                   7679:       } else {
                   7680:          return '';
                   7681:       }
                   7682:    }
1.30      www      7683: 
1.766     albertel 7684:     if ($thisallowed eq 'A') {
                   7685: 	return 'A';
1.814     raeburn  7686:     } elsif ($thisallowed eq 'B') {
                   7687:         return 'B';
1.766     albertel 7688:     }
1.52      www      7689:    return 'F';
1.232     www      7690: }
1.1162    raeburn  7691: 
1.1172.2.13  raeburn  7692: # ------------------------------------------- Check construction space access
                   7693: 
                   7694: sub constructaccess {
                   7695:     my ($url,$setpriv)=@_;
                   7696: 
                   7697: # We do not allow editing of previous versions of files
                   7698:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7699: 
                   7700: # Get username and domain from URL
                   7701:     my ($ownername,$ownerdomain,$ownerhome);
                   7702: 
                   7703:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7704:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7705: 
                   7706: # The URL does not really point to any authorspace, forget it
                   7707:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7708: 
                   7709: # Now we need to see if the user has access to the authorspace of
                   7710: # $ownername at $ownerdomain
                   7711: 
                   7712:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7713: # Real author for this?
                   7714:        $ownerhome = $env{'user.home'};
                   7715:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7716:           return ($ownername,$ownerdomain,$ownerhome);
                   7717:        }
                   7718:     } else {
                   7719: # Co-author for this?
                   7720:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7721:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7722:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7723:             return ($ownername,$ownerdomain,$ownerhome);
                   7724:         }
                   7725:     }
                   7726: 
                   7727: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7728: # we might as well leave
                   7729:    unless ($setpriv) { return ''; }
                   7730: 
                   7731: # Backdoor access?
                   7732:     my $allowed=&allowed('eco',$ownerdomain);
                   7733: # Nope
                   7734:     unless ($allowed) { return ''; }
                   7735: # Looks like we may have access, but could be locked by the owner of the construction space
                   7736:     if ($allowed eq 'U') {
                   7737:         my %blocked=&get('environment',['domcoord.author'],
                   7738:                          $ownerdomain,$ownername);
                   7739: # Is blocked by owner
                   7740:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7741:     }
                   7742:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7743: # Grant temporary access
                   7744:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7745:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7746:         if (!$update) { $update = $then; }
                   7747:         my $refresh=$env{'user.refresh.time'};
                   7748:         if (!$refresh) { $refresh = $update; }
                   7749:         my $now = time;
                   7750:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7751:                            $now,'ca','constructaccess');
                   7752:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7753:         return($ownername,$ownerdomain,$ownerhome);
                   7754:     }
                   7755: # No business here
                   7756:     return '';
                   7757: }
                   7758: 
1.1172.2.66  raeburn  7759: # ----------------------------------------------------------- Content Blocking
                   7760: 
                   7761: {
                   7762: # Caches for faster Course Contents display where content blocking
                   7763: # is in operation (i.e., interval param set) for timed quiz.
                   7764: #
                   7765: # User for whom data are being temporarily cached.
                   7766: my $cacheduser='';
                   7767: # Cached blockers for this user (a hash of blocking items).
                   7768: my %cachedblockers=();
                   7769: # When the data were last cached.
                   7770: my $cachedlast='';
                   7771: 
                   7772: sub load_all_blockers {
                   7773:     my ($uname,$udom,$blocks)=@_;
                   7774:     if (($uname ne '') && ($udom ne '')) {
                   7775:         if (($cacheduser eq $uname.':'.$udom) &&
                   7776:             (abs($cachedlast-time)<5)) {
                   7777:             return;
                   7778:         }
                   7779:     }
                   7780:     $cachedlast=time;
                   7781:     $cacheduser=$uname.':'.$udom;
                   7782:     %cachedblockers = &get_commblock_resources($blocks);
                   7783: }
                   7784: 
1.1162    raeburn  7785: sub get_comm_blocks {
                   7786:     my ($cdom,$cnum) = @_;
                   7787:     if ($cdom eq '' || $cnum eq '') {
                   7788:         return unless ($env{'request.course.id'});
                   7789:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7790:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7791:     }
                   7792:     my %commblocks;
                   7793:     my $hashid=$cdom.'_'.$cnum;
                   7794:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7795:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7796:         %commblocks = %{$blocksref};
                   7797:     } else {
                   7798:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7799:         my $cachetime = 600;
                   7800:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7801:     }
                   7802:     return %commblocks;
                   7803: }
                   7804: 
1.1172.2.66  raeburn  7805: sub get_commblock_resources {
                   7806:     my ($blocks) = @_;
                   7807:     my %blockers = ();
                   7808:     return %blockers unless ($env{'request.course.id'});
                   7809:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7810:     my %commblocks;
                   7811:     if (ref($blocks) eq 'HASH') {
                   7812:         %commblocks = %{$blocks};
                   7813:     } else {
                   7814:         %commblocks = &get_comm_blocks();
                   7815:     }
1.1172.2.66  raeburn  7816:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7817:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7818:     return %blockers unless (ref($navmap));
                   7819:     my $now = time;
1.1162    raeburn  7820:     foreach my $block (keys(%commblocks)) {
                   7821:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7822:             my ($start,$end) = ($1,$2);
                   7823:             if ($start <= $now && $end >= $now) {
                   7824:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7825:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7826:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7827:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7828:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7829:                             }
                   7830:                         }
                   7831:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7832:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7833:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7834:                             }
                   7835:                         }
                   7836:                     }
                   7837:                 }
                   7838:             }
                   7839:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7840:             my $item = $1;
1.1163    raeburn  7841:             my @to_test;
1.1162    raeburn  7842:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7843:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7844:                     my @interval;
                   7845:                     my $type = 'map';
                   7846:                     if ($item eq 'course') {
                   7847:                         $type = 'course';
                   7848:                         @interval=&EXT("resource.0.interval");
                   7849:                     } else {
                   7850:                         if ($item =~ /___\d+___/) {
                   7851:                             $type = 'resource';
                   7852:                             @interval=&EXT("resource.0.interval",$item);
                   7853:                             if (ref($navmap)) {
                   7854:                                 my $res = $navmap->getBySymb($item);
                   7855:                                 push(@to_test,$res);
                   7856:                             }
1.1162    raeburn  7857:                         } else {
1.1172.2.66  raeburn  7858:                             my $mapsymb = &symbread($item,1);
                   7859:                             if ($mapsymb) {
                   7860:                                 if (ref($navmap)) {
                   7861:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7862:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7863:                                     foreach my $res (@to_test) {
                   7864:                                         my $symb = $res->symb();
                   7865:                                         next if ($symb eq $mapsymb);
                   7866:                                         if ($symb ne '') {
                   7867:                                             @interval=&EXT("resource.0.interval",$symb);
                   7868:                                             if ($interval[1] eq 'map') {
                   7869:                                                 last;
1.1162    raeburn  7870:                                             }
                   7871:                                         }
                   7872:                                     }
                   7873:                                 }
                   7874:                             }
                   7875:                         }
1.1172.2.66  raeburn  7876:                     }
                   7877:                     if ($interval[0] =~ /^\d+$/) {
                   7878:                         my $first_access;
                   7879:                         if ($type eq 'resource') {
                   7880:                             $first_access=&get_first_access($interval[1],$item);
                   7881:                         } elsif ($type eq 'map') {
                   7882:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7883:                         } else {
                   7884:                             $first_access=&get_first_access($interval[1]);
                   7885:                         }
                   7886:                         if ($first_access) {
                   7887:                             my $timesup = $first_access+$interval[0];
                   7888:                             if ($timesup > $now) {
                   7889:                                 my $activeblock;
                   7890:                                 foreach my $res (@to_test) {
                   7891:                                     if ($res->answerable()) {
                   7892:                                         $activeblock = 1;
                   7893:                                         last;
                   7894:                                     }
                   7895:                                 }
                   7896:                                 if ($activeblock) {
                   7897:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7898:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7899:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7900:                                          }
                   7901:                                     }
                   7902:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7903:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7904:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7905:                                         }
1.1162    raeburn  7906:                                     }
                   7907:                                 }
                   7908:                             }
                   7909:                         }
                   7910:                     }
                   7911:                 }
                   7912:             }
                   7913:         }
                   7914:     }
1.1172.2.66  raeburn  7915:     return %blockers;
1.1162    raeburn  7916: }
                   7917: 
1.1172.2.66  raeburn  7918: sub has_comm_blocking {
                   7919:     my ($priv,$symb,$uri,$blocks) = @_;
                   7920:     my @blockers;
                   7921:     return unless ($env{'request.course.id'});
                   7922:     return unless ($priv eq 'bre');
                   7923:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7924:     return if ($env{'request.state'} eq 'construct');
                   7925:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7926:     return unless (keys(%cachedblockers) > 0);
                   7927:     my (%possibles,@symbs);
                   7928:     if (!$symb) {
                   7929:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7930:     }
1.1172.2.66  raeburn  7931:     if ($symb) {
                   7932:         @symbs = ($symb);
                   7933:     } elsif (keys(%possibles)) {
                   7934:         @symbs = keys(%possibles);
                   7935:     }
                   7936:     my $noblock;
                   7937:     foreach my $symb (@symbs) {
                   7938:         last if ($noblock);
                   7939:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7940:         foreach my $block (keys(%cachedblockers)) {
                   7941:             if ($block =~ /^firstaccess____(.+)$/) {
                   7942:                 my $item = $1;
                   7943:                 if (($item eq $map) || ($item eq $symb)) {
                   7944:                     $noblock = 1;
                   7945:                     last;
                   7946:                 }
1.1162    raeburn  7947:             }
1.1172.2.66  raeburn  7948:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7949:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7950:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7951:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7952:                             push(@blockers,$block);
                   7953:                         }
                   7954:                     }
                   7955:                 }
                   7956:             }
                   7957:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7958:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7959:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7960:                         push(@blockers,$block);
                   7961:                     }
                   7962:                 }
1.1162    raeburn  7963:             }
                   7964:         }
                   7965:     }
1.1172.2.66  raeburn  7966:     return if ($noblock);
                   7967:     return @blockers;
                   7968: }
1.1162    raeburn  7969: }
                   7970: 
1.1172.2.66  raeburn  7971: # -------------------------------- Deversion and split uri into path an filename
                   7972: 
1.1133    foxr     7973: #
1.1172.2.66  raeburn  7974: #   Removes the version from a URI and
1.1133    foxr     7975: #   splits it in to its filename and path to the filename.
                   7976: #   Seems like File::Basename could have done this more clearly.
                   7977: #   Parameters:
                   7978: #      $uri   - input URI
                   7979: #   Returns:
                   7980: #     Two element list consisting of 
                   7981: #     $pathname  - the URI up to and excluding the trailing /
                   7982: #     $filename  - The part of the URI following the last /
                   7983: #  NOTE:
                   7984: #    Another realization of this is simply:
                   7985: #    use File::Basename;
                   7986: #    ...
                   7987: #    $uri = shift;
                   7988: #    $filename = basename($uri);
                   7989: #    $path     = dirname($uri);
                   7990: #    return ($filename, $path);
                   7991: #
                   7992: #     The implementation below is probably faster however.
                   7993: #
1.710     albertel 7994: sub split_uri_for_cond {
                   7995:     my $uri=&deversion(&declutter(shift));
                   7996:     my @uriparts=split(/\//,$uri);
                   7997:     my $filename=pop(@uriparts);
                   7998:     my $pathname=join('/',@uriparts);
                   7999:     return ($pathname,$filename);
                   8000: }
1.232     www      8001: # --------------------------------------------------- Is a resource on the map?
                   8002: 
                   8003: sub is_on_map {
1.710     albertel 8004:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8005:     #Trying to find the conditional for the file
1.620     albertel 8006:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8007: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8008:     if ($match) {
1.289     bowersj2 8009: 	return (1,$1);
                   8010:     } else {
1.434     www      8011: 	return (0,0);
1.289     bowersj2 8012:     }
1.12      www      8013: }
                   8014: 
1.427     www      8015: # --------------------------------------------------------- Get symb from alias
                   8016: 
                   8017: sub get_symb_from_alias {
                   8018:     my $symb=shift;
                   8019:     my ($map,$resid,$url)=&decode_symb($symb);
                   8020: # Already is a symb
                   8021:     if ($url) { return $symb; }
                   8022: # Must be an alias
                   8023:     my $aliassymb='';
                   8024:     my %bighash;
1.620     albertel 8025:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8026:                             &GDBM_READER(),0640)) {
                   8027:         my $rid=$bighash{'mapalias_'.$symb};
                   8028: 	if ($rid) {
                   8029: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8030: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8031: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8032: 	}
                   8033:         untie %bighash;
                   8034:     }
                   8035:     return $aliassymb;
                   8036: }
                   8037: 
1.12      www      8038: # ----------------------------------------------------------------- Define Role
                   8039: 
                   8040: sub definerole {
                   8041:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8042:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8043:     foreach my $role (split(':',$sysrole)) {
                   8044: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8045:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8046:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8047: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8048:                return "refused:s:$crole&$cqual"; 
                   8049:             }
                   8050:         }
1.191     harris41 8051:     }
1.800     albertel 8052:     foreach my $role (split(':',$domrole)) {
                   8053: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8054:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8055:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8056: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8057:                return "refused:d:$crole&$cqual"; 
                   8058:             }
                   8059:         }
1.191     harris41 8060:     }
1.800     albertel 8061:     foreach my $role (split(':',$courole)) {
                   8062: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8063:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8064:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8065: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8066:                return "refused:c:$crole&$cqual"; 
                   8067:             }
                   8068:         }
1.191     harris41 8069:     }
1.1172.2.84  raeburn  8070:     my $uhome;
                   8071:     if (($uname ne '') && ($udom ne '')) {
                   8072:         $uhome = &homeserver($uname,$udom);
                   8073:         return $uhome if ($uhome eq 'no_host');
                   8074:     } else {
                   8075:         $uname = $env{'user.name'};
                   8076:         $udom = $env{'user.domain'};
                   8077:         $uhome = $env{'user.home'};
                   8078:     }
1.620     albertel 8079:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8080:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8081:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8082:     return reply($command,$uhome);
1.12      www      8083:   } else {
                   8084:     return 'refused';
                   8085:   }
1.105     harris41 8086: }
                   8087: 
                   8088: # ---------------- Make a metadata query against the network of library servers
                   8089: 
                   8090: sub metadata_query {
1.1172.2.33  raeburn  8091:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8092:     my %rhash;
1.845     albertel 8093:     my %libserv = &all_library();
1.244     matthew  8094:     my @server_list = (defined($server_array) ? @$server_array
                   8095:                                               : keys(%libserv) );
                   8096:     for my $server (@server_list) {
1.1172.2.33  raeburn  8097:         my $domains = '';
                   8098:         if (ref($domains_hash) eq 'HASH') {
                   8099:             $domains = $domains_hash->{$server};    
                   8100:         }
1.118     harris41 8101: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8102: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8103: 	    $rhash{$server}=$reply;
                   8104: 	}
                   8105: 	else {
                   8106: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8107: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8108: 			     $server);
                   8109: 	    $rhash{$server}=$reply;
                   8110: 	}
1.112     harris41 8111:     }
1.118     harris41 8112:     return \%rhash;
1.240     www      8113: }
                   8114: 
                   8115: # ----------------------------------------- Send log queries and wait for reply
                   8116: 
                   8117: sub log_query {
                   8118:     my ($uname,$udom,$query,%filters)=@_;
                   8119:     my $uhome=&homeserver($uname,$udom);
                   8120:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8121:     my $uhost=&hostname($uhome);
1.800     albertel 8122:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8123:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8124:                        $uhome);
1.479     albertel 8125:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8126:     return get_query_reply($queryid);
                   8127: }
                   8128: 
1.818     raeburn  8129: # -------------------------- Update MySQL table for portfolio file
                   8130: 
                   8131: sub update_portfolio_table {
1.821     raeburn  8132:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8133:     if ($group ne '') {
                   8134:         $file_name =~s /^\Q$group\E//;
                   8135:     }
1.818     raeburn  8136:     my $homeserver = &homeserver($uname,$udom);
                   8137:     my $queryid=
1.821     raeburn  8138:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8139:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8140:     my $reply = &get_query_reply($queryid);
                   8141:     return $reply;
                   8142: }
                   8143: 
1.899     raeburn  8144: # -------------------------- Update MySQL allusers table
                   8145: 
                   8146: sub update_allusers_table {
                   8147:     my ($uname,$udom,$names) = @_;
                   8148:     my $homeserver = &homeserver($uname,$udom);
                   8149:     my $queryid=
                   8150:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8151:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8152:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8153:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8154:                'generation='.&escape($names->{'generation'}).'%%'.
                   8155:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8156:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8157:     return;
1.899     raeburn  8158: }
                   8159: 
1.508     raeburn  8160: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8161: 
                   8162: sub fetch_enrollment_query {
1.511     raeburn  8163:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8164:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8165:     my $maxtries = 1;
1.508     raeburn  8166:     if ($context eq 'automated') {
                   8167:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8168:         $sleep = 2;
                   8169:         $loopmax = 100;
1.547     raeburn  8170:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8171:     } else {
                   8172:         $homeserver = &homeserver($cnum,$dom);
                   8173:     }
1.838     albertel 8174:     my $host=&hostname($homeserver);
1.506     raeburn  8175:     my $cmd = '';
1.1000    raeburn  8176:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8177:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8178:     }
                   8179:     $cmd =~ s/%%$//;
                   8180:     $cmd = &escape($cmd);
                   8181:     my $query = 'fetchenrollment';
1.620     albertel 8182:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8183:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8184:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8185:         return 'error: '.$queryid;
                   8186:     }
1.1172.2.93  raeburn  8187:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8188:     my $tries = 1;
                   8189:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8190:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8191:         $tries ++;
                   8192:     }
1.526     raeburn  8193:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8194:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8195:     } else {
1.901     albertel 8196:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8197:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8198:             foreach my $line (@responses) {
                   8199:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8200:                 $$replyref{$key} = $value;
                   8201:             }
                   8202:         } else {
1.1117    foxr     8203:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8204:             foreach my $line (@responses) {
                   8205:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8206:                 $$replyref{$key} = $value;
                   8207:                 if ($value > 0) {
1.800     albertel 8208:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8209:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8210:                         my $destname = $pathname.'/'.$filename;
                   8211:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8212:                         if ($xml_classlist =~ /^error/) {
                   8213:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8214:                         } else {
1.1172.2.96  raeburn  8215:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8216:                                 print FILE &unescape($xml_classlist);
                   8217:                                 close(FILE);
1.526     raeburn  8218:                             } else {
                   8219:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8220:                             }
                   8221:                         }
                   8222:                     }
                   8223:                 }
                   8224:             }
                   8225:         }
                   8226:         return 'ok';
                   8227:     }
                   8228:     return 'error';
                   8229: }
                   8230: 
1.242     www      8231: sub get_query_reply {
1.1172.2.79  raeburn  8232:     my ($queryid,$sleep,$loopmax) = @_;
                   8233:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8234:         $sleep = 0.2;
                   8235:     }
                   8236:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8237:         $loopmax = 100;
                   8238:     }
1.1117    foxr     8239:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8240:     my $reply='';
1.1172.2.79  raeburn  8241:     for (1..$loopmax) {
                   8242: 	sleep($sleep);
1.240     www      8243:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8244: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8245: 		$reply = join('',<$fh>);
                   8246: 		close($fh);
1.240     www      8247: 	   } else { return 'error: reply_file_error'; }
1.242     www      8248:            return &unescape($reply);
                   8249: 	}
1.240     www      8250:     }
1.242     www      8251:     return 'timeout:'.$queryid;
1.240     www      8252: }
                   8253: 
                   8254: sub courselog_query {
1.241     www      8255: #
                   8256: # possible filters:
                   8257: # url: url or symb
                   8258: # username
                   8259: # domain
                   8260: # action: view, submit, grade
                   8261: # start: timestamp
                   8262: # end: timestamp
                   8263: #
1.240     www      8264:     my (%filters)=@_;
1.620     albertel 8265:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8266:     if ($filters{'url'}) {
                   8267: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8268:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8269:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8270:     }
1.620     albertel 8271:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8272:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8273:     return &log_query($cname,$cdom,'courselog',%filters);
                   8274: }
                   8275: 
                   8276: sub userlog_query {
1.858     raeburn  8277: #
                   8278: # possible filters:
                   8279: # action: log check role
                   8280: # start: timestamp
                   8281: # end: timestamp
                   8282: #
1.240     www      8283:     my ($uname,$udom,%filters)=@_;
                   8284:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8285: }
                   8286: 
1.506     raeburn  8287: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8288: 
                   8289: sub auto_run {
1.508     raeburn  8290:     my ($cnum,$cdom) = @_;
1.876     raeburn  8291:     my $response = 0;
                   8292:     my $settings;
                   8293:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8294:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8295:         $settings = $domconfig{'autoenroll'};
                   8296:         if ($settings->{'run'} eq '1') {
                   8297:             $response = 1;
                   8298:         }
                   8299:     } else {
1.934     raeburn  8300:         my $homeserver;
                   8301:         if (&is_course($cdom,$cnum)) {
                   8302:             $homeserver = &homeserver($cnum,$cdom);
                   8303:         } else {
                   8304:             $homeserver = &domain($cdom,'primary');
                   8305:         }
                   8306:         if ($homeserver ne 'no_host') {
                   8307:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8308:         }
1.876     raeburn  8309:     }
1.506     raeburn  8310:     return $response;
                   8311: }
1.776     albertel 8312: 
1.506     raeburn  8313: sub auto_get_sections {
1.508     raeburn  8314:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8315:     my $homeserver;
                   8316:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8317:         $homeserver = &homeserver($cnum,$cdom);
                   8318:     }
                   8319:     if (!defined($homeserver)) { 
                   8320:         if ($cdom =~ /^$match_domain$/) {
                   8321:             $homeserver = &domain($cdom,'primary');
                   8322:         }
                   8323:     }
                   8324:     my @secs;
                   8325:     if (defined($homeserver)) {
                   8326:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8327:         unless ($response eq 'refused') {
                   8328:             @secs = split(/:/,$response);
                   8329:         }
1.506     raeburn  8330:     }
                   8331:     return @secs;
                   8332: }
1.776     albertel 8333: 
1.506     raeburn  8334: sub auto_new_course {
1.1099    raeburn  8335:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8336:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8337:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8338:     return $response;
                   8339: }
1.776     albertel 8340: 
1.506     raeburn  8341: sub auto_validate_courseID {
1.508     raeburn  8342:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8343:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8344:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8345:     return $response;
                   8346: }
1.776     albertel 8347: 
1.1007    raeburn  8348: sub auto_validate_instcode {
1.1020    raeburn  8349:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8350:     my ($homeserver,$response);
                   8351:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8352:         $homeserver = &homeserver($cnum,$cdom);
                   8353:     }
                   8354:     if (!defined($homeserver)) {
                   8355:         if ($cdom =~ /^$match_domain$/) {
                   8356:             $homeserver = &domain($cdom,'primary');
                   8357:         }
                   8358:     }
1.1065    raeburn  8359:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8360:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8361:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8362:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8363: }
                   8364: 
1.506     raeburn  8365: sub auto_create_password {
1.873     raeburn  8366:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8367:     my ($homeserver,$response);
1.506     raeburn  8368:     my $create_passwd = 0;
                   8369:     my $authchk = '';
1.873     raeburn  8370:     if ($udom =~ /^$match_domain$/) {
                   8371:         $homeserver = &domain($udom,'primary');
                   8372:     }
                   8373:     if ($homeserver eq '') {
                   8374:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8375:             $homeserver = &homeserver($cnum,$cdom);
                   8376:         }
                   8377:     }
                   8378:     if ($homeserver eq '') {
                   8379:         $authchk = 'nodomain';
1.506     raeburn  8380:     } else {
1.873     raeburn  8381:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8382:         if ($response eq 'refused') {
                   8383:             $authchk = 'refused';
                   8384:         } else {
1.901     albertel 8385:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8386:         }
1.506     raeburn  8387:     }
                   8388:     return ($authparam,$create_passwd,$authchk);
                   8389: }
                   8390: 
1.706     raeburn  8391: sub auto_photo_permission {
                   8392:     my ($cnum,$cdom,$students) = @_;
                   8393:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8394:     my ($outcome,$perm_reqd,$conditions) = 
                   8395: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8396:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8397: 	return (undef,undef);
                   8398:     }
1.706     raeburn  8399:     return ($outcome,$perm_reqd,$conditions);
                   8400: }
                   8401: 
                   8402: sub auto_checkphotos {
                   8403:     my ($uname,$udom,$pid) = @_;
                   8404:     my $homeserver = &homeserver($uname,$udom);
                   8405:     my ($result,$resulttype);
                   8406:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8407: 				   &escape($uname).':'.&escape($pid),
                   8408: 				   $homeserver));
1.709     albertel 8409:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8410: 	return (undef,undef);
                   8411:     }
1.706     raeburn  8412:     if ($outcome) {
                   8413:         ($result,$resulttype) = split(/:/,$outcome);
                   8414:     } 
                   8415:     return ($result,$resulttype);
                   8416: }
                   8417: 
                   8418: sub auto_photochoice {
                   8419:     my ($cnum,$cdom) = @_;
                   8420:     my $homeserver = &homeserver($cnum,$cdom);
                   8421:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8422: 						       &escape($cdom),
                   8423: 						       $homeserver)));
1.709     albertel 8424:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8425: 	return (undef,undef);
                   8426:     }
1.706     raeburn  8427:     return ($update,$comment);
                   8428: }
                   8429: 
                   8430: sub auto_photoupdate {
                   8431:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8432:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8433:     my $host=&hostname($homeserver);
1.706     raeburn  8434:     my $cmd = '';
                   8435:     my $maxtries = 1;
1.800     albertel 8436:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8437:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8438:     }
                   8439:     $cmd =~ s/%%$//;
                   8440:     $cmd = &escape($cmd);
                   8441:     my $query = 'institutionalphotos';
                   8442:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8443:     unless ($queryid=~/^\Q$host\E\_/) {
                   8444:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8445:         return 'error: '.$queryid;
                   8446:     }
                   8447:     my $reply = &get_query_reply($queryid);
                   8448:     my $tries = 1;
                   8449:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8450:         $reply = &get_query_reply($queryid);
                   8451:         $tries ++;
                   8452:     }
                   8453:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8454:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8455:     } else {
                   8456:         my @responses = split(/:/,$reply);
                   8457:         my $outcome = shift(@responses); 
                   8458:         foreach my $item (@responses) {
                   8459:             my ($key,$value) = split(/=/,$item);
                   8460:             $$photo{$key} = $value;
                   8461:         }
                   8462:         return $outcome;
                   8463:     }
                   8464:     return 'error';
                   8465: }
                   8466: 
1.521     raeburn  8467: sub auto_instcode_format {
1.793     albertel 8468:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8469: 	$cat_order) = @_;
1.521     raeburn  8470:     my $courses = '';
1.772     raeburn  8471:     my @homeservers;
1.521     raeburn  8472:     if ($caller eq 'global') {
1.841     albertel 8473: 	my %servers = &get_servers($codedom,'library');
                   8474: 	foreach my $tryserver (keys(%servers)) {
                   8475: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8476: 		push(@homeservers,$tryserver);
                   8477: 	    }
1.584     raeburn  8478:         }
1.1022    raeburn  8479:     } elsif ($caller eq 'requests') {
                   8480:         if ($codedom =~ /^$match_domain$/) {
                   8481:             my $chome = &domain($codedom,'primary');
                   8482:             unless ($chome eq 'no_host') {
                   8483:                 push(@homeservers,$chome);
                   8484:             }
                   8485:         }
1.521     raeburn  8486:     } else {
1.772     raeburn  8487:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8488:     }
1.793     albertel 8489:     foreach my $code (keys(%{$instcodes})) {
                   8490:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8491:     }
                   8492:     chop($courses);
1.772     raeburn  8493:     my $ok_response = 0;
                   8494:     my $response;
                   8495:     while (@homeservers > 0 && $ok_response == 0) {
                   8496:         my $server = shift(@homeservers); 
                   8497:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8498:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8499:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8500: 		split(/:/,$response);
1.772     raeburn  8501:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8502:             push(@{$codetitles},&str2array($codetitles_str));
                   8503:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8504:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8505:             $ok_response = 1;
                   8506:         }
                   8507:     }
                   8508:     if ($ok_response) {
1.521     raeburn  8509:         return 'ok';
1.772     raeburn  8510:     } else {
                   8511:         return $response;
1.521     raeburn  8512:     }
                   8513: }
                   8514: 
1.792     raeburn  8515: sub auto_instcode_defaults {
                   8516:     my ($domain,$returnhash,$code_order) = @_;
                   8517:     my @homeservers;
1.841     albertel 8518: 
                   8519:     my %servers = &get_servers($domain,'library');
                   8520:     foreach my $tryserver (keys(%servers)) {
                   8521: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8522: 	    push(@homeservers,$tryserver);
                   8523: 	}
1.792     raeburn  8524:     }
1.841     albertel 8525: 
1.792     raeburn  8526:     my $response;
1.841     albertel 8527:     foreach my $server (@homeservers) {
1.792     raeburn  8528:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8529:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8530: 	
                   8531: 	foreach my $pair (split(/\&/,$response)) {
                   8532: 	    my ($name,$value)=split(/\=/,$pair);
                   8533: 	    if ($name eq 'code_order') {
                   8534: 		@{$code_order} = split(/\&/,&unescape($value));
                   8535: 	    } else {
                   8536: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8537: 	    }
                   8538: 	}
                   8539: 	return 'ok';
1.792     raeburn  8540:     }
1.841     albertel 8541: 
                   8542:     return $response;
1.1003    raeburn  8543: }
                   8544: 
                   8545: sub auto_possible_instcodes {
1.1007    raeburn  8546:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8547:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8548:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8549:         return;
                   8550:     }
1.1003    raeburn  8551:     my (@homeservers,$uhome);
                   8552:     if (defined(&domain($domain,'primary'))) {
                   8553:         $uhome=&domain($domain,'primary');
                   8554:         push(@homeservers,&domain($domain,'primary'));
                   8555:     } else {
                   8556:         my %servers = &get_servers($domain,'library');
                   8557:         foreach my $tryserver (keys(%servers)) {
                   8558:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8559:                 push(@homeservers,$tryserver);
                   8560:             }
                   8561:         }
                   8562:     }
                   8563:     my $response;
                   8564:     foreach my $server (@homeservers) {
                   8565:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8566:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8567:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8568:             split(':',$response);
                   8569:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8570:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8571:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8572:             my ($name,$value)=split('=',$item);
                   8573:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8574:         }
                   8575:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8576:             my ($name,$value)=split('=',$item);
                   8577:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8578:         }
                   8579:         return 'ok';
                   8580:     }
                   8581:     return $response;
                   8582: }
1.792     raeburn  8583: 
1.1010    raeburn  8584: sub auto_courserequest_checks {
                   8585:     my ($dom) = @_;
1.1020    raeburn  8586:     my ($homeserver,%validations);
                   8587:     if ($dom =~ /^$match_domain$/) {
                   8588:         $homeserver = &domain($dom,'primary');
                   8589:     }
                   8590:     unless ($homeserver eq 'no_host') {
                   8591:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8592:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8593:             my @items = split(/&/,$response);
                   8594:             foreach my $item (@items) {
                   8595:                 my ($key,$value) = split('=',$item);
                   8596:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8597:             }
                   8598:         }
                   8599:     }
1.1010    raeburn  8600:     return %validations; 
                   8601: }
                   8602: 
1.1020    raeburn  8603: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8604:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8605:     my ($homeserver,$response);
                   8606:     if ($dom =~ /^$match_domain$/) {
                   8607:         $homeserver = &domain($dom,'primary');
                   8608:     }
1.1172.2.43  raeburn  8609:     unless ($homeserver eq 'no_host') {
                   8610:         my $customdata;
                   8611:         if (ref($custominfo) eq 'HASH') {
                   8612:             $customdata = &freeze_escape($custominfo);
                   8613:         }
1.1020    raeburn  8614:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8615:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8616:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8617:                                     $customdata,$homeserver));
1.1020    raeburn  8618:     }
                   8619:     return $response;
                   8620: }
                   8621: 
1.777     albertel 8622: sub auto_validate_class_sec {
1.918     raeburn  8623:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8624:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8625:     my $ownerlist;
                   8626:     if (ref($owners) eq 'ARRAY') {
                   8627:         $ownerlist = join(',',@{$owners});
                   8628:     } else {
                   8629:         $ownerlist = $owners;
                   8630:     }
1.773     raeburn  8631:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8632:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8633:     return $response;
                   8634: }
                   8635: 
1.1172.2.94  raeburn  8636: sub auto_validate_instclasses {
                   8637:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8638:     my ($homeserver,%validations);
                   8639:     $homeserver = &homeserver($cnum,$cdom);
                   8640:     unless ($homeserver eq 'no_host') {
                   8641:         my $ownerlist;
                   8642:         if (ref($owners) eq 'ARRAY') {
                   8643:             $ownerlist = join(',',@{$owners});
                   8644:         } else {
                   8645:             $ownerlist = $owners;
                   8646:         }
                   8647:         if (ref($classesref) eq 'HASH') {
                   8648:             my $classes = &freeze_escape($classesref);
                   8649:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8650:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8651:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8652:                 my @items = split(/&/,$response);
                   8653:                 foreach my $item (@items) {
                   8654:                     my ($key,$value) = split('=',$item);
                   8655:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8656:                 }
                   8657:             }
                   8658:         }
                   8659:     }
                   8660:     return %validations;
                   8661: }
                   8662: 
1.1172.2.38  raeburn  8663: sub auto_crsreq_update {
                   8664:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8665:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8666:     my ($homeserver,%crsreqresponse);
                   8667:     if ($cdom =~ /^$match_domain$/) {
                   8668:         $homeserver = &domain($cdom,'primary');
                   8669:     }
                   8670:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8671:         my $info;
                   8672:         if (ref($inbound) eq 'HASH') {
                   8673:             $info = &freeze_escape($inbound);
                   8674:         }
                   8675:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8676:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8677:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8678:                             &escape($title).':'.&escape($code).':'.
                   8679:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8680:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8681:             my @items = split(/&/,$response);
                   8682:             foreach my $item (@items) {
                   8683:                 my ($key,$value) = split('=',$item);
                   8684:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8685:             }
                   8686:         }
                   8687:     }
                   8688:     return \%crsreqresponse;
                   8689: }
                   8690: 
1.1172.2.78  raeburn  8691: sub auto_export_grades {
                   8692:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8693:     my ($homeserver,%exportresponse);
                   8694:     if ($cdom =~ /^$match_domain$/) {
                   8695:         $homeserver = &domain($cdom,'primary');
                   8696:     }
                   8697:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8698:         my $info;
                   8699:         if (ref($inforef) eq 'HASH') {
                   8700:             $info = &freeze_escape($inforef);
                   8701:         }
                   8702:         if (ref($gradesref) eq 'HASH') {
                   8703:             my $grades = &freeze_escape($gradesref);
                   8704:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8705:                                 $info.':'.$grades,$homeserver);
                   8706:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8707:                 my @items = split(/&/,$response);
                   8708:                 foreach my $item (@items) {
                   8709:                     my ($key,$value) = split('=',$item);
                   8710:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8711:                 }
                   8712:             }
                   8713:         }
                   8714:     }
                   8715:     return \%exportresponse;
                   8716: }
                   8717: 
1.1172.2.68  raeburn  8718: sub check_instcode_cloning {
                   8719:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8720:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8721:         return;
                   8722:     }
                   8723:     my $canclone;
                   8724:     if (@{$code_order} > 0) {
                   8725:         my $instcoderegexp ='^';
                   8726:         my @clonecodes = split(/\&/,$cloner);
                   8727:         foreach my $item (@{$code_order}) {
                   8728:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8729:                 foreach my $pair (@clonecodes) {
                   8730:                     my ($key,$val) = split(/\=/,$pair,2);
                   8731:                     $val = &unescape($val);
                   8732:                     if ($key eq $item) {
                   8733:                         $instcoderegexp .= '('.$val.')';
                   8734:                         last;
                   8735:                     }
                   8736:                 }
                   8737:             } else {
                   8738:                 $instcoderegexp .= $codedefaults->{$item};
                   8739:             }
                   8740:         }
                   8741:         $instcoderegexp .= '$';
                   8742:         my (@from,@to);
                   8743:         eval {
                   8744:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8745:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8746:         };
                   8747:         if ((@from > 0) && (@to > 0)) {
                   8748:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8749:             if (!@diffs) {
                   8750:                 $canclone = 1;
                   8751:             }
                   8752:         }
                   8753:     }
                   8754:     return $canclone;
                   8755: }
                   8756: 
                   8757: sub default_instcode_cloning {
                   8758:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8759:     my (%codedefaults,@code_order,$canclone);
                   8760:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8761:         %codedefaults = %{$codedefaultsref};
                   8762:         @code_order = @{$codeorderref};
                   8763:     } elsif ($clonedom) {
                   8764:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8765:     }
                   8766:     if (($domdefclone) && (@code_order)) {
                   8767:         my @clonecodes = split(/\+/,$domdefclone);
                   8768:         my $instcoderegexp ='^';
                   8769:         foreach my $item (@code_order) {
                   8770:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8771:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8772:             } else {
                   8773:                 $instcoderegexp .= $codedefaults{$item};
                   8774:             }
                   8775:         }
                   8776:         $instcoderegexp .= '$';
                   8777:         my (@from,@to);
                   8778:         eval {
                   8779:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8780:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8781:         };
                   8782:         if ((@from > 0) && (@to > 0)) {
                   8783:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8784:             if (!@diffs) {
                   8785:                 $canclone = 1;
                   8786:             }
                   8787:         }
                   8788:     }
                   8789:     return $canclone;
                   8790: }
                   8791: 
1.679     raeburn  8792: # ------------------------------------------------------- Course Group routines
                   8793: 
                   8794: sub get_coursegroups {
1.809     raeburn  8795:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8796:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8797: }
                   8798: 
1.679     raeburn  8799: sub modify_coursegroup {
                   8800:     my ($cdom,$cnum,$groupsettings) = @_;
                   8801:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8802: }
                   8803: 
1.809     raeburn  8804: sub toggle_coursegroup_status {
                   8805:     my ($cdom,$cnum,$group,$action) = @_;
                   8806:     my ($from_namespace,$to_namespace);
                   8807:     if ($action eq 'delete') {
                   8808:         $from_namespace = 'coursegroups';
                   8809:         $to_namespace = 'deleted_groups';
                   8810:     } else {
                   8811:         $from_namespace = 'deleted_groups';
                   8812:         $to_namespace = 'coursegroups';
                   8813:     }
                   8814:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8815:     if (my $tmp = &error(%curr_group)) {
                   8816:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8817:         return ('read error',$tmp);
                   8818:     } else {
                   8819:         my %savedsettings = %curr_group; 
1.809     raeburn  8820:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8821:         my $deloutcome;
                   8822:         if ($result eq 'ok') {
1.809     raeburn  8823:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8824:         } else {
                   8825:             return ('write error',$result);
                   8826:         }
                   8827:         if ($deloutcome eq 'ok') {
                   8828:             return 'ok';
                   8829:         } else {
                   8830:             return ('delete error',$deloutcome);
                   8831:         }
                   8832:     }
                   8833: }
                   8834: 
1.679     raeburn  8835: sub modify_group_roles {
1.957     raeburn  8836:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8837:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8838:     my $role = 'gr/'.&escape($userprivs);
                   8839:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8840:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8841:     if ($result eq 'ok') {
                   8842:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8843:     }
1.679     raeburn  8844:     return $result;
                   8845: }
                   8846: 
                   8847: sub modify_coursegroup_membership {
                   8848:     my ($cdom,$cnum,$membership) = @_;
                   8849:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8850:     return $result;
                   8851: }
                   8852: 
1.682     raeburn  8853: sub get_active_groups {
                   8854:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8855:     my $now = time;
                   8856:     my %groups = ();
                   8857:     foreach my $key (keys(%env)) {
1.811     albertel 8858:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8859:             my ($start,$end) = split(/\./,$env{$key});
                   8860:             if (($end!=0) && ($end<$now)) { next; }
                   8861:             if (($start!=0) && ($start>$now)) { next; }
                   8862:             if ($1 eq $cdom && $2 eq $cnum) {
                   8863:                 $groups{$3} = $env{$key} ;
                   8864:             }
                   8865:         }
                   8866:     }
                   8867:     return %groups;
                   8868: }
                   8869: 
1.683     raeburn  8870: sub get_group_membership {
                   8871:     my ($cdom,$cnum,$group) = @_;
                   8872:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8873: }
                   8874: 
                   8875: sub get_users_groups {
                   8876:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8877:     my @usersgroups;
1.683     raeburn  8878:     my $cachetime=1800;
                   8879: 
                   8880:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8881:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8882:     if (defined($cached)) {
1.734     albertel 8883:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8884:     } else {  
                   8885:         $grouplist = '';
1.816     raeburn  8886:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8887:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8888:         my $access_end = $env{'course.'.$courseid.
                   8889:                               '.default_enrollment_end_date'};
                   8890:         my $now = time;
                   8891:         foreach my $key (keys(%roleshash)) {
                   8892:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8893:                 my $group = $1;
                   8894:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8895:                     my $start = $2;
                   8896:                     my $end = $1;
                   8897:                     if ($start == -1) { next; } # deleted from group
                   8898:                     if (($start!=0) && ($start>$now)) { next; }
                   8899:                     if (($end!=0) && ($end<$now)) {
                   8900:                         if ($access_end && $access_end < $now) {
                   8901:                             if ($access_end - $end < 86400) {
                   8902:                                 push(@usersgroups,$group);
1.733     raeburn  8903:                             }
                   8904:                         }
1.817     raeburn  8905:                         next;
1.733     raeburn  8906:                     }
1.817     raeburn  8907:                     push(@usersgroups,$group);
1.683     raeburn  8908:                 }
                   8909:             }
                   8910:         }
1.817     raeburn  8911:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8912:         $grouplist = join(':',@usersgroups);
                   8913:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8914:     }
1.733     raeburn  8915:     return @usersgroups;
1.683     raeburn  8916: }
                   8917: 
                   8918: sub devalidate_getgroups_cache {
                   8919:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8920:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8921: 
1.683     raeburn  8922:     my $hashid="$udom:$uname:$courseid";
                   8923:     &devalidate_cache_new('getgroups',$hashid);
                   8924: }
                   8925: 
1.12      www      8926: # ------------------------------------------------------------------ Plain Text
                   8927: 
                   8928: sub plaintext {
1.988     raeburn  8929:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8930:     if ($short =~ m{^cr/}) {
1.758     albertel 8931: 	return (split('/',$short))[-1];
                   8932:     }
1.742     raeburn  8933:     if (!defined($cid)) {
                   8934:         $cid = $env{'request.course.id'};
                   8935:     }
                   8936:     my %rolenames = (
1.1008    raeburn  8937:                       Course    => 'std',
                   8938:                       Community => 'alt1',
1.742     raeburn  8939:                     );
1.1037    raeburn  8940:     if ($cid ne '') {
                   8941:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8942:             unless ($forcedefault) {
                   8943:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8944:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8945:                 return &Apache::lonlocal::mt($roletext);
                   8946:             }
                   8947:         }
                   8948:     }
                   8949:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8950:         (defined($rolenames{$type})) && 
                   8951:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8952:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8953:     } elsif ($cid ne '') {
                   8954:         my $crstype = $env{'course.'.$cid.'.type'};
                   8955:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8956:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8957:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8958:         }
1.742     raeburn  8959:     }
1.1037    raeburn  8960:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8961: }
                   8962: 
                   8963: # ----------------------------------------------------------------- Assign Role
                   8964: 
                   8965: sub assignrole {
1.957     raeburn  8966:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8967:         $context)=@_;
1.21      www      8968:     my $mrole;
                   8969:     if ($role =~ /^cr\//) {
1.393     www      8970:         my $cwosec=$url;
1.811     albertel 8971:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8972: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8973:            my $refused = 1;
                   8974:            if ($context eq 'requestcourses') {
                   8975:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8976:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8977:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8978:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8979:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8980:                            if ($crsenv{'internal.courseowner'} eq
                   8981:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8982:                                $refused = '';
                   8983:                            }
                   8984:                        }
                   8985:                    }
                   8986:                }
                   8987:            }
                   8988:            if ($refused) {
                   8989:                &logthis('Refused custom assignrole: '.
                   8990:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8991:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8992:                return 'refused';
                   8993:            }
1.104     www      8994:         }
1.21      www      8995:         $mrole='cr';
1.678     raeburn  8996:     } elsif ($role =~ /^gr\//) {
                   8997:         my $cwogrp=$url;
1.811     albertel 8998:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8999:         unless (&allowed('mdg',$cwogrp)) {
                   9000:             &logthis('Refused group assignrole: '.
                   9001:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9002:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9003:             return 'refused';
                   9004:         }
                   9005:         $mrole='gr';
1.21      www      9006:     } else {
1.82      www      9007:         my $cwosec=$url;
1.811     albertel 9008:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9009:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9010:             my $refused;
                   9011:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9012:                 if (!(&allowed('c'.$role,$url))) {
                   9013:                     $refused = 1;
                   9014:                 }
                   9015:             } else {
                   9016:                 $refused = 1;
                   9017:             }
1.947     raeburn  9018:             if ($refused) {
1.1045    raeburn  9019:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9020:                 if (!$selfenroll && $context eq 'course') {
                   9021:                     my %crsenv;
                   9022:                     if ($role eq 'cc' || $role eq 'co') {
                   9023:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9024:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9025:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9026:                                 if ($crsenv{'internal.courseowner'} eq 
                   9027:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9028:                                     $refused = '';
                   9029:                                 }
                   9030:                             }
                   9031:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9032:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9033:                                 if ($crsenv{'internal.courseowner'} eq 
                   9034:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9035:                                     $refused = '';
                   9036:                                 }
                   9037:                             }
                   9038:                         }
                   9039:                     }
                   9040:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9041:                     $refused = '';
1.1017    raeburn  9042:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9043:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9044:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9045:                         my $wrongcc;
                   9046:                         if ($cnum =~ /^$match_community$/) {
                   9047:                             $wrongcc = 1 if ($role eq 'cc');
                   9048:                         } else {
                   9049:                             $wrongcc = 1 if ($role eq 'co');
                   9050:                         }
                   9051:                         unless ($wrongcc) {
                   9052:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9053:                             if ($crsenv{'internal.courseowner'} eq 
                   9054:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9055:                                 $refused = '';
                   9056:                             }
1.1017    raeburn  9057:                         }
                   9058:                     }
1.1172.2.9  raeburn  9059:                 } elsif ($context eq 'requestauthor') {
                   9060:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9061:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9062:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9063:                             $refused = '';
                   9064:                         } else {
                   9065:                             my %domdefaults = &get_domain_defaults($udom);
                   9066:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9067:                                 my $checkbystatus;
                   9068:                                 if ($env{'user.adv'}) {
                   9069:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9070:                                     if ($disposition eq 'automatic') {
                   9071:                                         $refused = '';
                   9072:                                     } elsif ($disposition eq '') {
                   9073:                                         $checkbystatus = 1;
                   9074:                                     }
                   9075:                                 } else {
                   9076:                                     $checkbystatus = 1;
                   9077:                                 }
                   9078:                                 if ($checkbystatus) {
                   9079:                                     if ($env{'environment.inststatus'}) {
                   9080:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9081:                                         foreach my $type (@inststatuses) {
                   9082:                                             if (($type ne '') &&
                   9083:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9084:                                                 $refused = '';
                   9085:                                             }
                   9086:                                         }
                   9087:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9088:                                         $refused = '';
                   9089:                                     }
                   9090:                                 }
                   9091:                             }
                   9092:                         }
                   9093:                     }
1.1017    raeburn  9094:                 }
                   9095:                 if ($refused) {
1.947     raeburn  9096:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9097:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9098: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9099:                     return 'refused';
                   9100:                 }
1.932     raeburn  9101:             }
1.1131    raeburn  9102:         } elsif ($role eq 'au') {
                   9103:             if ($url ne '/'.$udom.'/') {
                   9104:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9105:                          ' to assign author role for '.$uname.':'.$udom.
                   9106:                          ' in domain: '.$url.' refused (wrong domain).');
                   9107:                 return 'refused';
                   9108:             }
1.104     www      9109:         }
1.21      www      9110:         $mrole=$role;
                   9111:     }
1.620     albertel 9112:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9113:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9114:     if ($end) { $command.='_'.$end; }
1.21      www      9115:     if ($start) {
                   9116: 	if ($end) { 
1.81      www      9117:            $command.='_'.$start; 
1.21      www      9118:         } else {
1.81      www      9119:            $command.='_0_'.$start;
1.21      www      9120:         }
                   9121:     }
1.739     raeburn  9122:     my $origstart = $start;
                   9123:     my $origend = $end;
1.957     raeburn  9124:     my $delflag;
1.357     www      9125: # actually delete
                   9126:     if ($deleteflag) {
1.373     www      9127: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9128: # modify command to delete the role
1.620     albertel 9129:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9130:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9131: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9132: # set start and finish to negative values for userrolelog
                   9133:            $start=-1;
                   9134:            $end=-1;
1.957     raeburn  9135:            $delflag = 1;
1.357     www      9136:         }
                   9137:     }
                   9138: # send command
1.349     www      9139:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9140: # log new user role if status is ok
1.349     www      9141:     if ($answer eq 'ok') {
1.663     raeburn  9142: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9143:         if (($role eq 'cc') || ($role eq 'in') ||
                   9144:             ($role eq 'ep') || ($role eq 'ad') ||
                   9145:             ($role eq 'ta') || ($role eq 'st') ||
                   9146:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9147:             ($role eq 'co')) {
1.1172.2.13  raeburn  9148: # for course roles, perform group memberships changes triggered by role change.
                   9149:             unless ($role =~ /^gr/) {
                   9150:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9151:                                                  $origstart,$selfenroll,$context);
                   9152:             }
1.1172.2.9  raeburn  9153:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9154:                            $selfenroll,$context);
                   9155:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9156:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9157:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9158:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9159:                            $context);
                   9160:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9161:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9162:                              $context);
                   9163:         }
1.1053    raeburn  9164:         if ($role eq 'cc') {
                   9165:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9166:         }
1.349     www      9167:     }
                   9168:     return $answer;
1.169     harris41 9169: }
                   9170: 
1.1053    raeburn  9171: sub autoupdate_coowners {
                   9172:     my ($url,$end,$start,$uname,$udom) = @_;
                   9173:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9174:     if (($cdom ne '') && ($cnum ne '')) {
                   9175:         my $now = time;
                   9176:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9177:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9178:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9179:             my $instcode = $coursehash{'internal.coursecode'};
                   9180:             if ($instcode ne '') {
1.1056    raeburn  9181:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9182:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9183:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9184:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9185:                         if ($result eq 'valid') {
                   9186:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9187:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9188:                                     push(@newcoowners,$coowner);
                   9189:                                 }
                   9190:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9191:                                     push(@newcoowners,$uname.':'.$udom);
                   9192:                                 }
                   9193:                                 @newcoowners = sort(@newcoowners);
                   9194:                             } else {
                   9195:                                 push(@newcoowners,$uname.':'.$udom);
                   9196:                             }
                   9197:                         } else {
                   9198:                             if ($coursehash{'internal.co-owners'}) {
                   9199:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9200:                                     unless ($coowner eq $uname.':'.$udom) {
                   9201:                                         push(@newcoowners,$coowner);
                   9202:                                     }
                   9203:                                 }
                   9204:                                 unless (@newcoowners > 0) {
                   9205:                                     $delcoowners = 1;
                   9206:                                     $coowners = '';
                   9207:                                 }
                   9208:                             }
                   9209:                         }
                   9210:                         if (@newcoowners || $delcoowners) {
                   9211:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9212:                                             $delcoowners,@newcoowners);
                   9213:                         }
                   9214:                     }
                   9215:                 }
                   9216:             }
                   9217:         }
                   9218:     }
                   9219: }
                   9220: 
                   9221: sub store_coowners {
                   9222:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9223:     my $cid = $cdom.'_'.$cnum;
                   9224:     my ($coowners,$delresult,$putresult);
                   9225:     if (@newcoowners) {
                   9226:         $coowners = join(',',@newcoowners);
                   9227:         my %coownershash = (
                   9228:                             'internal.co-owners' => $coowners,
                   9229:                            );
                   9230:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9231:         if ($putresult eq 'ok') {
                   9232:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9233:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9234:             }
                   9235:         }
                   9236:     }
                   9237:     if ($delcoowners) {
                   9238:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9239:         if ($delresult eq 'ok') {
                   9240:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9241:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9242:             }
                   9243:         }
                   9244:     }
                   9245:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9246:         my %crsinfo =
                   9247:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9248:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9249:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9250:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9251:         }
                   9252:     }
                   9253: }
                   9254: 
1.169     harris41 9255: # -------------------------------------------------- Modify user authentication
1.197     www      9256: # Overrides without validation
                   9257: 
1.169     harris41 9258: sub modifyuserauth {
                   9259:     my ($udom,$uname,$umode,$upass)=@_;
                   9260:     my $uhome=&homeserver($uname,$udom);
1.197     www      9261:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9262:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9263:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9264:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9265:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9266: 		     &escape($upass),$uhome);
1.620     albertel 9267:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9268:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9269:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9270:     &log($udom,,$uname,$uhome,
1.620     albertel 9271:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9272:                                      $env{'user.name'}.', '.$umode.
1.197     www      9273:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9274:     unless ($reply eq 'ok') {
1.197     www      9275:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9276: 	return 'error: '.$reply;
                   9277:     }   
1.170     harris41 9278:     return 'ok';
1.80      www      9279: }
                   9280: 
1.81      www      9281: # --------------------------------------------------------------- Modify a user
1.80      www      9282: 
1.81      www      9283: sub modifyuser {
1.206     matthew  9284:     my ($udom,    $uname, $uid,
                   9285:         $umode,   $upass, $first,
                   9286:         $middle,  $last,  $gene,
1.1058    raeburn  9287:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9288:     $udom= &LONCAPA::clean_domain($udom);
                   9289:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9290:     my $showcandelete = 'none';
                   9291:     if (ref($candelete) eq 'ARRAY') {
                   9292:         if (@{$candelete} > 0) {
                   9293:             $showcandelete = join(', ',@{$candelete});
                   9294:         }
                   9295:     }
1.81      www      9296:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9297:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9298: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9299:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9300:                                      ' desiredhome not specified'). 
1.620     albertel 9301:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9302:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9303:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9304:     my $newuser;
                   9305:     if ($uhome eq 'no_host') {
                   9306:         $newuser = 1;
                   9307:     }
1.80      www      9308: # ----------------------------------------------------------------- Create User
1.406     albertel 9309:     if (($uhome eq 'no_host') && 
                   9310: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9311:         my $unhome='';
1.844     albertel 9312:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9313:             $unhome = $desiredhome;
1.620     albertel 9314: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9315: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9316:         } else { # load balancing routine for determining $unhome
1.81      www      9317:             my $loadm=10000000;
1.841     albertel 9318: 	    my %servers = &get_servers($udom,'library');
                   9319: 	    foreach my $tryserver (keys(%servers)) {
                   9320: 		my $answer=reply('load',$tryserver);
                   9321: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9322: 		    $loadm=$answer;
                   9323: 		    $unhome=$tryserver;
                   9324: 		}
1.80      www      9325: 	    }
                   9326:         }
                   9327:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9328: 	    return 'error: unable to find a home server for '.$uname.
                   9329:                    ' in domain '.$udom;
1.80      www      9330:         }
                   9331:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9332:                          &escape($upass),$unhome);
                   9333: 	unless ($reply eq 'ok') {
                   9334:             return 'error: '.$reply;
                   9335:         }   
1.230     stredwic 9336:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9337:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9338: 	    return 'error: unable verify users home machine.';
1.80      www      9339:         }
1.209     matthew  9340:     }   # End of creation of new user
1.80      www      9341: # ---------------------------------------------------------------------- Add ID
                   9342:     if ($uid) {
                   9343:        $uid=~tr/A-Z/a-z/;
                   9344:        my %uidhash=&idrget($udom,$uname);
1.196     www      9345:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9346:          && (!$forceid)) {
1.80      www      9347: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9348: 	      return 'error: user id "'.$uid.'" does not match '.
                   9349:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9350:           }
                   9351:        } else {
                   9352: 	  &idput($udom,($uname => $uid));
                   9353:        }
                   9354:     }
                   9355: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9356:     my @tmp=&get('environment',
1.899     raeburn  9357: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9358:                     'permanentemail','inststatus'],
1.134     albertel 9359: 		   $udom,$uname);
1.1075    raeburn  9360:     my (%names,%oldnames);
1.313     matthew  9361:     if ($tmp[0] =~ m/^error:.*/) { 
                   9362:         %names=(); 
                   9363:     } else {
                   9364:         %names = @tmp;
1.1075    raeburn  9365:         %oldnames = %names;
1.313     matthew  9366:     }
1.388     www      9367: #
1.1058    raeburn  9368: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9369: # of users did not contain them), do not overwrite existing values
                   9370: # unless field is in $candelete array ref.  
                   9371: #
                   9372: 
                   9373:     my @fields = ('firstname','middlename','lastname','generation',
                   9374:                   'permanentemail','id');
                   9375:     my %newvalues;
                   9376:     if (ref($candelete) eq 'ARRAY') {
                   9377:         foreach my $field (@fields) {
                   9378:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9379:                 if ($field eq 'firstname') {
                   9380:                     $names{$field} = $first;
                   9381:                 } elsif ($field eq 'middlename') {
                   9382:                     $names{$field} = $middle;
                   9383:                 } elsif ($field eq 'lastname') {
                   9384:                     $names{$field} = $last;
                   9385:                 } elsif ($field eq 'generation') { 
                   9386:                     $names{$field} = $gene;
                   9387:                 } elsif ($field eq 'permanentemail') {
                   9388:                     $names{$field} = $email;
                   9389:                 } elsif ($field eq 'id') {
                   9390:                     $names{$field}  = $uid;
                   9391:                 }
                   9392:             }
                   9393:         }
                   9394:     }
1.388     www      9395:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9396:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9397:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9398:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9399:     if ($email) {
                   9400:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9401:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9402:     }
1.899     raeburn  9403:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9404:     if (defined($inststatus)) {
                   9405:         $names{'inststatus'} = '';
                   9406:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9407:         if (ref($usertypes) eq 'HASH') {
                   9408:             my @okstatuses; 
                   9409:             foreach my $item (split(/:/,$inststatus)) {
                   9410:                 if (defined($usertypes->{$item})) {
                   9411:                     push(@okstatuses,$item);  
                   9412:                 }
                   9413:             }
                   9414:             if (@okstatuses) {
                   9415:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9416:             }
                   9417:         }
                   9418:     }
1.1075    raeburn  9419:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9420:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9421:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9422:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9423:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9424:     } else {
                   9425:         $logmsg .= ' during self creation';
                   9426:     }
1.1075    raeburn  9427:     my $changed;
                   9428:     if ($newuser) {
                   9429:         $changed = 1;
                   9430:     } else {
                   9431:         foreach my $field (@fields) {
                   9432:             if ($names{$field} ne $oldnames{$field}) {
                   9433:                 $changed = 1;
                   9434:                 last;
                   9435:             }
                   9436:         }
                   9437:     }
                   9438:     unless ($changed) {
                   9439:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9440:         &logthis($logmsg);
                   9441:         return 'ok';
                   9442:     }
                   9443:     my $reply = &put('environment', \%names, $udom,$uname);
                   9444:     if ($reply ne 'ok') { 
                   9445:         return 'error: '.$reply;
                   9446:     }
1.1087    raeburn  9447:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9448:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9449:     }
1.1075    raeburn  9450:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9451:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9452:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9453:     &logthis($logmsg);
1.134     albertel 9454:     return 'ok';
1.80      www      9455: }
                   9456: 
1.81      www      9457: # -------------------------------------------------------------- Modify student
1.80      www      9458: 
1.81      www      9459: sub modifystudent {
                   9460:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9461:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9462:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9463:     if (!$cid) {
1.620     albertel 9464: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9465: 	    return 'not_in_class';
                   9466: 	}
1.80      www      9467:     }
                   9468: # --------------------------------------------------------------- Make the user
1.81      www      9469:     my $reply=&modifyuser
1.209     matthew  9470: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9471:          $desiredhome,$email,$inststatus);
1.80      www      9472:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9473:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9474:     # student's environment
1.297     matthew  9475:     $uid = undef if (!$forceid);
1.455     albertel 9476:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9477: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9478:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9479:     return $reply;
                   9480: }
                   9481: 
                   9482: sub modify_student_enrollment {
1.1172.2.23  raeburn  9483:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9484:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9485:     my ($cdom,$cnum,$chome);
                   9486:     if (!$cid) {
1.620     albertel 9487: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9488: 	    return 'not_in_class';
                   9489: 	}
1.620     albertel 9490: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9491: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9492:     } else {
                   9493: 	($cdom,$cnum)=split(/_/,$cid);
                   9494:     }
1.620     albertel 9495:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9496:     if (!$chome) {
1.457     raeburn  9497: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9498:     }
1.455     albertel 9499:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9500:     # Make sure the user exists
1.81      www      9501:     my $uhome=&homeserver($uname,$udom);
                   9502:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9503: 	return 'error: no such user';
                   9504:     }
1.297     matthew  9505:     # Get student data if we were not given enough information
                   9506:     if (!defined($first)  || $first  eq '' || 
                   9507:         !defined($last)   || $last   eq '' || 
                   9508:         !defined($uid)    || $uid    eq '' || 
                   9509:         !defined($middle) || $middle eq '' || 
                   9510:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9511:         # They did not supply us with enough data to enroll the student, so
                   9512:         # we need to pick up more information.
1.297     matthew  9513:         my %tmp = &get('environment',
1.294     matthew  9514:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9515:                        ,$udom,$uname);
                   9516: 
1.800     albertel 9517:         #foreach my $key (keys(%tmp)) {
                   9518:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9519:         #}
1.294     matthew  9520:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9521:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9522:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9523:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9524:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9525:     }
1.556     albertel 9526:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9527:     my $user = "$uname:$udom";
                   9528:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9529:     my $reply=cput('classlist',
1.1148    raeburn  9530: 		   {$user => 
1.1172.2.76  raeburn  9531: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9532: 		   $cdom,$cnum);
1.1148    raeburn  9533:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9534:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9535:     } else { 
1.81      www      9536: 	return 'error: '.$reply;
                   9537:     }
1.297     matthew  9538:     # Add student role to user
1.83      www      9539:     my $uurl='/'.$cid;
1.81      www      9540:     $uurl=~s/\_/\//g;
                   9541:     if ($usec) {
                   9542: 	$uurl.='/'.$usec;
                   9543:     }
1.1148    raeburn  9544:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9545:                              $selfenroll,$context);
                   9546:     if ($result ne 'ok') {
                   9547:         if ($old_entry{$user} ne '') {
                   9548:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9549:         } else {
                   9550:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9551:         }
                   9552:     }
                   9553:     return $result; 
1.21      www      9554: }
                   9555: 
1.556     albertel 9556: sub format_name {
                   9557:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9558:     my $name;
                   9559:     if ($first ne 'lastname') {
                   9560: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9561:     } else {
                   9562: 	if ($lastname=~/\S/) {
                   9563: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9564: 	    $name=~s/\s+,/,/;
                   9565: 	} else {
                   9566: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9567: 	}
                   9568:     }
                   9569:     $name=~s/^\s+//;
                   9570:     $name=~s/\s+$//;
                   9571:     $name=~s/\s+/ /g;
                   9572:     return $name;
                   9573: }
                   9574: 
1.84      www      9575: # ------------------------------------------------- Write to course preferences
                   9576: 
                   9577: sub writecoursepref {
                   9578:     my ($courseid,%prefs)=@_;
                   9579:     $courseid=~s/^\///;
                   9580:     $courseid=~s/\_/\//g;
                   9581:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9582:     my $chome=homeserver($cnum,$cdomain);
                   9583:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9584: 	return 'error: no such course';
                   9585:     }
                   9586:     my $cstring='';
1.800     albertel 9587:     foreach my $pref (keys(%prefs)) {
                   9588: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9589:     }
1.84      www      9590:     $cstring=~s/\&$//;
                   9591:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9592: }
                   9593: 
                   9594: # ---------------------------------------------------------- Make/modify course
                   9595: 
                   9596: sub createcourse {
1.741     raeburn  9597:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9598:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9599:     $url=&declutter($url);
                   9600:     my $cid='';
1.1028    raeburn  9601:     if ($context eq 'requestcourses') {
                   9602:         my $can_create = 0;
                   9603:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9604:         if ($udom eq $ownerdom) {
                   9605:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9606:                                   $context)) {
                   9607:                 $can_create = 1;
                   9608:             }
                   9609:         } else {
                   9610:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9611:                                            $category);
                   9612:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9613:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9614:                 if (@curr > 0) {
                   9615:                     my @options = qw(approval validate autolimit);
                   9616:                     my $optregex = join('|',@options);
                   9617:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9618:                         $can_create = 1;
                   9619:                     }
                   9620:                 }
                   9621:             }
                   9622:         }
                   9623:         if ($can_create) {
                   9624:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9625:                 unless (&allowed('ccc',$udom)) {
                   9626:                     return 'refused'; 
                   9627:                 }
1.1017    raeburn  9628:             }
                   9629:         } else {
                   9630:             return 'refused';
                   9631:         }
1.1028    raeburn  9632:     } elsif (!&allowed('ccc',$udom)) {
                   9633:         return 'refused';
1.84      www      9634:     }
1.1011    raeburn  9635: # --------------------------------------------------------------- Get Unique ID
                   9636:     my $uname;
                   9637:     if ($cnum =~ /^$match_courseid$/) {
                   9638:         my $chome=&homeserver($cnum,$udom,'true');
                   9639:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9640:             $uname = $cnum;
                   9641:         } else {
1.1038    raeburn  9642:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9643:         }
                   9644:     } else {
1.1038    raeburn  9645:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9646:     }
                   9647:     return $uname if ($uname =~ /^error/);
                   9648: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9649:     if (!defined($course_server)) {
                   9650:         if (defined(&domain($udom,'primary'))) {
                   9651:             $course_server = &domain($udom,'primary');
                   9652:         } else {
                   9653:             $course_server = $env{'user.home'}; 
                   9654:         }
                   9655:     }
                   9656:     my %host_servers =
                   9657:         &Apache::lonnet::get_servers($udom,'library');
                   9658:     unless ($host_servers{$course_server}) {
                   9659:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9660:     }
1.84      www      9661: # ------------------------------------------------------------- Make the course
                   9662:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9663:                       $course_server);
1.84      www      9664:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9665:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9666:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9667: 	return 'error: no such course';
                   9668:     }
1.271     www      9669: # ----------------------------------------------------------------- Course made
1.516     raeburn  9670: # log existence
1.1029    raeburn  9671:     my $now = time;
1.918     raeburn  9672:     my $newcourse = {
                   9673:                     $udom.'_'.$uname => {
1.921     raeburn  9674:                                      description => $description,
                   9675:                                      inst_code   => $inst_code,
                   9676:                                      owner       => $course_owner,
                   9677:                                      type        => $crstype,
1.1029    raeburn  9678:                                      creator     => $env{'user.name'}.':'.
                   9679:                                                     $env{'user.domain'},
                   9680:                                      created     => $now,
                   9681:                                      context     => $context,
1.918     raeburn  9682:                                                 },
                   9683:                     };
1.921     raeburn  9684:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9685: # set toplevel url
1.271     www      9686:     my $topurl=$url;
                   9687:     unless ($nonstandard) {
                   9688: # ------------------------------------------ For standard courses, make top url
                   9689:         my $mapurl=&clutter($url);
1.278     www      9690:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9691:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9692: <map>
                   9693: <resource id="1" type="start"></resource>
                   9694: <resource id="2" src="$mapurl"></resource>
                   9695: <resource id="3" type="finish"></resource>
                   9696: <link index="1" from="1" to="2"></link>
                   9697: <link index="2" from="2" to="3"></link>
                   9698: </map>
                   9699: ENDINITMAP
                   9700:         $topurl=&declutter(
1.638     albertel 9701:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9702:                           );
                   9703:     }
                   9704: # ----------------------------------------------------------- Write preferences
1.84      www      9705:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9706:                      ('description'              => $description,
                   9707:                       'url'                      => $topurl,
                   9708:                       'internal.creator'         => $env{'user.name'}.':'.
                   9709:                                                     $env{'user.domain'},
                   9710:                       'internal.created'         => $now,
                   9711:                       'internal.creationcontext' => $context)
                   9712:                     );
1.84      www      9713:     return '/'.$udom.'/'.$uname;
                   9714: }
                   9715: 
1.1011    raeburn  9716: # ------------------------------------------------------------------- Create ID
                   9717: sub generate_coursenum {
1.1038    raeburn  9718:     my ($udom,$crstype) = @_;
1.1011    raeburn  9719:     my $domdesc = &domain($udom);
                   9720:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9721:     my $first;
                   9722:     if ($crstype eq 'Community') {
                   9723:         $first = '0';
                   9724:     } else {
                   9725:         $first = int(1+rand(9)); 
                   9726:     } 
                   9727:     my $uname=$first.
1.1011    raeburn  9728:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9729:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9730:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9731: # ----------------------------------------------- Make sure that does not exist
                   9732:     my $uhome=&homeserver($uname,$udom,'true');
                   9733:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9734:         if ($crstype eq 'Community') {
                   9735:             $first = '0';
                   9736:         } else {
                   9737:             $first = int(1+rand(9));
                   9738:         }
                   9739:         $uname=$first.
1.1011    raeburn  9740:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9741:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9742:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9743:         $uhome=&homeserver($uname,$udom,'true');
                   9744:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9745:             return 'error: unable to generate unique course-ID';
                   9746:         }
                   9747:     }
                   9748:     return $uname;
                   9749: }
                   9750: 
1.813     albertel 9751: sub is_course {
1.1167    droeschl 9752:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9753:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9754:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9755:     my $uhome=&homeserver($cnum,$cdom);
                   9756:     my $iscourse;
                   9757:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9758:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9759:     } else {
                   9760:         my $hashid = $cdom.':'.$cnum;
                   9761:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9762:         unless (defined($cached)) {
                   9763:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9764:                                         $cnum,undef,undef,'.');
                   9765:             $iscourse = 0;
                   9766:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9767:                 $iscourse = 1;
                   9768:             }
                   9769:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9770:         }
                   9771:     }
                   9772:     return unless($iscourse);
1.1167    droeschl 9773:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9774: }
                   9775: 
1.1015    raeburn  9776: sub store_userdata {
                   9777:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9778:     my $result;
1.1016    raeburn  9779:     if ($datakey ne '') {
1.1013    raeburn  9780:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9781:             if ($udom eq '' || $uname eq '') {
                   9782:                 $udom = $env{'user.domain'};
                   9783:                 $uname = $env{'user.name'};
                   9784:             }
                   9785:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9786:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9787:                 $result = 'error: no_host';
                   9788:             } else {
                   9789:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9790:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9791: 
                   9792:                 my $namevalue='';
                   9793:                 foreach my $key (keys(%{$storehash})) {
                   9794:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9795:                 }
                   9796:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9797:                 unless ($namespace eq 'courserequests') {
                   9798:                     $datakey = &escape($datakey);
                   9799:                 }
1.1105    raeburn  9800:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9801:                                   $namevalue,$uhome);
1.1013    raeburn  9802:             }
                   9803:         } else {
                   9804:             $result = 'error: data to store was not a hash reference'; 
                   9805:         }
                   9806:     } else {
                   9807:         $result= 'error: invalid requestkey'; 
                   9808:     }
                   9809:     return $result;
                   9810: }
                   9811: 
1.21      www      9812: # ---------------------------------------------------------- Assign Custom Role
                   9813: 
                   9814: sub assigncustomrole {
1.957     raeburn  9815:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9816:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9817:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9818: }
                   9819: 
                   9820: # ----------------------------------------------------------------- Revoke Role
                   9821: 
                   9822: sub revokerole {
1.957     raeburn  9823:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9824:     my $now=time;
1.965     raeburn  9825:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9826: }
                   9827: 
                   9828: # ---------------------------------------------------------- Revoke Custom Role
                   9829: 
                   9830: sub revokecustomrole {
1.957     raeburn  9831:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9832:     my $now=time;
1.357     www      9833:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9834:            $deleteflag,$selfenroll,$context);
1.17      www      9835: }
                   9836: 
1.533     banghart 9837: # ------------------------------------------------------------ Disk usage
1.535     albertel 9838: sub diskusage {
1.955     raeburn  9839:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9840:     $directorypath =~ s/\/$//;
                   9841:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9842:                        .&escape($getpropath).':'.&escape($uname).':'
                   9843:                        .&escape($udom),homeserver($uname,$udom));
                   9844:     if ($listing eq 'unknown_cmd') {
                   9845:         if ($getpropath) {
                   9846:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9847:         }
                   9848:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9849:     }
1.514     albertel 9850:     return $listing;
1.512     banghart 9851: }
                   9852: 
1.566     banghart 9853: sub is_locked {
1.1096    raeburn  9854:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9855:     my @check;
                   9856:     my $is_locked;
1.1093    raeburn  9857:     push (@check,$file_name);
1.613     albertel 9858:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9859: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9860:     my ($tmp)=keys(%locked);
                   9861:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9862:     
1.566     banghart 9863:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9864:         $is_locked = 'false';
                   9865:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9866:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9867:                $is_locked = 'true';
1.1096    raeburn  9868:                if (ref($which) eq 'ARRAY') {
                   9869:                    push(@{$which},$entry);
                   9870:                } else {
                   9871:                    last;
                   9872:                }
1.745     raeburn  9873:            }
                   9874:        }
1.566     banghart 9875:     } else {
                   9876:         $is_locked = 'false';
                   9877:     }
1.1093    raeburn  9878:     return $is_locked;
1.566     banghart 9879: }
                   9880: 
1.759     albertel 9881: sub declutter_portfile {
                   9882:     my ($file) = @_;
1.833     albertel 9883:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9884:     return $file;
                   9885: }
                   9886: 
1.559     banghart 9887: # ------------------------------------------------------------- Mark as Read Only
                   9888: 
                   9889: sub mark_as_readonly {
                   9890:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9891:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9892:     my ($tmp)=keys(%current_permissions);
                   9893:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9894:     foreach my $file (@{$files}) {
1.759     albertel 9895: 	$file = &declutter_portfile($file);
1.561     banghart 9896:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9897:     }
1.613     albertel 9898:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9899:     return;
                   9900: }
                   9901: 
1.572     banghart 9902: # ------------------------------------------------------------Save Selected Files
                   9903: 
                   9904: sub save_selected_files {
                   9905:     my ($user, $path, @files) = @_;
                   9906:     my $filename = $user."savedfiles";
1.573     banghart 9907:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  9908:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 9909:     foreach my $file (@files) {
1.620     albertel 9910:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9911:     }
                   9912:     foreach my $file (@other_files) {
1.574     banghart 9913:         print (OUT $file."\n");
1.572     banghart 9914:     }
1.574     banghart 9915:     close (OUT);
1.572     banghart 9916:     return 'ok';
                   9917: }
                   9918: 
1.574     banghart 9919: sub clear_selected_files {
                   9920:     my ($user) = @_;
                   9921:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  9922:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 9923:     print (OUT undef);
                   9924:     close (OUT);
                   9925:     return ("ok");    
                   9926: }
                   9927: 
1.572     banghart 9928: sub files_in_path {
                   9929:     my ($user, $path) = @_;
                   9930:     my $filename = $user."savedfiles";
                   9931:     my %return_files;
1.1172.2.96  raeburn  9932:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 9933:     while (my $line_in = <IN>) {
1.574     banghart 9934:         chomp ($line_in);
                   9935:         my @paths_and_file = split (m!/!, $line_in);
                   9936:         my $file_part = pop (@paths_and_file);
                   9937:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9938:         $path_part.='/';
                   9939:         my $path_and_file = $path_part.$file_part;
                   9940:         if ($path_part eq $path) {
                   9941:             $return_files{$file_part}= 'selected';
                   9942:         }
                   9943:     }
1.574     banghart 9944:     close (IN);
                   9945:     return (\%return_files);
1.572     banghart 9946: }
                   9947: 
                   9948: # called in portfolio select mode, to show files selected NOT in current directory
                   9949: sub files_not_in_path {
                   9950:     my ($user, $path) = @_;
                   9951:     my $filename = $user."savedfiles";
                   9952:     my @return_files;
                   9953:     my $path_part;
1.1172.2.96  raeburn  9954:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 9955:     while (my $line = <IN>) {
1.572     banghart 9956:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9957:         my @paths_and_file = split(m|/|, $line);
                   9958:         my $file_part = pop(@paths_and_file);
                   9959:         chomp($file_part);
                   9960:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9961:         $path_part .= '/';
                   9962:         my $path_and_file = $path_part.$file_part;
                   9963:         if ($path_part ne $path) {
1.800     albertel 9964:             push(@return_files, ($path_and_file));
1.572     banghart 9965:         }
                   9966:     }
1.800     albertel 9967:     close(OUT);
1.574     banghart 9968:     return (@return_files);
1.572     banghart 9969: }
                   9970: 
1.745     raeburn  9971: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9972: 
1.745     raeburn  9973: sub get_portfile_permissions {
                   9974:     my ($domain,$user) = @_;
1.613     albertel 9975:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9976:     my ($tmp)=keys(%current_permissions);
                   9977:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9978:     return \%current_permissions;
                   9979: }
                   9980: 
                   9981: #---------------------------------------------Get portfolio file access controls
                   9982: 
1.749     raeburn  9983: sub get_access_controls {
1.745     raeburn  9984:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9985:     my %access;
                   9986:     my $real_file = $file;
                   9987:     $file =~ s/\.meta$//;
1.745     raeburn  9988:     if (defined($file)) {
1.749     raeburn  9989:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9990:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9991:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9992:             }
                   9993:         }
1.745     raeburn  9994:     } else {
1.749     raeburn  9995:         foreach my $key (keys(%{$current_permissions})) {
                   9996:             if ($key =~ /\0accesscontrol$/) {
                   9997:                 if (defined($group)) {
                   9998:                     if ($key !~ m-^\Q$group\E/-) {
                   9999:                         next;
                   10000:                     }
                   10001:                 }
                   10002:                 my ($fullpath) = split(/\0/,$key);
                   10003:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10004:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10005:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10006:                     }
                   10007:                 }
                   10008:             }
                   10009:         }
                   10010:     }
                   10011:     return %access;
                   10012: }
                   10013: 
                   10014: sub modify_access_controls {
                   10015:     my ($file_name,$changes,$domain,$user)=@_;
                   10016:     my ($outcome,$deloutcome);
                   10017:     my %store_permissions;
                   10018:     my %new_values;
                   10019:     my %new_control;
                   10020:     my %translation;
                   10021:     my @deletions = ();
                   10022:     my $now = time;
                   10023:     if (exists($$changes{'activate'})) {
                   10024:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10025:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10026:             my $numnew = scalar(@newitems);
                   10027:             for (my $i=0; $i<$numnew; $i++) {
                   10028:                 my $newkey = $newitems[$i];
                   10029:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10030:                 if ($newkey =~ /^\d+:/) { 
                   10031:                     $newkey =~ s/^(\d+)/$newid/;
                   10032:                     $translation{$1} = $newid;
                   10033:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10034:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10035:                     $translation{$1} = $newid;
                   10036:                 }
1.749     raeburn  10037:                 $new_values{$file_name."\0".$newkey} = 
                   10038:                                           $$changes{'activate'}{$newitems[$i]};
                   10039:                 $new_control{$newkey} = $now;
                   10040:             }
                   10041:         }
                   10042:     }
                   10043:     my %todelete;
                   10044:     my %changed_items;
                   10045:     foreach my $action ('delete','update') {
                   10046:         if (exists($$changes{$action})) {
                   10047:             if (ref($$changes{$action}) eq 'HASH') {
                   10048:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10049:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10050:                     if ($action eq 'delete') { 
                   10051:                         $todelete{$itemnum} = 1;
                   10052:                     } else {
                   10053:                         $changed_items{$itemnum} = $key;
                   10054:                     }
                   10055:                 }
1.745     raeburn  10056:             }
                   10057:         }
1.749     raeburn  10058:     }
                   10059:     # get lock on access controls for file.
                   10060:     my $lockhash = {
                   10061:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10062:                                                        ':'.$env{'user.domain'},
                   10063:                    }; 
                   10064:     my $tries = 0;
                   10065:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10066:    
1.1172.2.79  raeburn  10067:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10068:         $tries ++;
1.1172.2.79  raeburn  10069:         sleep(0.1);
1.749     raeburn  10070:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10071:     }
                   10072:     if ($gotlock eq 'ok') {
                   10073:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10074:         my ($tmp)=keys(%curr_permissions);
                   10075:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10076:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10077:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10078:             if (ref($curr_controls) eq 'HASH') {
                   10079:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10080:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10081:                     if (defined($todelete{$itemnum})) {
                   10082:                         push(@deletions,$file_name."\0".$control_item);
                   10083:                     } else {
                   10084:                         if (defined($changed_items{$itemnum})) {
                   10085:                             $new_control{$changed_items{$itemnum}} = $now;
                   10086:                             push(@deletions,$file_name."\0".$control_item);
                   10087:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10088:                         } else {
                   10089:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10090:                         }
                   10091:                     }
1.745     raeburn  10092:                 }
                   10093:             }
                   10094:         }
1.970     raeburn  10095:         my ($group);
                   10096:         if (&is_course($domain,$user)) {
                   10097:             ($group,my $file) = split(/\//,$file_name,2);
                   10098:         }
1.749     raeburn  10099:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10100:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10101:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10102:         #  remove lock
                   10103:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10104:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10105:         my $sqlresult =
1.970     raeburn  10106:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10107:                                     $group);
1.749     raeburn  10108:     } else {
                   10109:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10110:     }
1.749     raeburn  10111:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10112: }
                   10113: 
1.827     raeburn  10114: sub make_public_indefinitely {
                   10115:     my ($requrl) = @_;
                   10116:     my $now = time;
                   10117:     my $action = 'activate';
                   10118:     my $aclnum = 0;
                   10119:     if (&is_portfolio_url($requrl)) {
                   10120:         my (undef,$udom,$unum,$file_name,$group) =
                   10121:             &parse_portfolio_url($requrl);
                   10122:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10123:         my %access_controls = &get_access_controls($current_perms,
                   10124:                                                    $group,$file_name);
                   10125:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10126:             my ($num,$scope,$end,$start) = 
                   10127:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10128:             if ($scope eq 'public') {
                   10129:                 if ($start <= $now && $end == 0) {
                   10130:                     $action = 'none';
                   10131:                 } else {
                   10132:                     $action = 'update';
                   10133:                     $aclnum = $num;
                   10134:                 }
                   10135:                 last;
                   10136:             }
                   10137:         }
                   10138:         if ($action eq 'none') {
                   10139:              return 'ok';
                   10140:         } else {
                   10141:             my %changes;
                   10142:             my $newend = 0;
                   10143:             my $newstart = $now;
                   10144:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10145:             $changes{$action}{$newkey} = {
                   10146:                 type => 'public',
                   10147:                 time => {
                   10148:                     start => $newstart,
                   10149:                     end   => $newend,
                   10150:                 },
                   10151:             };
                   10152:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10153:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10154:             return $outcome;
                   10155:         }
                   10156:     } else {
                   10157:         return 'invalid';
                   10158:     }
                   10159: }
                   10160: 
1.745     raeburn  10161: #------------------------------------------------------Get Marked as Read Only
                   10162: 
                   10163: sub get_marked_as_readonly {
                   10164:     my ($domain,$user,$what,$group) = @_;
                   10165:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10166:     my @readonly_files;
1.629     banghart 10167:     my $cmp1=$what;
                   10168:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10169:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10170:         if (defined($group)) {
                   10171:             if ($file_name !~ m-^\Q$group\E/-) {
                   10172:                 next;
                   10173:             }
                   10174:         }
1.561     banghart 10175:         if (ref($value) eq "ARRAY"){
                   10176:             foreach my $stored_what (@{$value}) {
1.629     banghart 10177:                 my $cmp2=$stored_what;
1.759     albertel 10178:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10179:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10180:                 }
1.629     banghart 10181:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10182:                     push(@readonly_files, $file_name);
1.745     raeburn  10183:                     last;
1.563     banghart 10184:                 } elsif (!defined($what)) {
                   10185:                     push(@readonly_files, $file_name);
1.745     raeburn  10186:                     last;
1.561     banghart 10187:                 }
                   10188:             }
1.745     raeburn  10189:         }
1.561     banghart 10190:     }
                   10191:     return @readonly_files;
                   10192: }
1.577     banghart 10193: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10194: 
1.577     banghart 10195: sub get_marked_as_readonly_hash {
1.745     raeburn  10196:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10197:     my %readonly_files;
1.745     raeburn  10198:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10199:         if (defined($group)) {
                   10200:             if ($file_name !~ m-^\Q$group\E/-) {
                   10201:                 next;
                   10202:             }
                   10203:         }
1.577     banghart 10204:         if (ref($value) eq "ARRAY"){
                   10205:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10206:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10207:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10208:                         if ($lock_descriptor eq 'graded') {
                   10209:                             $readonly_files{$file_name} = 'graded';
                   10210:                         } elsif ($lock_descriptor eq 'handback') {
                   10211:                             $readonly_files{$file_name} = 'handback';
                   10212:                         } else {
                   10213:                             if (!exists($readonly_files{$file_name})) {
                   10214:                                 $readonly_files{$file_name} = 'locked';
                   10215:                             }
                   10216:                         }
1.745     raeburn  10217:                     }
1.750     banghart 10218:                 } 
1.577     banghart 10219:             }
                   10220:         } 
                   10221:     }
                   10222:     return %readonly_files;
                   10223: }
1.559     banghart 10224: # ------------------------------------------------------------ Unmark as Read Only
                   10225: 
                   10226: sub unmark_as_readonly {
1.629     banghart 10227:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10228:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10229:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10230:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10231:     my $symb_crs = $what;
                   10232:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10233:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10234:     my ($tmp)=keys(%current_permissions);
                   10235:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10236:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10237:     foreach my $file (@readonly_files) {
1.759     albertel 10238: 	my $clean_file = &declutter_portfile($file);
                   10239: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10240: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10241:         my @new_locks;
                   10242:         my @del_keys;
                   10243:         if (ref($current_locks) eq "ARRAY"){
                   10244:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10245:                 my $compare=$locker;
1.749     raeburn  10246:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10247:                     $compare=join('',@{$locker});
1.746     raeburn  10248:                     if ($compare ne $symb_crs) {
                   10249:                         push(@new_locks, $locker);
                   10250:                     }
1.563     banghart 10251:                 }
                   10252:             }
1.650     albertel 10253:             if (scalar(@new_locks) > 0) {
1.563     banghart 10254:                 $current_permissions{$file} = \@new_locks;
                   10255:             } else {
                   10256:                 push(@del_keys, $file);
1.613     albertel 10257:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10258:                 delete($current_permissions{$file});
1.563     banghart 10259:             }
                   10260:         }
1.561     banghart 10261:     }
1.613     albertel 10262:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10263:     return;
                   10264: }
1.512     banghart 10265: 
1.17      www      10266: # ------------------------------------------------------------ Directory lister
                   10267: 
                   10268: sub dirlist {
1.955     raeburn  10269:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10270:     $uri=~s/^\///;
                   10271:     $uri=~s/\/$//;
1.253     stredwic 10272:     my ($udom, $uname);
1.955     raeburn  10273:     if ($getuserdir) {
1.253     stredwic 10274:         $udom = $userdomain;
                   10275:         $uname = $username;
1.955     raeburn  10276:     } else {
                   10277:         (undef,$udom,$uname)=split(/\//,$uri);
                   10278:         if(defined($userdomain)) {
                   10279:             $udom = $userdomain;
                   10280:         }
                   10281:         if(defined($username)) {
                   10282:             $uname = $username;
                   10283:         }
1.253     stredwic 10284:     }
1.955     raeburn  10285:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10286: 
1.955     raeburn  10287:     $dirRoot = $perlvar{'lonDocRoot'};
                   10288:     if (defined($getpropath)) {
                   10289:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10290:         $dirRoot =~ s/\/$//;
1.955     raeburn  10291:     } elsif (defined($getuserdir)) {
                   10292:         my $subdir=$uname.'__';
                   10293:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10294:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10295:                    ."/$udom/$subdir/$uname";
                   10296:     } elsif (defined($alternateRoot)) {
                   10297:         $dirRoot = $alternateRoot;
1.751     banghart 10298:     }
1.253     stredwic 10299: 
                   10300:     if($udom) {
                   10301:         if($uname) {
1.1135    raeburn  10302:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10303:             if ($uhome eq 'no_host') {
                   10304:                 return ([],'no_host');
                   10305:             }
1.955     raeburn  10306:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10307:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10308:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10309:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10310:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10311:             } else {
                   10312:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10313:             }
1.605     matthew  10314:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10315:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10316:                 @listing_results = split(/:/,$listing);
                   10317:             } else {
                   10318:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10319:             }
1.1135    raeburn  10320:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10321:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10322:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10323:                 return ([],$listing);
                   10324:             } else {
                   10325:                 return (\@listing_results);
1.1135    raeburn  10326:             }
1.955     raeburn  10327:         } elsif(!$alternateRoot) {
1.1136    raeburn  10328:             my (%allusers,%listerror);
1.841     albertel 10329: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10330:  	    foreach my $tryserver (keys(%servers)) {
                   10331:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10332:                                   &escape($udom),$tryserver);
                   10333:                 if ($listing eq 'unknown_cmd') {
                   10334: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10335: 				      $udom, $tryserver);
                   10336:                 } else {
                   10337:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10338:                 }
1.841     albertel 10339: 		if ($listing eq 'unknown_cmd') {
                   10340: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10341: 				      $udom, $tryserver);
                   10342: 		    @listing_results = split(/:/,$listing);
                   10343: 		} else {
                   10344: 		    @listing_results =
                   10345: 			map { &unescape($_); } split(/:/,$listing);
                   10346: 		}
1.1136    raeburn  10347:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10348:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10349:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10350:                     $listerror{$tryserver} = $listing;
                   10351:                 } else {
1.841     albertel 10352: 		    foreach my $line (@listing_results) {
                   10353: 			my ($entry) = split(/&/,$line,2);
                   10354: 			$allusers{$entry} = 1;
                   10355: 		    }
                   10356: 		}
1.253     stredwic 10357:             }
1.1136    raeburn  10358:             my @alluserslist=();
1.800     albertel 10359:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10360:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10361:             }
1.1172.2.80  raeburn  10362:             if (!%listerror) {
                   10363:                 # no errors
                   10364:                 return (\@alluserslist);
                   10365:             } elsif (scalar(keys(%servers)) == 1) {
                   10366:                 # one library server, one error
                   10367:                 my ($key) = keys(%listerror);
                   10368:                 return (\@alluserslist, $listerror{$key});
                   10369:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10370:                 # con_lost indicates that we might miss data from at least one
                   10371:                 # library server
                   10372:                 return (\@alluserslist, 'con_lost');
                   10373:             } else {
                   10374:                 # multiple library servers and no con_lost -> data should be
                   10375:                 # complete.
                   10376:                 return (\@alluserslist);
                   10377:             }
                   10378: 
1.253     stredwic 10379:         } else {
1.1136    raeburn  10380:             return ([],'missing username');
1.253     stredwic 10381:         }
1.955     raeburn  10382:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10383:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10384:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10385:         return (\@all_domains);
1.955     raeburn  10386:     } else {
1.1136    raeburn  10387:         return ([],'missing domain');
1.275     stredwic 10388:     }
                   10389: }
                   10390: 
                   10391: # --------------------------------------------- GetFileTimestamp
                   10392: # This function utilizes dirlist and returns the date stamp for
                   10393: # when it was last modified.  It will also return an error of -1
                   10394: # if an error occurs
                   10395: 
                   10396: sub GetFileTimestamp {
1.955     raeburn  10397:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10398:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10399:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10400:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10401:                                     undef,$getuserdir);
                   10402:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10403:         return -1;
                   10404:     }
                   10405:     if (ref($fileref) eq 'ARRAY') {
                   10406:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10407:         # @stats contains first the filename, then the stat output
                   10408:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10409:     } else {
                   10410:         return -1;
1.253     stredwic 10411:     }
1.26      www      10412: }
                   10413: 
1.712     albertel 10414: sub stat_file {
                   10415:     my ($uri) = @_;
1.787     albertel 10416:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10417: 
1.955     raeburn  10418:     my ($udom,$uname,$file);
1.712     albertel 10419:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10420: 	($udom,$uname,$file) =
1.811     albertel 10421: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10422: 	$file = 'userfiles/'.$file;
                   10423:     }
                   10424:     if ($uri =~ m-^/res/-) {
                   10425: 	($udom,$uname) = 
1.807     albertel 10426: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10427: 	$file = $uri;
                   10428:     }
                   10429: 
                   10430:     if (!$udom || !$uname || !$file) {
                   10431: 	# unable to handle the uri
                   10432: 	return ();
                   10433:     }
1.956     raeburn  10434:     my $getpropath;
                   10435:     if ($file =~ /^userfiles\//) {
                   10436:         $getpropath = 1;
                   10437:     }
1.1136    raeburn  10438:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10439:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10440:         return ();
                   10441:     } else {
                   10442:         if (ref($listref) eq 'ARRAY') {
                   10443:             my @stats = split('&',$listref->[0]);
                   10444: 	    shift(@stats); #filename is first
                   10445: 	    return @stats;
                   10446:         }
1.712     albertel 10447:     }
                   10448:     return ();
                   10449: }
                   10450: 
1.26      www      10451: # -------------------------------------------------------- Value of a Condition
                   10452: 
1.713     albertel 10453: # gets the value of a specific preevaluated condition
                   10454: #    stored in the string  $env{user.state.<cid>}
                   10455: # or looks up a condition reference in the bighash and if if hasn't
                   10456: # already been evaluated recurses into docondval to get the value of
                   10457: # the condition, then memoizing it to 
                   10458: #   $env{user.state.<cid>.<condition>}
1.40      www      10459: sub directcondval {
                   10460:     my $number=shift;
1.620     albertel 10461:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10462: 	&Apache::lonuserstate::evalstate();
                   10463:     }
1.713     albertel 10464:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10465: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10466:     } elsif ($number =~ /^_/) {
                   10467: 	my $sub_condition;
                   10468: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10469: 		&GDBM_READER(),0640)) {
                   10470: 	    $sub_condition=$bighash{'conditions'.$number};
                   10471: 	    untie(%bighash);
                   10472: 	}
                   10473: 	my $value = &docondval($sub_condition);
1.949     raeburn  10474: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10475: 	return $value;
                   10476:     }
1.620     albertel 10477:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10478:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10479:     } else {
                   10480:        return 2;
                   10481:     }
                   10482: }
                   10483: 
1.713     albertel 10484: # get the collection of conditions for this resource
1.26      www      10485: sub condval {
                   10486:     my $condidx=shift;
1.54      www      10487:     my $allpathcond='';
1.713     albertel 10488:     foreach my $cond (split(/\|/,$condidx)) {
                   10489: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10490: 	    $allpathcond.=
                   10491: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10492: 	}
1.191     harris41 10493:     }
1.54      www      10494:     $allpathcond=~s/\|$//;
1.713     albertel 10495:     return &docondval($allpathcond);
                   10496: }
                   10497: 
                   10498: #evaluates an expression of conditions
                   10499: sub docondval {
                   10500:     my ($allpathcond) = @_;
                   10501:     my $result=0;
                   10502:     if ($env{'request.course.id'}
                   10503: 	&& defined($allpathcond)) {
                   10504: 	my $operand='|';
                   10505: 	my @stack;
                   10506: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10507: 	    if ($chunk eq '(') {
                   10508: 		push @stack,($operand,$result);
                   10509: 	    } elsif ($chunk eq ')') {
                   10510: 		my $before=pop @stack;
                   10511: 		if (pop @stack eq '&') {
                   10512: 		    $result=$result>$before?$before:$result;
                   10513: 		} else {
                   10514: 		    $result=$result>$before?$result:$before;
                   10515: 		}
                   10516: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10517: 		$operand=$chunk;
                   10518: 	    } else {
                   10519: 		my $new=directcondval($chunk);
                   10520: 		if ($operand eq '&') {
                   10521: 		    $result=$result>$new?$new:$result;
                   10522: 		} else {
                   10523: 		    $result=$result>$new?$result:$new;
                   10524: 		}
                   10525: 	    }
                   10526: 	}
1.26      www      10527:     }
                   10528:     return $result;
1.421     albertel 10529: }
                   10530: 
                   10531: # ---------------------------------------------------- Devalidate courseresdata
                   10532: 
                   10533: sub devalidatecourseresdata {
                   10534:     my ($coursenum,$coursedomain)=@_;
                   10535:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10536:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10537: }
                   10538: 
1.763     www      10539: 
1.200     www      10540: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10541: #
                   10542: #  Parameters:
                   10543: #      $coursenum    - Number of the course.
                   10544: #      $coursedomain - Domain at which the course was created.
                   10545: #  Returns:
                   10546: #     A hash of the course parameters along (I think) with timestamps
                   10547: #     and version info.
1.877     foxr     10548: 
1.624     albertel 10549: sub get_courseresdata {
                   10550:     my ($coursenum,$coursedomain)=@_;
1.200     www      10551:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10552:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10553:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10554:     my %dumpreply;
1.417     albertel 10555:     unless (defined($cached)) {
1.624     albertel 10556: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10557: 	$result=\%dumpreply;
1.251     albertel 10558: 	my ($tmp) = keys(%dumpreply);
                   10559: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10560: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10561: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10562: 	    return $tmp;
1.416     albertel 10563: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10564: 	    $result=undef;
1.599     albertel 10565: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10566: 	}
                   10567:     }
1.624     albertel 10568:     return $result;
                   10569: }
                   10570: 
1.633     albertel 10571: sub devalidateuserresdata {
                   10572:     my ($uname,$udom)=@_;
                   10573:     my $hashid="$udom:$uname";
                   10574:     &devalidate_cache_new('userres',$hashid);
                   10575: }
                   10576: 
1.624     albertel 10577: sub get_userresdata {
                   10578:     my ($uname,$udom)=@_;
                   10579:     #most student don\'t have any data set, check if there is some data
                   10580:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10581: 
                   10582:     my $hashid="$udom:$uname";
                   10583:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10584:     if (!defined($cached)) {
                   10585: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10586: 	$result=\%resourcedata;
                   10587: 	&do_cache_new('userres',$hashid,$result,600);
                   10588:     }
                   10589:     my ($tmp)=keys(%$result);
                   10590:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10591: 	return $result;
                   10592:     }
                   10593:     #error 2 occurs when the .db doesn't exist
                   10594:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10595:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10596: 	    &logthis("<font color=\"blue\">WARNING:".
                   10597: 		     " Trying to get resource data for ".
                   10598: 		     $uname." at ".$udom.": ".
                   10599: 		     $tmp."</font>");
                   10600:         }
1.624     albertel 10601:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10602: 	#&EXT_cache_set($udom,$uname);
                   10603: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10604: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10605:     }
                   10606:     return $tmp;
                   10607: }
1.879     foxr     10608: #----------------------------------------------- resdata - return resource data
                   10609: #  Purpose:
                   10610: #    Return resource data for either users or for a course.
                   10611: #  Parameters:
                   10612: #     $name      - Course/user name.
                   10613: #     $domain    - Name of the domain the user/course is registered on.
                   10614: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10615: #     @which     - Array of names of resources desired.
                   10616: #  Returns:
                   10617: #     The value of the first reasource in @which that is found in the
                   10618: #     resource hash.
                   10619: #  Exceptional Conditions:
                   10620: #     If the $type passed in is not valid (not the string 'course' or 
                   10621: #     'user', an undefined  reference is returned.
                   10622: #     If none of the resources are found, an undef is returned
1.624     albertel 10623: sub resdata {
                   10624:     my ($name,$domain,$type,@which)=@_;
                   10625:     my $result;
                   10626:     if ($type eq 'course') {
                   10627: 	$result=&get_courseresdata($name,$domain);
                   10628:     } elsif ($type eq 'user') {
                   10629: 	$result=&get_userresdata($name,$domain);
                   10630:     }
                   10631:     if (!ref($result)) { return $result; }    
1.251     albertel 10632:     foreach my $item (@which) {
1.927     albertel 10633: 	if (defined($result->{$item->[0]})) {
                   10634: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10635: 	}
1.250     albertel 10636:     }
1.291     albertel 10637:     return undef;
1.200     www      10638: }
                   10639: 
1.1172.2.31  raeburn  10640: sub get_numsuppfiles {
                   10641:     my ($cnum,$cdom,$ignorecache)=@_;
                   10642:     my $hashid=$cnum.':'.$cdom;
                   10643:     my ($suppcount,$cached);
                   10644:     unless ($ignorecache) {
                   10645:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10646:     }
                   10647:     unless (defined($cached)) {
                   10648:         my $chome=&homeserver($cnum,$cdom);
                   10649:         unless ($chome eq 'no_host') {
                   10650:             ($suppcount,my $errors) = (0,0);
                   10651:             my $suppmap = 'supplemental.sequence';
                   10652:             ($suppcount,$errors) =
                   10653:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10654:         }
                   10655:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10656:     }
                   10657:     return $suppcount;
                   10658: }
                   10659: 
1.379     matthew  10660: #
                   10661: # EXT resource caching routines
                   10662: #
                   10663: 
                   10664: sub clear_EXT_cache_status {
1.383     albertel 10665:     &delenv('cache.EXT.');
1.379     matthew  10666: }
                   10667: 
                   10668: sub EXT_cache_status {
                   10669:     my ($target_domain,$target_user) = @_;
1.383     albertel 10670:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10671:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10672:         # We know already the user has no data
                   10673:         return 1;
                   10674:     } else {
                   10675:         return 0;
                   10676:     }
                   10677: }
                   10678: 
                   10679: sub EXT_cache_set {
                   10680:     my ($target_domain,$target_user) = @_;
1.383     albertel 10681:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10682:     #&appenv({$cachename => time});
1.379     matthew  10683: }
                   10684: 
1.28      www      10685: # --------------------------------------------------------- Value of a Variable
1.58      www      10686: sub EXT {
1.715     albertel 10687: 
1.1172.2.28  raeburn  10688:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10689:     unless ($varname) { return ''; }
1.218     albertel 10690:     #get real user name/domain, courseid and symb
                   10691:     my $courseid;
1.359     albertel 10692:     my $publicuser;
1.427     www      10693:     if ($symbparm) {
                   10694: 	$symbparm=&get_symb_from_alias($symbparm);
                   10695:     }
1.218     albertel 10696:     if (!($uname && $udom)) {
1.790     albertel 10697:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10698:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10699:     } else {
1.620     albertel 10700: 	$courseid=$env{'request.course.id'};
1.218     albertel 10701:     }
1.48      www      10702:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10703:     my $rest;
1.320     albertel 10704:     if (defined($therest[0])) {
1.48      www      10705:        $rest=join('.',@therest);
                   10706:     } else {
                   10707:        $rest='';
                   10708:     }
1.320     albertel 10709: 
1.57      www      10710:     my $qualifierrest=$qualifier;
                   10711:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10712:     my $spacequalifierrest=$space;
                   10713:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10714:     if ($realm eq 'user') {
1.48      www      10715: # --------------------------------------------------------------- user.resource
                   10716: 	if ($space eq 'resource') {
1.651     albertel 10717: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10718: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10719: 		 &&
1.744     albertel 10720: 		 ($symbparm eq &symbread()) ) {	
                   10721: 		# if we are in the middle of processing the resource the
                   10722: 		# get the value we are planning on committing
                   10723:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10724:                     return $Apache::lonhomework::results{$qualifierrest};
                   10725:                 } else {
                   10726:                     return $Apache::lonhomework::history{$qualifierrest};
                   10727:                 }
1.335     albertel 10728: 	    } else {
1.359     albertel 10729: 		my %restored;
1.620     albertel 10730: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10731: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10732: 		} else {
                   10733: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10734: 		}
1.335     albertel 10735: 		return $restored{$qualifierrest};
                   10736: 	    }
1.48      www      10737: # ----------------------------------------------------------------- user.access
                   10738:         } elsif ($space eq 'access') {
1.218     albertel 10739: 	    # FIXME - not supporting calls for a specific user
1.48      www      10740:             return &allowed($qualifier,$rest);
                   10741: # ------------------------------------------ user.preferences, user.environment
                   10742:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10743: 	    if (($uname eq $env{'user.name'}) &&
                   10744: 		($udom eq $env{'user.domain'})) {
                   10745: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10746: 	    } else {
1.359     albertel 10747: 		my %returnhash;
                   10748: 		if (!$publicuser) {
                   10749: 		    %returnhash=&userenvironment($udom,$uname,
                   10750: 						 $qualifierrest);
                   10751: 		}
1.218     albertel 10752: 		return $returnhash{$qualifierrest};
                   10753: 	    }
1.48      www      10754: # ----------------------------------------------------------------- user.course
                   10755:         } elsif ($space eq 'course') {
1.218     albertel 10756: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10757:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10758: # ------------------------------------------------------------------- user.role
                   10759:         } elsif ($space eq 'role') {
1.218     albertel 10760: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10761:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10762:             if ($qualifier eq 'value') {
                   10763: 		return $role;
                   10764:             } elsif ($qualifier eq 'extent') {
                   10765:                 return $where;
                   10766:             }
                   10767: # ----------------------------------------------------------------- user.domain
                   10768:         } elsif ($space eq 'domain') {
1.218     albertel 10769:             return $udom;
1.48      www      10770: # ------------------------------------------------------------------- user.name
                   10771:         } elsif ($space eq 'name') {
1.218     albertel 10772:             return $uname;
1.48      www      10773: # ---------------------------------------------------- Any other user namespace
1.29      www      10774:         } else {
1.359     albertel 10775: 	    my %reply;
                   10776: 	    if (!$publicuser) {
                   10777: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10778: 	    }
                   10779: 	    return $reply{$qualifierrest};
1.48      www      10780:         }
1.236     www      10781:     } elsif ($realm eq 'query') {
                   10782: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10783:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10784: 						[$spacequalifierrest]);
1.620     albertel 10785: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10786:    } elsif ($realm eq 'request') {
1.48      www      10787: # ------------------------------------------------------------- request.browser
                   10788:         if ($space eq 'browser') {
1.1145    bisitz   10789:             return $env{'browser.'.$qualifier};
1.57      www      10790: # ------------------------------------------------------------ request.filename
                   10791:         } else {
1.620     albertel 10792:             return $env{'request.'.$spacequalifierrest};
1.29      www      10793:         }
1.28      www      10794:     } elsif ($realm eq 'course') {
1.48      www      10795: # ---------------------------------------------------------- course.description
1.620     albertel 10796:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10797:     } elsif ($realm eq 'resource') {
1.165     www      10798: 
1.620     albertel 10799: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10800: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10801: 	}
1.693     albertel 10802: 
1.1172.2.30  raeburn  10803:         if ($qualifier eq '') {
                   10804: 	    if ($space eq 'title') {
                   10805: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10806: 	        return &gettitle($symbparm);
                   10807: 	    }
1.693     albertel 10808: 	
1.1172.2.30  raeburn  10809: 	    if ($space eq 'map') {
                   10810: 	        my ($map) = &decode_symb($symbparm);
                   10811: 	        return &symbread($map);
                   10812: 	    }
                   10813:             if ($space eq 'maptitle') {
                   10814:                 my ($map) = &decode_symb($symbparm);
                   10815:                 return &gettitle($map);
                   10816:             }
                   10817: 	    if ($space eq 'filename') {
                   10818: 	        if ($symbparm) {
                   10819: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10820: 	        }
                   10821: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10822: 	    }
1.1172.2.30  raeburn  10823: 
                   10824:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10825:                 if ($space eq 'visibleparts') {
                   10826:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10827:                     my $item;
                   10828:                     if (ref($navmap)) {
                   10829:                         my $res = $navmap->getBySymb($symbparm);
                   10830:                         my $parts = $res->parts();
                   10831:                         if (ref($parts) eq 'ARRAY') {
                   10832:                             $item = join(',',@{$parts});
                   10833:                         }
                   10834:                         undef($navmap);
                   10835:                     }
                   10836:                     return $item;
                   10837:                 }
                   10838:             }
                   10839:         }
1.693     albertel 10840: 
                   10841: 	my ($section, $group, @groups);
1.593     albertel 10842: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10843:         if (($courseid eq '') && ($cid)) {
                   10844:             $courseid = $cid;
                   10845:         }
                   10846: 	if (($symbparm && $courseid) && 
                   10847: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10848: 
1.218     albertel 10849: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10850: 
1.60      www      10851: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10852: 	    my $symbp=$symbparm;
1.735     albertel 10853: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10854: 
                   10855: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10856: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10857: 
1.620     albertel 10858: 	    if (($env{'user.name'} eq $uname) &&
                   10859: 		($env{'user.domain'} eq $udom)) {
                   10860: 		$section=$env{'request.course.sec'};
1.733     raeburn  10861:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10862:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10863: 	    } else {
1.539     albertel 10864: 		if (! defined($usection)) {
1.551     albertel 10865: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10866: 		} else {
                   10867: 		    $section = $usection;
                   10868: 		}
1.733     raeburn  10869:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10870: 	    }
                   10871: 
                   10872: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10873: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10874: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10875: 
1.593     albertel 10876: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10877: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10878: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10879: 
1.60      www      10880: # ----------------------------------------------------------- first, check user
1.624     albertel 10881: 
                   10882: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10883: 				       ([$courselevelr,'resource'],
                   10884: 					[$courselevelm,'map'     ],
                   10885: 					[$courselevel, 'course'  ]));
1.931     albertel 10886: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10887: 
1.594     albertel 10888: # ------------------------------------------------ second, check some of course
1.684     raeburn  10889:             my $coursereply;
1.691     raeburn  10890:             if (@groups > 0) {
                   10891:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10892:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10893:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10894:             }
1.96      www      10895: 
1.684     raeburn  10896: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10897: 				  $env{'course.'.$courseid.'.domain'},
                   10898: 				  'course',
                   10899: 				  ([$seclevelr,   'resource'],
                   10900: 				   [$seclevelm,   'map'     ],
                   10901: 				   [$seclevel,    'course'  ],
                   10902: 				   [$courselevelr,'resource']));
                   10903: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10904: 
1.60      www      10905: # ------------------------------------------------------ third, check map parms
1.218     albertel 10906: 	    my %parmhash=();
                   10907: 	    my $thisparm='';
                   10908: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10909: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10910: 		    &GDBM_READER(),0640)) {
1.218     albertel 10911: 		$thisparm=$parmhash{$symbparm};
                   10912: 		untie(%parmhash);
                   10913: 	    }
1.927     albertel 10914: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10915: 	}
1.594     albertel 10916: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10917: 
1.218     albertel 10918: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10919: 	my $filename;
                   10920: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10921: 	if ($symbparm) {
1.409     www      10922: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10923: 	} else {
1.620     albertel 10924: 	    $filename=$env{'request.filename'};
1.282     albertel 10925: 	}
                   10926: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10927: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10928: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10929: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10930: 
1.927     albertel 10931: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10932: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10933: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10934: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10935: 				     $env{'course.'.$courseid.'.domain'},
                   10936: 				     'course',
1.927     albertel 10937: 				     ([$courselevelm,'map'   ],
                   10938: 				      [$courselevel, 'course']));
                   10939: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10940: 	}
1.145     www      10941: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10942: 	unless ($space eq '0') {
1.336     albertel 10943: 	    my @parts=split(/_/,$space);
                   10944: 	    my $id=pop(@parts);
                   10945: 	    my $part=join('_',@parts);
                   10946: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10947: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10948: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10949: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10950: 	}
1.395     albertel 10951: 	if ($recurse) { return undef; }
                   10952: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10953: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10954: # ---------------------------------------------------- Any other user namespace
                   10955:     } elsif ($realm eq 'environment') {
                   10956: # ----------------------------------------------------------------- environment
1.620     albertel 10957: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10958: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10959: 	} else {
1.770     albertel 10960: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10961: 		return '';
                   10962: 	    }
1.219     albertel 10963: 	    my %returnhash=&userenvironment($udom,$uname,
                   10964: 					    $spacequalifierrest);
                   10965: 	    return $returnhash{$spacequalifierrest};
                   10966: 	}
1.28      www      10967:     } elsif ($realm eq 'system') {
1.48      www      10968: # ----------------------------------------------------------------- system.time
                   10969: 	if ($space eq 'time') {
                   10970: 	    return time;
                   10971:         }
1.696     albertel 10972:     } elsif ($realm eq 'server') {
                   10973: # ----------------------------------------------------------------- system.time
                   10974: 	if ($space eq 'name') {
                   10975: 	    return $ENV{'SERVER_NAME'};
                   10976:         }
1.28      www      10977:     }
1.48      www      10978:     return '';
1.61      www      10979: }
                   10980: 
1.927     albertel 10981: sub get_reply {
                   10982:     my ($reply_value) = @_;
1.940     raeburn  10983:     if (ref($reply_value) eq 'ARRAY') {
                   10984:         if (wantarray) {
                   10985: 	    return @$reply_value;
                   10986:         }
                   10987:         return $reply_value->[0];
                   10988:     } else {
                   10989:         return $reply_value;
1.927     albertel 10990:     }
                   10991: }
                   10992: 
1.691     raeburn  10993: sub check_group_parms {
                   10994:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10995:     my @groupitems = ();
                   10996:     my $resultitem;
1.927     albertel 10997:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10998:     foreach my $group (@{$groups}) {
                   10999:         foreach my $level (@levels) {
1.927     albertel 11000:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11001:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11002:         }
                   11003:     }
                   11004:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11005:                             $env{'course.'.$courseid.'.domain'},
                   11006:                                      'course',@groupitems);
                   11007:     return $coursereply;
                   11008: }
                   11009: 
                   11010: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11011:     my ($courseid,@groups) = @_;
                   11012:     @groups = sort(@groups);
1.691     raeburn  11013:     return @groups;
                   11014: }
                   11015: 
1.395     albertel 11016: sub packages_tab_default {
                   11017:     my ($uri,$varname)=@_;
                   11018:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11019: 
                   11020:     my (@extension,@specifics,$do_default);
                   11021:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11022: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11023: 	if ($pack_type eq 'default') {
                   11024: 	    $do_default=1;
                   11025: 	} elsif ($pack_type eq 'extension') {
                   11026: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11027: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11028: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11029: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11030: 	}
                   11031:     }
                   11032:     # first look for a package that matches the requested part id
                   11033:     foreach my $package (@specifics) {
                   11034: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11035: 	next if ($pack_part ne $part);
                   11036: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11037: 	    return $packagetab{"$pack_type&$name&default"};
                   11038: 	}
                   11039:     }
                   11040:     # look for any possible matching non extension_ package
                   11041:     foreach my $package (@specifics) {
                   11042: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11043: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11044: 	    return $packagetab{"$pack_type&$name&default"};
                   11045: 	}
1.585     albertel 11046: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11047: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11048: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11049: 	}
                   11050:     }
1.738     albertel 11051:     # look for any posible extension_ match
                   11052:     foreach my $package (@extension) {
                   11053: 	my ($package,$pack_type)=@{$package};
                   11054: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11055: 	    return $packagetab{"$pack_type&$name&default"};
                   11056: 	}
                   11057: 	if (defined($packagetab{$package."&$name&default"})) {
                   11058: 	    return $packagetab{$package."&$name&default"};
                   11059: 	}
                   11060:     }
                   11061:     # look for a global default setting
                   11062:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11063: 	return $packagetab{"default&$name&default"};
                   11064:     }
1.395     albertel 11065:     return undef;
                   11066: }
                   11067: 
1.334     albertel 11068: sub add_prefix_and_part {
                   11069:     my ($prefix,$part)=@_;
                   11070:     my $keyroot;
                   11071:     if (defined($prefix) && $prefix !~ /^__/) {
                   11072: 	# prefix that has a part already
                   11073: 	$keyroot=$prefix;
                   11074:     } elsif (defined($prefix)) {
                   11075: 	# prefix that is missing a part
                   11076: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11077:     } else {
                   11078: 	# no prefix at all
                   11079: 	if (defined($part)) { $keyroot='_'.$part; }
                   11080:     }
                   11081:     return $keyroot;
                   11082: }
                   11083: 
1.71      www      11084: # ---------------------------------------------------------------- Get metadata
                   11085: 
1.599     albertel 11086: my %metaentry;
1.1070    www      11087: my %importedpartids;
1.1172.2.99  raeburn  11088: my %importedrespids;
1.71      www      11089: sub metadata {
1.176     www      11090:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11091:     $uri=&declutter($uri);
1.288     albertel 11092:     # if it is a non metadata possible uri return quickly
1.529     albertel 11093:     if (($uri eq '') || 
                   11094: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11095: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11096:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11097: 	return undef;
                   11098:     }
1.1172.2.49  raeburn  11099:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11100: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11101: 	return undef;
1.288     albertel 11102:     }
1.73      www      11103:     my $filename=$uri;
                   11104:     $uri=~s/\.meta$//;
1.172     www      11105: #
                   11106: # Is the metadata already cached?
1.177     www      11107: # Look at timestamp of caching
1.172     www      11108: # Everything is cached by the main uri, libraries are never directly cached
                   11109: #
1.428     albertel 11110:     if (!defined($liburi)) {
1.599     albertel 11111: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11112: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11113:     }
                   11114:     {
1.1069    www      11115: # Imported parts would go here
1.1172.2.99  raeburn  11116:         my @origfiletagids=();
1.1069    www      11117:         my $importedparts=0;
1.1172.2.99  raeburn  11118: 
                   11119: # Imported responseids would go here
                   11120:         my $importedresponses=0;
1.172     www      11121: #
                   11122: # Is this a recursive call for a library?
                   11123: #
1.599     albertel 11124: #	if (! exists($metacache{$uri})) {
                   11125: #	    $metacache{$uri}={};
                   11126: #	}
1.924     albertel 11127: 	my $cachetime = 60*60;
1.171     www      11128:         if ($liburi) {
                   11129: 	    $liburi=&declutter($liburi);
                   11130:             $filename=$liburi;
1.401     bowersj2 11131:         } else {
1.599     albertel 11132: 	    &devalidate_cache_new('meta',$uri);
                   11133: 	    undef(%metaentry);
1.401     bowersj2 11134: 	}
1.140     www      11135:         my %metathesekeys=();
1.73      www      11136:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11137: 	my $metastring;
1.1140    www      11138: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11139: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11140: 	    $metastring = 
1.929     albertel 11141: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11142: 					  ('grade_target' => 'meta'));
                   11143: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11144: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11145:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11146: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11147: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11148: 	    $metastring=&getfile($file);
1.489     albertel 11149: 	}
1.208     albertel 11150:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11151:         my $token;
1.140     www      11152:         undef %metathesekeys;
1.71      www      11153:         while ($token=$parser->get_token) {
1.339     albertel 11154: 	    if ($token->[0] eq 'S') {
                   11155: 		if (defined($token->[2]->{'package'})) {
1.172     www      11156: #
                   11157: # This is a package - get package info
                   11158: #
1.339     albertel 11159: 		    my $package=$token->[2]->{'package'};
                   11160: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11161: 		    if (defined($token->[2]->{'id'})) { 
                   11162: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11163: 		    }
1.599     albertel 11164: 		    if ($metaentry{':packages'}) {
                   11165: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11166: 		    } else {
1.599     albertel 11167: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11168: 		    }
1.736     albertel 11169: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11170: 			my $part=$keyroot;
                   11171: 			$part=~s/^\_//;
1.736     albertel 11172: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11173: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11174: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11175: 			    # ignore package.tab specified default values
                   11176:                             # here &package_tab_default() will fetch those
                   11177: 			    if ($subp eq 'default') { next; }
1.736     albertel 11178: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11179: 			    my $unikey;
                   11180: 			    if ($pack =~ /_0$/) {
                   11181: 				$unikey='parameter_0_'.$name;
                   11182: 				$part=0;
                   11183: 			    } else {
                   11184: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11185: 			    }
1.339     albertel 11186: 			    if ($subp eq 'display') {
                   11187: 				$value.=' [Part: '.$part.']';
                   11188: 			    }
1.599     albertel 11189: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11190: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11191: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11192: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11193: 			    }
1.599     albertel 11194: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11195: 				$metaentry{':'.$unikey}=
                   11196: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11197: 			    }
1.339     albertel 11198: 			}
                   11199: 		    }
                   11200: 		} else {
1.172     www      11201: #
                   11202: # This is not a package - some other kind of start tag
1.339     albertel 11203: #
                   11204: 		    my $entry=$token->[1];
1.1068    www      11205: 		    my $unikey='';
1.175     www      11206: 
1.339     albertel 11207: 		    if ($entry eq 'import') {
1.175     www      11208: #
                   11209: # Importing a library here
1.339     albertel 11210: #
1.1067    www      11211:                         my $location=$parser->get_text('/import');
                   11212:                         my $dir=$filename;
                   11213:                         $dir=~s|[^/]*$||;
                   11214:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11215: 
                   11216:                         my $importid=$token->[2]->{'id'};
1.1068    www      11217:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11218: #
                   11219: # Check metadata for imported file to
                   11220: # see if it contained response items
                   11221: #
                   11222:                         my %currmetaentry = %metaentry;
                   11223:                         my $libresponseorder = &metadata($location,'responseorder');
                   11224:                         my $origfile;
                   11225:                         if ($libresponseorder ne '') {
                   11226:                             if ($#origfiletagids<0) {
                   11227:                                 undef(%importedrespids);
                   11228:                                 undef(%importedpartids);
                   11229:                             }
                   11230:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11231:                             if (@{$importedrespids{$importid}} > 0) {
                   11232:                                 $importedresponses = 1;
                   11233: # We need to get the original file and the imported file to get the response order correct
                   11234: # Load and inspect original file
                   11235:                                 if ($#origfiletagids<0) {
                   11236:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11237:                                     $origfile=&getfile($origfilelocation);
                   11238:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11239:                                 }
                   11240:                             }
                   11241:                         }
                   11242: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11243: # hash populated for imported library file
                   11244:                         %metaentry = %currmetaentry;
                   11245:                         undef(%currmetaentry);
1.1068    www      11246:                         if ($importmode eq 'problem') {
1.1069    www      11247: # Import as problem/response
1.1068    www      11248:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11249:                         } elsif ($importmode eq 'part') {
                   11250: # Import as part(s)
1.1069    www      11251:                            $importedparts=1;
                   11252: # We need to get the original file and the imported file to get the part order correct
                   11253: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11254: # Load and inspect original file if we didn't do that already
                   11255:                            if ($#origfiletagids<0) {
                   11256:                                undef(%importedrespids);
                   11257:                                undef(%importedpartids);
                   11258:                                if ($origfile eq '') {
                   11259:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11260:                                    $origfile=&getfile($origfilelocation);
                   11261:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11262:                                }
1.1070    www      11263:                            }
                   11264: 
1.1069    www      11265: # Load and inspect imported file
                   11266:                            my $impfile=&getfile($location);
                   11267:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11268:                            if ($#impfilepartids>=0) {
                   11269: # This problem had parts
1.1070    www      11270:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11271:                            } else {
                   11272: # Importing by turning a single problem into a problem part
                   11273: # It gets the import-tags ID as part-ID
                   11274:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11275:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11276:                            }
1.1068    www      11277:                         } else {
                   11278: # Normal import
                   11279:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11280:                            if (defined($token->[2]->{'id'})) {
                   11281:                               $unikey.='_'.$token->[2]->{'id'};
                   11282:                            }
1.1067    www      11283:                         }
                   11284: 
1.339     albertel 11285: 			if ($depthcount<20) {
1.736     albertel 11286: 			    my $metadata = 
                   11287: 				&metadata($uri,'keys', $location,$unikey,
                   11288: 					  $depthcount+1);
                   11289: 			    foreach my $meta (split(',',$metadata)) {
                   11290: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11291: 				$metathesekeys{$meta}=1;
1.339     albertel 11292: 			    }
1.1068    www      11293: 			
                   11294:                         }
1.1067    www      11295: 		    } else {
                   11296: #
                   11297: # Not importing, some other kind of non-package, non-library start tag
                   11298: # 
                   11299:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11300:                         if (defined($token->[2]->{'id'})) {
                   11301:                             $unikey.='_'.$token->[2]->{'id'};
                   11302:                         }
1.339     albertel 11303: 			if (defined($token->[2]->{'name'})) { 
                   11304: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11305: 			}
                   11306: 			$metathesekeys{$unikey}=1;
1.736     albertel 11307: 			foreach my $param (@{$token->[3]}) {
                   11308: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11309: 				$token->[2]->{$param};
1.339     albertel 11310: 			}
                   11311: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11312: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11313: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11314: 		 # only ws inside the tag, and not in default, so use default
                   11315: 		 # as value
1.599     albertel 11316: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11317: 			} elsif ( $internaltext =~ /\S/ ) {
                   11318: 		  # something interesting inside the tag
                   11319: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11320: 			} else {
1.908     albertel 11321: 		  # no interesting values, don't set a default
1.339     albertel 11322: 			}
1.172     www      11323: # end of not-a-package not-a-library import
1.339     albertel 11324: 		    }
1.172     www      11325: # end of not-a-package start tag
1.339     albertel 11326: 		}
1.172     www      11327: # the next is the end of "start tag"
1.339     albertel 11328: 	    }
                   11329: 	}
1.483     albertel 11330: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11331: 	$extension = lc($extension);
                   11332: 	if ($extension eq 'htm') { $extension='html'; }
                   11333: 
1.737     albertel 11334: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11335: 	    #no specific packages #how's our extension
                   11336: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11337: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11338: 					 \%metathesekeys);
                   11339: 	}
1.883     albertel 11340: 
                   11341: 	if (!exists($metaentry{':packages'})
                   11342: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11343: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11344: 		#no specific packages well let's get default then
                   11345: 		if ($key!~/^default&/) { next; }
1.488     albertel 11346: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11347: 					     \%metathesekeys);
                   11348: 	    }
                   11349: 	}
1.338     www      11350: # are there custom rights to evaluate
1.599     albertel 11351: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11352: 
1.338     www      11353:     #
                   11354:     # Importing a rights file here
1.339     albertel 11355:     #
                   11356: 	    unless ($depthcount) {
1.599     albertel 11357: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11358: 		my $dir=$filename;
                   11359: 		$dir=~s|[^/]*$||;
                   11360: 		$location=&filelocation($dir,$location);
1.736     albertel 11361: 		my $rights_metadata =
                   11362: 		    &metadata($uri,'keys',$location,'_rights',
                   11363: 			      $depthcount+1);
                   11364: 		foreach my $rights (split(',',$rights_metadata)) {
                   11365: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11366: 		    $metathesekeys{$rights}=1;
1.339     albertel 11367: 		}
                   11368: 	    }
                   11369: 	}
1.737     albertel 11370: 	# uniqifiy package listing
                   11371: 	my %seen;
                   11372: 	my @uniq_packages =
                   11373: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11374: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11375: 
1.1172.2.99  raeburn  11376:         if (($importedresponses) || ($importedparts)) {
                   11377:             if ($importedparts) {
1.1070    www      11378: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11379:                 $metaentry{':partorder'}='';
                   11380:                 $metathesekeys{'partorder'}=1;
                   11381:             }
                   11382:             if ($importedresponses) {
                   11383: # We had imported responses and need to rebuild responseorder
                   11384:                 $metaentry{':responseorder'}='';
                   11385:                 $metathesekeys{'responseorder'}=1;
                   11386:             }
                   11387:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11388:                 my $origid = $origfiletagids[$index+1];
                   11389:                 if ($origfiletagids[$index] eq 'part') {
                   11390: # Original part, part of the problem
                   11391:                     if ($importedparts) {
                   11392:                         $metaentry{':partorder'}.=','.$origid;
                   11393:                     }
                   11394:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11395:                     if ($importedparts) {
                   11396: # We have imported parts at this position
                   11397:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11398:                     }
                   11399:                     if ($importedresponses) {
                   11400: # We have imported responses at this position
                   11401:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11402:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11403:                         }
                   11404:                     }
                   11405:                 } else {
                   11406: # Original response item, part of the problem
                   11407:                     if ($importedresponses) {
                   11408:                         $metaentry{':responseorder'}.=','.$origid;
                   11409:                     }
                   11410:                 }
                   11411:             }
                   11412:             if ($importedparts) {
                   11413:                 $metaentry{':partorder'}=~s/^\,//;
                   11414:             }
                   11415:             if ($importedresponses) {
                   11416:                 $metaentry{':responseorder'}=~s/^\,//;
                   11417:             }
1.1070    www      11418:         }
                   11419: 
1.737     albertel 11420: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11421: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11422: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11423: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11424: # this is the end of "was not already recently cached
1.71      www      11425:     }
1.599     albertel 11426:     return $metaentry{':'.$what};
1.261     albertel 11427: }
                   11428: 
1.488     albertel 11429: sub metadata_create_package_def {
1.483     albertel 11430:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11431:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11432:     if ($subp eq 'default') { next; }
                   11433:     
1.599     albertel 11434:     if (defined($metaentry{':packages'})) {
                   11435: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11436:     } else {
1.599     albertel 11437: 	$metaentry{':packages'}=$package;
1.483     albertel 11438:     }
                   11439:     my $value=$packagetab{$key};
                   11440:     my $unikey;
                   11441:     $unikey='parameter_0_'.$name;
1.599     albertel 11442:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11443:     $$metathesekeys{$unikey}=1;
1.599     albertel 11444:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11445: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11446:     }
1.599     albertel 11447:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11448: 	$metaentry{':'.$unikey}=
                   11449: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11450:     }
                   11451: }
                   11452: 
1.261     albertel 11453: sub metadata_generate_part0 {
                   11454:     my ($metadata,$metacache,$uri) = @_;
                   11455:     my %allnames;
1.737     albertel 11456:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11457: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11458: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11459: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11460: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11461: 	    $allnames{$name}=$part;
                   11462: 	  }
                   11463: 	}
                   11464:     }
                   11465:     foreach my $name (keys(%allnames)) {
                   11466:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11467:       my $key=":parameter_0_$name";
1.261     albertel 11468:       $$metacache{"$key.part"}='0';
                   11469:       $$metacache{"$key.name"}=$name;
1.428     albertel 11470:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11471: 					   $allnames{$name}.'_'.$name.
                   11472: 					   '.type'};
1.428     albertel 11473:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11474: 			     '.display'};
1.644     www      11475:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11476:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11477:       $$metacache{"$key.display"}=$olddis;
                   11478:     }
1.71      www      11479: }
                   11480: 
1.764     albertel 11481: # ------------------------------------------------------ Devalidate title cache
                   11482: 
                   11483: sub devalidate_title_cache {
                   11484:     my ($url)=@_;
                   11485:     if (!$env{'request.course.id'}) { return; }
                   11486:     my $symb=&symbread($url);
                   11487:     if (!$symb) { return; }
                   11488:     my $key=$env{'request.course.id'}."\0".$symb;
                   11489:     &devalidate_cache_new('title',$key);
                   11490: }
                   11491: 
1.1014    droeschl 11492: # ------------------------------------------------- Get the title of a course
                   11493: 
                   11494: sub current_course_title {
                   11495:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11496: }
1.301     www      11497: # ------------------------------------------------- Get the title of a resource
                   11498: 
                   11499: sub gettitle {
                   11500:     my $urlsymb=shift;
                   11501:     my $symb=&symbread($urlsymb);
1.534     albertel 11502:     if ($symb) {
1.620     albertel 11503: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11504: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11505: 	if (defined($cached)) { 
                   11506: 	    return $result;
                   11507: 	}
1.534     albertel 11508: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11509: 	my $title='';
1.907     albertel 11510: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11511: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11512: 	} else {
                   11513: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11514: 		    &GDBM_READER(),0640)) {
                   11515: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11516: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11517: 		untie(%bighash);
                   11518: 	    }
1.534     albertel 11519: 	}
                   11520: 	$title=~s/\&colon\;/\:/gs;
                   11521: 	if ($title) {
1.1159    www      11522: # Remember both $symb and $title for dynamic metadata
                   11523:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11524:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11525: # Cache this title and then return it
1.599     albertel 11526: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11527: 	}
                   11528: 	$urlsymb=$url;
                   11529:     }
                   11530:     my $title=&metadata($urlsymb,'title');
                   11531:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11532:     return $title;
1.301     www      11533: }
1.613     albertel 11534: 
1.614     albertel 11535: sub get_slot {
                   11536:     my ($which,$cnum,$cdom)=@_;
                   11537:     if (!$cnum || !$cdom) {
1.790     albertel 11538: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11539: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11540: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11541:     }
1.703     albertel 11542:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11543:     my %slotinfo;
                   11544:     if (exists($remembered{$key})) {
                   11545: 	$slotinfo{$which} = $remembered{$key};
                   11546:     } else {
                   11547: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11548: 	&Apache::lonhomework::showhash(%slotinfo);
                   11549: 	my ($tmp)=keys(%slotinfo);
                   11550: 	if ($tmp=~/^error:/) { return (); }
                   11551: 	$remembered{$key} = $slotinfo{$which};
                   11552:     }
1.616     albertel 11553:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11554: 	return %{$slotinfo{$which}};
                   11555:     }
                   11556:     return $slotinfo{$which};
1.614     albertel 11557: }
1.1150    raeburn  11558: 
                   11559: sub get_reservable_slots {
                   11560:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11561:     my $now = time;
                   11562:     my $reservable_info;
                   11563:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11564:     if (exists($remembered{$key})) {
                   11565:         $reservable_info = $remembered{$key};
                   11566:     } else {
                   11567:         my %resv;
                   11568:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11569:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11570:         $reservable_info = \%resv;
                   11571:         $remembered{$key} = $reservable_info;
                   11572:     }
                   11573:     return $reservable_info;
                   11574: }
                   11575: 
                   11576: sub get_course_slots {
                   11577:     my ($cnum,$cdom) = @_;
                   11578:     my $hashid=$cnum.':'.$cdom;
                   11579:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11580:     if (defined($cached)) {
                   11581:         if (ref($result) eq 'HASH') {
                   11582:             return %{$result};
                   11583:         }
                   11584:     } else {
                   11585:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11586:         my ($tmp) = keys(%slots);
                   11587:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11588:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11589:             return %slots;
                   11590:         }
                   11591:     }
                   11592:     return;
                   11593: }
                   11594: 
                   11595: sub devalidate_slots_cache {
                   11596:     my ($cnum,$cdom)=@_;
                   11597:     my $hashid=$cnum.':'.$cdom;
                   11598:     &devalidate_cache_new('allslots',$hashid);
                   11599: }
                   11600: 
1.1172.2.8  raeburn  11601: sub get_coursechange {
                   11602:     my ($cdom,$cnum) = @_;
                   11603:     if ($cdom eq '' || $cnum eq '') {
                   11604:         return unless ($env{'request.course.id'});
                   11605:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11606:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11607:     }
                   11608:     my $hashid=$cdom.'_'.$cnum;
                   11609:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11610:     if ((defined($cached)) && ($change ne '')) {
                   11611:         return $change;
                   11612:     } else {
                   11613:         my %crshash;
                   11614:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11615:         if ($crshash{'internal.contentchange'} eq '') {
                   11616:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11617:             if ($change eq '') {
                   11618:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11619:                 $change = $crshash{'internal.created'};
                   11620:             }
                   11621:         } else {
                   11622:             $change = $crshash{'internal.contentchange'};
                   11623:         }
                   11624:         my $cachetime = 600;
                   11625:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11626:     }
                   11627:     return $change;
                   11628: }
                   11629: 
                   11630: sub devalidate_coursechange_cache {
                   11631:     my ($cnum,$cdom)=@_;
                   11632:     my $hashid=$cnum.':'.$cdom;
                   11633:     &devalidate_cache_new('crschange',$hashid);
                   11634: }
                   11635: 
1.31      www      11636: # ------------------------------------------------- Update symbolic store links
                   11637: 
                   11638: sub symblist {
                   11639:     my ($mapname,%newhash)=@_;
1.438     www      11640:     $mapname=&deversion(&declutter($mapname));
1.31      www      11641:     my %hash;
1.620     albertel 11642:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11643:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11644:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11645: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11646: 		next if ($url eq 'last_known'
                   11647: 			 && $env{'form.no_update_last_known'});
                   11648: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11649: 						    $newhash{$url}->[1],
                   11650: 						    $newhash{$url}->[0]);
1.191     harris41 11651:             }
1.31      www      11652:             if (untie(%hash)) {
                   11653: 		return 'ok';
                   11654:             }
                   11655:         }
                   11656:     }
                   11657:     return 'error';
1.212     www      11658: }
                   11659: 
                   11660: # --------------------------------------------------------------- Verify a symb
                   11661: 
                   11662: sub symbverify {
1.1172.2.11  raeburn  11663:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11664:     my $thisfn=$thisurl;
1.439     www      11665:     $thisfn=&declutter($thisfn);
1.215     www      11666: # direct jump to resource in page or to a sequence - will construct own symbs
                   11667:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11668: # check URL part
1.409     www      11669:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11670: 
1.431     www      11671:     unless ($url eq $thisfn) { return 0; }
1.213     www      11672: 
1.216     www      11673:     $symb=&symbclean($symb);
1.510     www      11674:     $thisurl=&deversion($thisurl);
1.439     www      11675:     $thisfn=&deversion($thisfn);
1.213     www      11676: 
                   11677:     my %bighash;
                   11678:     my $okay=0;
1.431     www      11679: 
1.620     albertel 11680:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11681:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11682:         my $noclutter;
1.1032    raeburn  11683:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11684:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11685:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11686:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11687:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11688:                 $noclutter = 1;
                   11689:             }
                   11690:         }
                   11691:         my $ids;
                   11692:         if ($noclutter) {
                   11693:             $ids=$bighash{'ids_'.$thisurl};
                   11694:         } else {
                   11695:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11696:         }
1.1102    raeburn  11697:         unless ($ids) {
1.1172.2.13  raeburn  11698:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11699:             $ids=$bighash{$idkey};
1.216     www      11700:         }
                   11701:         if ($ids) {
                   11702: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11703:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11704:                 $symb =~ s/\?.+$//;
                   11705:             }
1.800     albertel 11706: 	    foreach my $id (split(/\,/,$ids)) {
                   11707: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11708:                if (
                   11709:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11710:    eq $symb) {
1.1172.2.11  raeburn  11711:                    if (ref($encstate)) {
                   11712:                        $$encstate = $bighash{'encrypted_'.$id};
                   11713:                    }
1.1172.2.13  raeburn  11714:                    if (($env{'request.role.adv'}) ||
                   11715:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11716:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11717:                        $okay=1;
                   11718:                        last;
                   11719:                    }
                   11720:                }
                   11721:            }
1.216     www      11722:         }
1.213     www      11723: 	untie(%bighash);
                   11724:     }
                   11725:     return $okay;
1.31      www      11726: }
                   11727: 
1.210     www      11728: # --------------------------------------------------------------- Clean-up symb
                   11729: 
                   11730: sub symbclean {
                   11731:     my $symb=shift;
1.568     albertel 11732:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11733: # remove version from map
                   11734:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11735: 
1.210     www      11736: # remove version from URL
                   11737:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11738: 
1.507     www      11739: # remove wrapper
                   11740: 
1.510     www      11741:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11742:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11743:     return $symb;
1.409     www      11744: }
                   11745: 
                   11746: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11747: 
                   11748: sub encode_symb {
                   11749:     my ($map,$resid,$url)=@_;
                   11750:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11751: }
1.409     www      11752: 
                   11753: sub decode_symb {
1.568     albertel 11754:     my $symb=shift;
                   11755:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11756:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11757:     return (&fixversion($map),$resid,&fixversion($url));
                   11758: }
                   11759: 
                   11760: sub fixversion {
                   11761:     my $fn=shift;
1.609     banghart 11762:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11763:     my %bighash;
                   11764:     my $uri=&clutter($fn);
1.620     albertel 11765:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11766: # is this cached?
1.599     albertel 11767:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11768:     if (defined($cached)) { return $result; }
                   11769: # unfortunately not cached, or expired
1.620     albertel 11770:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11771: 	    &GDBM_READER(),0640)) {
                   11772:  	if ($bighash{'version_'.$uri}) {
                   11773:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11774:  	    unless (($version eq 'mostrecent') || 
                   11775: 		    ($version==&getversion($uri))) {
1.440     www      11776:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11777:  	    }
                   11778:  	}
                   11779:  	untie %bighash;
1.413     www      11780:     }
1.599     albertel 11781:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11782: }
                   11783: 
                   11784: sub deversion {
                   11785:     my $url=shift;
                   11786:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11787:     return $url;
1.210     www      11788: }
                   11789: 
1.31      www      11790: # ------------------------------------------------------ Return symb list entry
                   11791: 
                   11792: sub symbread {
1.1172.2.66  raeburn  11793:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11794:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11795:     if (defined($env{$cache_str})) {
                   11796:         if ($ignorecachednull) {
                   11797:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11798:         } else {
                   11799:             return $env{$cache_str};
                   11800:         }
                   11801:     }
1.242     www      11802: # no filename provided? try from environment
1.1172.2.54  raeburn  11803:     unless ($thisfn) {
1.620     albertel 11804:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11805:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11806:         }
                   11807:         $thisfn=$env{'request.filename'};
1.44      www      11808:     }
1.569     albertel 11809:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11810: # is that filename actually a symb? Verify, clean, and return
                   11811:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11812: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11813: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11814: 	}
1.242     www      11815:     }
1.44      www      11816:     $thisfn=declutter($thisfn);
1.31      www      11817:     my %hash;
1.37      www      11818:     my %bighash;
                   11819:     my $syval='';
1.620     albertel 11820:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11821:         my $targetfn = $thisfn;
1.609     banghart 11822:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11823:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11824:         }
1.687     albertel 11825: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11826: 	    $targetfn=$1;
                   11827: 	}
1.620     albertel 11828:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11829:                       &GDBM_READER(),0640)) {
1.481     raeburn  11830: 	    $syval=$hash{$targetfn};
1.37      www      11831:             untie(%hash);
                   11832:         }
                   11833: # ---------------------------------------------------------- There was an entry
                   11834:         if ($syval) {
1.601     albertel 11835: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11836: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11837: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11838: 		    #return $env{$cache_str}='';
1.601     albertel 11839: 		#}    
                   11840: 		#$syval.=$1;
                   11841: 	    #}
1.37      www      11842:         } else {
                   11843: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11844:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11845:                             &GDBM_READER(),0640)) {
1.37      www      11846: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11847:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11848:               unless ($ids) { 
                   11849:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11850:               }
                   11851:               unless ($ids) {
                   11852: # alias?
                   11853: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11854:               }
1.37      www      11855:               if ($ids) {
                   11856: # ------------------------------------------------------------------- Has ID(s)
                   11857:                  my @possibilities=split(/\,/,$ids);
1.39      www      11858:                  if ($#possibilities==0) {
                   11859: # ----------------------------------------------- There is only one possibility
1.37      www      11860: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11861: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11862: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11863:                      if (ref($possibles) eq 'HASH') {
                   11864:                          $possibles->{$syval} = 1;
                   11865:                      }
                   11866:                      if ($checkforblock) {
                   11867:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11868:                          if (@blockers) {
                   11869:                              $syval = '';
                   11870:                              return;
                   11871:                          }
                   11872:                      }
                   11873:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11874: # ------------------------------------------ There is more than one possibility
                   11875:                      my $realpossible=0;
1.800     albertel 11876:                      foreach my $id (@possibilities) {
                   11877: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11878:                          my $canaccess;
                   11879:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11880:                              $canaccess = 1;
                   11881:                          } else {
                   11882:                              $canaccess = &allowed('bre',$file);
                   11883:                          }
                   11884:                          if ($canaccess) {
                   11885:          		     my ($mapid,$resid)=split(/\./,$id);
                   11886:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11887:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11888:                                                              $resid,$thisfn);
                   11889:                                  if (ref($possibles) eq 'HASH') {
                   11890:                                      $possibles->{$syval} = 1;
                   11891:                                  }
                   11892:                                  if ($checkforblock) {
                   11893:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11894:                                      unless (@blockers > 0) {
                   11895:                                          $syval = $poss_syval;
                   11896:                                          $realpossible++;
                   11897:                                      }
                   11898:                                  } else {
                   11899:                                      $syval = $poss_syval;
                   11900:                                      $realpossible++;
                   11901:                                  }
                   11902:                              }
1.39      www      11903: 			 }
1.191     harris41 11904:                      }
1.39      www      11905: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11906:                  } else {
                   11907:                      $syval='';
1.37      www      11908:                  }
                   11909: 	      }
1.1172.2.66  raeburn  11910:               untie(%bighash);
1.481     raeburn  11911:            }
1.31      www      11912:         }
1.62      www      11913:         if ($syval) {
1.620     albertel 11914: 	    return $env{$cache_str}=$syval;
1.62      www      11915:         }
1.31      www      11916:     }
1.949     raeburn  11917:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11918:     return $env{$cache_str}='';
1.31      www      11919: }
                   11920: 
                   11921: # ---------------------------------------------------------- Return random seed
                   11922: 
1.32      www      11923: sub numval {
                   11924:     my $txt=shift;
                   11925:     $txt=~tr/A-J/0-9/;
                   11926:     $txt=~tr/a-j/0-9/;
                   11927:     $txt=~tr/K-T/0-9/;
                   11928:     $txt=~tr/k-t/0-9/;
                   11929:     $txt=~tr/U-Z/0-5/;
                   11930:     $txt=~tr/u-z/0-5/;
                   11931:     $txt=~s/\D//g;
1.564     albertel 11932:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11933:     return int($txt);
1.368     albertel 11934: }
                   11935: 
1.484     albertel 11936: sub numval2 {
                   11937:     my $txt=shift;
                   11938:     $txt=~tr/A-J/0-9/;
                   11939:     $txt=~tr/a-j/0-9/;
                   11940:     $txt=~tr/K-T/0-9/;
                   11941:     $txt=~tr/k-t/0-9/;
                   11942:     $txt=~tr/U-Z/0-5/;
                   11943:     $txt=~tr/u-z/0-5/;
                   11944:     $txt=~s/\D//g;
                   11945:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11946:     my $total;
                   11947:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11948:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11949:     return int($total);
                   11950: }
                   11951: 
1.575     albertel 11952: sub numval3 {
                   11953:     use integer;
                   11954:     my $txt=shift;
                   11955:     $txt=~tr/A-J/0-9/;
                   11956:     $txt=~tr/a-j/0-9/;
                   11957:     $txt=~tr/K-T/0-9/;
                   11958:     $txt=~tr/k-t/0-9/;
                   11959:     $txt=~tr/U-Z/0-5/;
                   11960:     $txt=~tr/u-z/0-5/;
                   11961:     $txt=~s/\D//g;
                   11962:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11963:     my $total;
                   11964:     foreach my $val (@txts) { $total+=$val; }
                   11965:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11966:     return $total;
                   11967: }
                   11968: 
1.675     albertel 11969: sub digest {
                   11970:     my ($data)=@_;
                   11971:     my $digest=&Digest::MD5::md5($data);
                   11972:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11973:     my ($e,$f);
                   11974:     {
                   11975:         use integer;
                   11976:         $e=($a+$b);
                   11977:         $f=($c+$d);
                   11978:         if ($_64bit) {
                   11979:             $e=(($e<<32)>>32);
                   11980:             $f=(($f<<32)>>32);
                   11981:         }
                   11982:     }
                   11983:     if (wantarray) {
                   11984: 	return ($e,$f);
                   11985:     } else {
                   11986: 	my $g;
                   11987: 	{
                   11988: 	    use integer;
                   11989: 	    $g=($e+$f);
                   11990: 	    if ($_64bit) {
                   11991: 		$g=(($g<<32)>>32);
                   11992: 	    }
                   11993: 	}
                   11994: 	return $g;
                   11995:     }
                   11996: }
                   11997: 
1.368     albertel 11998: sub latest_rnd_algorithm_id {
1.675     albertel 11999:     return '64bit5';
1.366     albertel 12000: }
1.32      www      12001: 
1.503     albertel 12002: sub get_rand_alg {
                   12003:     my ($courseid)=@_;
1.790     albertel 12004:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12005:     if ($courseid) {
1.620     albertel 12006: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12007:     }
                   12008:     return &latest_rnd_algorithm_id();
                   12009: }
                   12010: 
1.562     albertel 12011: sub validCODE {
                   12012:     my ($CODE)=@_;
                   12013:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12014:     return 0;
                   12015: }
                   12016: 
1.491     albertel 12017: sub getCODE {
1.620     albertel 12018:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12019:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12020: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12021: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12022: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12023:     }
                   12024:     return undef;
                   12025: }
1.1133    foxr     12026: #
                   12027: #  Determines the random seed for a specific context:
                   12028: #
                   12029: # parameters:
                   12030: #   symb      - in course context the symb for the seed.
                   12031: #   course_id - The course id of the form domain_coursenum.
                   12032: #   domain    - Domain for the user.
                   12033: #   course    - Course for the user.
                   12034: #   cenv      - environment of the course.
                   12035: #
                   12036: # NOTE:
                   12037: #   All parameters are picked out of the environment if missing
                   12038: #   or not defined.
                   12039: #   If a symb cannot be determined the current time is used instead.
                   12040: #
                   12041: #  For a given well defined symb, courside, domain, username,
                   12042: #  and course environment, the seed is reproducible.
                   12043: #
1.31      www      12044: sub rndseed {
1.1133    foxr     12045:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12046:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12047:     if (!defined($symb)) {
1.366     albertel 12048: 	unless ($symb=$wsymb) { return time; }
                   12049:     }
1.1146    foxr     12050:     if (!defined $courseid) { 
                   12051: 	$courseid=$wcourseid; 
                   12052:     }
                   12053:     if (!defined $domain) { $domain=$wdomain; }
                   12054:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12055: 
                   12056:     my $which;
                   12057:     if (defined($cenv->{'rndseed'})) {
                   12058: 	$which = $cenv->{'rndseed'};
                   12059:     } else {
                   12060: 	$which =&get_rand_alg($courseid);
                   12061:     }
1.491     albertel 12062:     if (defined(&getCODE())) {
1.675     albertel 12063: 	if ($which eq '64bit5') {
                   12064: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12065: 	} elsif ($which eq '64bit4') {
1.575     albertel 12066: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12067: 	} else {
                   12068: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12069: 	}
1.675     albertel 12070:     } elsif ($which eq '64bit5') {
                   12071: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12072:     } elsif ($which eq '64bit4') {
                   12073: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12074:     } elsif ($which eq '64bit3') {
                   12075: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12076:     } elsif ($which eq '64bit2') {
                   12077: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12078:     } elsif ($which eq '64bit') {
                   12079: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12080:     }
                   12081:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12082: }
                   12083: 
                   12084: sub rndseed_32bit {
                   12085:     my ($symb,$courseid,$domain,$username)=@_;
                   12086:     {
                   12087: 	use integer;
                   12088: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12089: 	my $symbseed=numval($symb) << 22;
                   12090: 	my $namechck=unpack("%32C*",$username) << 17;
                   12091: 	my $nameseed=numval($username) << 12;
                   12092: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12093: 	my $courseseed=unpack("%32C*",$courseid);
                   12094: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12095: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12096: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12097: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12098: 	return $num;
                   12099:     }
                   12100: }
                   12101: 
                   12102: sub rndseed_64bit {
                   12103:     my ($symb,$courseid,$domain,$username)=@_;
                   12104:     {
                   12105: 	use integer;
                   12106: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12107: 	my $symbseed=numval($symb) << 10;
                   12108: 	my $namechck=unpack("%32S*",$username);
                   12109: 	
                   12110: 	my $nameseed=numval($username) << 21;
                   12111: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12112: 	my $courseseed=unpack("%32S*",$courseid);
                   12113: 	
                   12114: 	my $num1=$symbchck+$symbseed+$namechck;
                   12115: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12116: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12117: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12118: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12119: 	return "$num1,$num2";
1.155     albertel 12120:     }
1.366     albertel 12121: }
                   12122: 
1.443     albertel 12123: sub rndseed_64bit2 {
                   12124:     my ($symb,$courseid,$domain,$username)=@_;
                   12125:     {
                   12126: 	use integer;
                   12127: 	# strings need to be an even # of cahracters long, it it is odd the
                   12128:         # last characters gets thrown away
                   12129: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12130: 	my $symbseed=numval($symb) << 10;
                   12131: 	my $namechck=unpack("%32S*",$username.' ');
                   12132: 	
                   12133: 	my $nameseed=numval($username) << 21;
1.501     albertel 12134: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12135: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12136: 	
                   12137: 	my $num1=$symbchck+$symbseed+$namechck;
                   12138: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12139: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12140: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12141: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12142: 	return "$num1,$num2";
                   12143:     }
                   12144: }
                   12145: 
                   12146: sub rndseed_64bit3 {
                   12147:     my ($symb,$courseid,$domain,$username)=@_;
                   12148:     {
                   12149: 	use integer;
                   12150: 	# strings need to be an even # of cahracters long, it it is odd the
                   12151:         # last characters gets thrown away
                   12152: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12153: 	my $symbseed=numval2($symb) << 10;
                   12154: 	my $namechck=unpack("%32S*",$username.' ');
                   12155: 	
                   12156: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12157: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12158: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12159: 	
                   12160: 	my $num1=$symbchck+$symbseed+$namechck;
                   12161: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12162: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12163: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12164: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12165: 	
1.503     albertel 12166: 	return "$num1:$num2";
1.443     albertel 12167:     }
                   12168: }
                   12169: 
1.575     albertel 12170: sub rndseed_64bit4 {
                   12171:     my ($symb,$courseid,$domain,$username)=@_;
                   12172:     {
                   12173: 	use integer;
                   12174: 	# strings need to be an even # of cahracters long, it it is odd the
                   12175:         # last characters gets thrown away
                   12176: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12177: 	my $symbseed=numval3($symb) << 10;
                   12178: 	my $namechck=unpack("%32S*",$username.' ');
                   12179: 	
                   12180: 	my $nameseed=numval3($username) << 21;
                   12181: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12182: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12183: 	
                   12184: 	my $num1=$symbchck+$symbseed+$namechck;
                   12185: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12186: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12187: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12188: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12189: 	
1.575     albertel 12190: 	return "$num1:$num2";
                   12191:     }
                   12192: }
                   12193: 
1.675     albertel 12194: sub rndseed_64bit5 {
                   12195:     my ($symb,$courseid,$domain,$username)=@_;
                   12196:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12197:     return "$num1:$num2";
                   12198: }
                   12199: 
1.366     albertel 12200: sub rndseed_CODE_64bit {
                   12201:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12202:     {
1.366     albertel 12203: 	use integer;
1.443     albertel 12204: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12205: 	my $symbseed=numval2($symb);
1.491     albertel 12206: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12207: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12208: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12209: 	my $num1=$symbseed+$CODEchck;
                   12210: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12211: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12212: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12213: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12214: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12215: 	return "$num1:$num2";
1.366     albertel 12216:     }
                   12217: }
                   12218: 
1.575     albertel 12219: sub rndseed_CODE_64bit4 {
                   12220:     my ($symb,$courseid,$domain,$username)=@_;
                   12221:     {
                   12222: 	use integer;
                   12223: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12224: 	my $symbseed=numval3($symb);
                   12225: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12226: 	my $CODEseed=numval3(&getCODE());
                   12227: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12228: 	my $num1=$symbseed+$CODEchck;
                   12229: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12230: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12231: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12232: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12233: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12234: 	return "$num1:$num2";
                   12235:     }
                   12236: }
                   12237: 
1.675     albertel 12238: sub rndseed_CODE_64bit5 {
                   12239:     my ($symb,$courseid,$domain,$username)=@_;
                   12240:     my $code = &getCODE();
                   12241:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12242:     return "$num1:$num2";
                   12243: }
                   12244: 
1.366     albertel 12245: sub setup_random_from_rndseed {
                   12246:     my ($rndseed)=@_;
1.503     albertel 12247:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12248: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12249:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12250:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12251:         } else {
                   12252:             &Math::Random::random_set_seed($num1,$num2);
                   12253:         }
1.366     albertel 12254:     } else {
                   12255: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12256:     }
1.36      albertel 12257: }
                   12258: 
1.474     albertel 12259: sub latest_receipt_algorithm_id {
1.835     albertel 12260:     return 'receipt3';
1.474     albertel 12261: }
                   12262: 
1.480     www      12263: sub recunique {
                   12264:     my $fucourseid=shift;
                   12265:     my $unique;
1.835     albertel 12266:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12267: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12268: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12269:     } else {
                   12270: 	$unique=$perlvar{'lonReceipt'};
                   12271:     }
                   12272:     return unpack("%32C*",$unique);
                   12273: }
                   12274: 
                   12275: sub recprefix {
                   12276:     my $fucourseid=shift;
                   12277:     my $prefix;
1.835     albertel 12278:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12279: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12280: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12281:     } else {
                   12282: 	$prefix=$perlvar{'lonHostID'};
                   12283:     }
                   12284:     return unpack("%32C*",$prefix);
                   12285: }
                   12286: 
1.76      www      12287: sub ireceipt {
1.474     albertel 12288:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12289: 
                   12290:     my $return =&recprefix($fucourseid).'-';
                   12291: 
                   12292:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12293: 	$env{'request.state'} eq 'construct') {
                   12294: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12295: 	return $return;
                   12296:     }
                   12297: 
1.76      www      12298:     my $cuname=unpack("%32C*",$funame);
                   12299:     my $cudom=unpack("%32C*",$fudom);
                   12300:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12301:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12302:     my $cunique=&recunique($fucourseid);
1.474     albertel 12303:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12304:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12305: 
1.790     albertel 12306: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12307: 			       
                   12308: 	$return.= ($cunique%$cuname+
                   12309: 		   $cunique%$cudom+
                   12310: 		   $cusymb%$cuname+
                   12311: 		   $cusymb%$cudom+
                   12312: 		   $cucourseid%$cuname+
                   12313: 		   $cucourseid%$cudom+
                   12314: 		   $cpart%$cuname+
                   12315: 		   $cpart%$cudom);
                   12316:     } else {
                   12317: 	$return.= ($cunique%$cuname+
                   12318: 		   $cunique%$cudom+
                   12319: 		   $cusymb%$cuname+
                   12320: 		   $cusymb%$cudom+
                   12321: 		   $cucourseid%$cuname+
                   12322: 		   $cucourseid%$cudom);
                   12323:     }
                   12324:     return $return;
1.76      www      12325: }
                   12326: 
                   12327: sub receipt {
1.474     albertel 12328:     my ($part)=@_;
1.790     albertel 12329:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12330:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12331: }
1.260     ng       12332: 
1.790     albertel 12333: sub whichuser {
                   12334:     my ($passedsymb)=@_;
                   12335:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12336:     if (defined($env{'form.grade_symb'})) {
                   12337: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12338: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12339: 	if (!$allowed &&
                   12340: 	    exists($env{'request.course.sec'}) &&
                   12341: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12342: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12343: 			      '/'.$env{'request.course.sec'});
                   12344: 	}
                   12345: 	if ($allowed) {
                   12346: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12347: 	    $courseid=$tmp_courseid;
                   12348: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12349: 	    ($name)=&get_env_multiple('form.grade_username');
                   12350: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12351: 	}
                   12352:     }
                   12353:     if (!$passedsymb) {
                   12354: 	$symb=&symbread();
                   12355:     } else {
                   12356: 	$symb=$passedsymb;
                   12357:     }
                   12358:     $courseid=$env{'request.course.id'};
                   12359:     $domain=$env{'user.domain'};
                   12360:     $name=$env{'user.name'};
                   12361:     if ($name eq 'public' && $domain eq 'public') {
                   12362: 	if (!defined($env{'form.username'})) {
                   12363: 	    $env{'form.username'}.=time.rand(10000000);
                   12364: 	}
                   12365: 	$name.=$env{'form.username'};
                   12366:     }
                   12367:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12368: 
                   12369: }
                   12370: 
1.36      albertel 12371: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12372: # returns either the contents of the file or 
                   12373: # -1 if the file doesn't exist
1.481     raeburn  12374: #
                   12375: # if the target is a file that was uploaded via DOCS, 
                   12376: # a check will be made to see if a current copy exists on the local server,
                   12377: # if it does this will be served, otherwise a copy will be retrieved from
                   12378: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12379: # the local server.   
1.472     albertel 12380: 
1.36      albertel 12381: sub getfile {
1.538     albertel 12382:     my ($file) = @_;
1.609     banghart 12383:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12384:     &repcopy($file);
                   12385:     return &readfile($file);
                   12386: }
                   12387: 
                   12388: sub repcopy_userfile {
                   12389:     my ($file)=@_;
1.1142    raeburn  12390:     my $londocroot = $perlvar{'lonDocRoot'};
                   12391:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12392:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12393:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12394: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12395:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12396:     if (-e "$file") {
1.828     www      12397: # we already have a local copy, check it out
1.538     albertel 12398: 	my @fileinfo = stat($file);
1.828     www      12399: 	my $rtncode;
                   12400: 	my $info;
1.538     albertel 12401: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12402: 	if ($lwpresp ne 'ok') {
1.828     www      12403: # there is no such file anymore, even though we had a local copy
1.482     albertel 12404: 	    if ($rtncode eq '404') {
1.538     albertel 12405: 		unlink($file);
1.482     albertel 12406: 	    }
                   12407: 	    return -1;
                   12408: 	}
                   12409: 	if ($info < $fileinfo[9]) {
1.828     www      12410: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12411: 	    return 'ok';
1.828     www      12412: 	} else {
                   12413: # the file is outdated, get rid of it
                   12414: 	    unlink($file);
1.482     albertel 12415: 	}
1.828     www      12416:     }
                   12417: # one way or the other, at this point, we don't have the file
                   12418: # construct the correct path for the file
                   12419:     my @parts = ($cdom,$cnum); 
                   12420:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12421: 	push @parts, split(/\//,$1);
                   12422:     }
                   12423:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12424:     foreach my $part (@parts) {
                   12425: 	$path .= '/'.$part;
                   12426: 	if (!-e $path) {
                   12427: 	    mkdir($path,0770);
1.482     albertel 12428: 	}
                   12429:     }
1.828     www      12430: # now the path exists for sure
                   12431: # get a user agent
                   12432:     my $ua=new LWP::UserAgent;
                   12433:     my $transferfile=$file.'.in.transfer';
                   12434: # FIXME: this should flock
                   12435:     if (-e $transferfile) { return 'ok'; }
                   12436:     my $request;
                   12437:     $uri=~s/^\///;
1.980     raeburn  12438:     my $homeserver = &homeserver($cnum,$cdom);
                   12439:     my $protocol = $protocol{$homeserver};
                   12440:     $protocol = 'http' if ($protocol ne 'https');
                   12441:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12442:     my $response=$ua->request($request,$transferfile);
                   12443: # did it work?
                   12444:     if ($response->is_error()) {
                   12445: 	unlink($transferfile);
                   12446: 	&logthis("Userfile repcopy failed for $uri");
                   12447: 	return -1;
                   12448:     }
                   12449: # worked, rename the transfer file
                   12450:     rename($transferfile,$file);
1.607     raeburn  12451:     return 'ok';
1.481     raeburn  12452: }
                   12453: 
1.517     albertel 12454: sub tokenwrapper {
                   12455:     my $uri=shift;
1.980     raeburn  12456:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12457:     $uri=~s|^/||;
1.620     albertel 12458:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12459:     my $token=$1;
1.552     albertel 12460:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12461:     if ($udom && $uname && $file) {
                   12462: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12463:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12464:         my $homeserver = &homeserver($uname,$udom);
                   12465:         my $protocol = $protocol{$homeserver};
                   12466:         $protocol = 'http' if ($protocol ne 'https');
                   12467:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12468:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12469:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12470:     } else {
                   12471:         return '/adm/notfound.html';
                   12472:     }
                   12473: }
                   12474: 
1.828     www      12475: # call with reqtype HEAD: get last modification time
                   12476: # call with reqtype GET: get the file contents
                   12477: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12478: #
1.481     raeburn  12479: sub getuploaded {
                   12480:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12481:     $uri=~s/^\///;
1.980     raeburn  12482:     my $homeserver = &homeserver($cnum,$cdom);
                   12483:     my $protocol = $protocol{$homeserver};
                   12484:     $protocol = 'http' if ($protocol ne 'https');
                   12485:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12486:     my $ua=new LWP::UserAgent;
                   12487:     my $request=new HTTP::Request($reqtype,$uri);
                   12488:     my $response=$ua->request($request);
                   12489:     $$rtncode = $response->code;
1.482     albertel 12490:     if (! $response->is_success()) {
                   12491: 	return 'failed';
                   12492:     }      
                   12493:     if ($reqtype eq 'HEAD') {
1.486     www      12494: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12495:     } elsif ($reqtype eq 'GET') {
                   12496: 	$$info = $response->content;
1.472     albertel 12497:     }
1.482     albertel 12498:     return 'ok';
1.36      albertel 12499: }
                   12500: 
1.481     raeburn  12501: sub readfile {
                   12502:     my $file = shift;
                   12503:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12504:     my $fh;
1.1172.2.96  raeburn  12505:     open($fh,"<",$file);
1.481     raeburn  12506:     my $a='';
1.800     albertel 12507:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12508:     return $a;
                   12509: }
                   12510: 
1.36      albertel 12511: sub filelocation {
1.590     banghart 12512:     my ($dir,$file) = @_;
                   12513:     my $location;
                   12514:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12515: 
                   12516:     if ($file =~ m-^/adm/-) {
                   12517: 	$file=~s-^/adm/wrapper/-/-;
                   12518: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12519:     }
1.882     albertel 12520: 
1.1139    www      12521:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12522:         $location = $file;
1.609     banghart 12523:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12524:         my ($udom,$uname,$filename)=
1.811     albertel 12525:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12526:         my $home=&homeserver($uname,$udom);
                   12527:         my $is_me=0;
                   12528:         my @ids=&current_machine_ids();
                   12529:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12530:         if ($is_me) {
1.1117    foxr     12531:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12532:         } else {
                   12533:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12534:   	      $udom.'/'.$uname.'/'.$filename;
                   12535:         }
1.882     albertel 12536:     } elsif ($file =~ m-^/adm/-) {
                   12537: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12538:     } else {
                   12539:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12540:         $file=~s:^/(res|priv)/:/:;
                   12541:         my $space=$1;
1.590     banghart 12542:         if ( !( $file =~ m:^/:) ) {
                   12543:             $location = $dir. '/'.$file;
                   12544:         } else {
1.1142    raeburn  12545:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12546:         }
1.59      albertel 12547:     }
1.590     banghart 12548:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12549:     while ($location=~m{/\.\./}) {
                   12550: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12551: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12552: 	} else {
                   12553: 	    $location=~ s{/\.\./}{/}g;
                   12554: 	}
                   12555:     } #remove dir/..
1.590     banghart 12556:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12557:     return $location;
1.46      www      12558: }
1.36      albertel 12559: 
1.46      www      12560: sub hreflocation {
                   12561:     my ($dir,$file)=@_;
1.980     raeburn  12562:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12563: 	$file=filelocation($dir,$file);
1.700     albertel 12564:     } elsif ($file=~m-^/adm/-) {
                   12565: 	$file=~s-^/adm/wrapper/-/-;
                   12566: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12567:     }
                   12568:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12569: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12570:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12571: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12572: 	        {/uploaded/$1/$2/}x;
1.46      www      12573:     }
1.913     albertel 12574:     if ($file=~ m{^/userfiles/}) {
                   12575: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12576:     }
1.462     albertel 12577:     return $file;
1.465     albertel 12578: }
                   12579: 
1.1139    www      12580: 
                   12581: 
                   12582: 
                   12583: 
1.465     albertel 12584: sub current_machine_domains {
1.853     albertel 12585:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12586: }
                   12587: 
                   12588: sub machine_domains {
                   12589:     my ($hostname) = @_;
1.465     albertel 12590:     my @domains;
1.838     albertel 12591:     my %hostname = &all_hostnames();
1.465     albertel 12592:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12593: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12594: 	if ($hostname eq $name) {
1.844     albertel 12595: 	    push(@domains,&host_domain($id));
1.465     albertel 12596: 	}
                   12597:     }
                   12598:     return @domains;
                   12599: }
                   12600: 
                   12601: sub current_machine_ids {
1.853     albertel 12602:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12603: }
                   12604: 
                   12605: sub machine_ids {
                   12606:     my ($hostname) = @_;
                   12607:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12608:     my @ids;
1.888     albertel 12609:     my %name_to_host = &all_names();
1.889     albertel 12610:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12611: 	return @{ $name_to_host{$hostname} };
                   12612:     }
                   12613:     return;
1.31      www      12614: }
                   12615: 
1.824     raeburn  12616: sub additional_machine_domains {
                   12617:     my @domains;
1.1172.2.96  raeburn  12618:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12619:     while( my $line = <$fh>) {
                   12620:         $line =~ s/\s//g;
                   12621:         push(@domains,$line);
                   12622:     }
                   12623:     return @domains;
                   12624: }
                   12625: 
                   12626: sub default_login_domain {
                   12627:     my $domain = $perlvar{'lonDefDomain'};
                   12628:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12629:     foreach my $posdom (&current_machine_domains(),
                   12630:                         &additional_machine_domains()) {
                   12631:         if (lc($posdom) eq lc($testdomain)) {
                   12632:             $domain=$posdom;
                   12633:             last;
                   12634:         }
                   12635:     }
                   12636:     return $domain;
                   12637: }
                   12638: 
1.31      www      12639: # ------------------------------------------------------------- Declutters URLs
                   12640: 
                   12641: sub declutter {
                   12642:     my $thisfn=shift;
1.569     albertel 12643:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12644:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12645:         $thisfn=~s{^/home/httpd/html}{};
                   12646:     }
1.31      www      12647:     $thisfn=~s/^\///;
1.697     albertel 12648:     $thisfn=~s|^adm/wrapper/||;
                   12649:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12650:     $thisfn=~s/^res\///;
1.1172    bisitz   12651:     $thisfn=~s/^priv\///;
1.1032    raeburn  12652:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12653:         $thisfn=~s/\?.+$//;
                   12654:     }
1.268     www      12655:     return $thisfn;
                   12656: }
                   12657: 
                   12658: # ------------------------------------------------------------- Clutter up URLs
                   12659: 
                   12660: sub clutter {
                   12661:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12662:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12663: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12664:        $thisfn='/res'.$thisfn; 
                   12665:     }
1.1031    raeburn  12666:     if ($thisfn !~m|^/adm|) {
                   12667: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12668: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12669: 	} else {
                   12670: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12671: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12672: 	    if ($embstyle eq 'ssi'
                   12673: 		|| ($embstyle eq 'hdn')
                   12674: 		|| ($embstyle eq 'rat')
                   12675: 		|| ($embstyle eq 'prv')
                   12676: 		|| ($embstyle eq 'ign')) {
                   12677: 		#do nothing with these
                   12678: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12679: 		|| ($embstyle eq 'emb')
                   12680: 		|| ($embstyle eq 'wrp')) {
                   12681: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12682: 	    } elsif ($embstyle eq 'unk'
                   12683: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12684: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12685: 	    } else {
1.718     www      12686: #		&logthis("Got a blank emb style");
1.695     albertel 12687: 	    }
1.694     albertel 12688: 	}
                   12689:     }
1.31      www      12690:     return $thisfn;
1.12      www      12691: }
                   12692: 
1.787     albertel 12693: sub clutter_with_no_wrapper {
                   12694:     my $uri = &clutter(shift);
                   12695:     if ($uri =~ m-^/adm/-) {
                   12696: 	$uri =~ s-^/adm/wrapper/-/-;
                   12697: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12698:     }
                   12699:     return $uri;
                   12700: }
                   12701: 
1.557     albertel 12702: sub freeze_escape {
                   12703:     my ($value)=@_;
                   12704:     if (ref($value)) {
                   12705: 	$value=&nfreeze($value);
                   12706: 	return '__FROZEN__'.&escape($value);
                   12707:     }
                   12708:     return &escape($value);
                   12709: }
                   12710: 
1.11      www      12711: 
1.557     albertel 12712: sub thaw_unescape {
                   12713:     my ($value)=@_;
                   12714:     if ($value =~ /^__FROZEN__/) {
                   12715: 	substr($value,0,10,undef);
                   12716: 	$value=&unescape($value);
                   12717: 	return &thaw($value);
                   12718:     }
                   12719:     return &unescape($value);
                   12720: }
                   12721: 
1.436     albertel 12722: sub correct_line_ends {
                   12723:     my ($result)=@_;
                   12724:     $$result =~s/\r\n/\n/mg;
                   12725:     $$result =~s/\r/\n/mg;
1.415     albertel 12726: }
1.1       albertel 12727: # ================================================================ Main Program
                   12728: 
1.184     www      12729: sub goodbye {
1.204     albertel 12730:    &logthis("Starting Shut down");
1.443     albertel 12731: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12732:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12733: #converted
1.599     albertel 12734: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12735:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12736: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12737: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12738: #1.1 only
1.870     albertel 12739: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12740: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12741: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12742: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12743:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12744:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12745:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12746:    &flushcourselogs();
                   12747:    &logthis("Shutting down");
                   12748: }
                   12749: 
1.852     albertel 12750: sub get_dns {
1.1172.2.17  raeburn  12751:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12752:     if (!$ignore_cache) {
                   12753: 	my ($content,$cached)=
                   12754: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12755: 	if ($cached) {
1.1172.2.17  raeburn  12756: 	    &$func($content,$hashref);
1.869     albertel 12757: 	    return;
                   12758: 	}
                   12759:     }
                   12760: 
                   12761:     my %alldns;
1.1172.2.96  raeburn  12762:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12763:         foreach my $dns (<$config>) {
                   12764: 	    next if ($dns !~ /^\^(\S*)/x);
                   12765:             my $line = $1;
                   12766:             my ($host,$protocol) = split(/:/,$line);
                   12767:             if ($protocol ne 'https') {
                   12768:                 $protocol = 'http';
                   12769:             }
                   12770: 	    $alldns{$host} = $protocol;
1.979     raeburn  12771:         }
1.1172.2.96  raeburn  12772:         close($config);
1.869     albertel 12773:     }
                   12774:     while (%alldns) {
1.1172.2.52  raeburn  12775: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12776: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12777:         $ua->timeout(30);
1.979     raeburn  12778: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12779: 	my $response=$ua->request($request);
1.979     raeburn  12780:         delete($alldns{$dns});
1.852     albertel 12781: 	next if ($response->is_error());
                   12782: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12783:         unless ($nocache) {
1.1172.2.23  raeburn  12784: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12785:         }
                   12786: 	&$func(\@content,$hashref);
1.869     albertel 12787: 	return;
1.852     albertel 12788:     }
                   12789:     close($config);
1.871     albertel 12790:     my $which = (split('/',$url))[3];
                   12791:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96  raeburn  12792:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12793:     my @content = <$config>;
1.1172.2.17  raeburn  12794:     &$func(\@content,$hashref);
                   12795:     return;
                   12796: }
                   12797: 
                   12798: # ------------------------------------------------------Get DNS checksums file
                   12799: sub parse_dns_checksums_tab {
                   12800:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12801:     my $lonhost = $perlvar{'lonHostID'};
                   12802:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12803:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12804:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12805:     my $webconfdir = '/etc/httpd/conf';
                   12806:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12807:         $webconfdir = '/etc/apache2';
                   12808:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12809:         if ($1 >= 10) {
                   12810:             $webconfdir = '/etc/apache2';
                   12811:         }
                   12812:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12813:         if ($1 >= 10.0) {
                   12814:             $webconfdir = '/etc/apache2';
                   12815:         }
                   12816:     }
1.1172.2.17  raeburn  12817:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12818:     my (%chksum,%revnum);
                   12819:     if (ref($lines) eq 'ARRAY') {
                   12820:         chomp(@{$lines});
1.1172.2.34  raeburn  12821:         my $version = shift(@{$lines});
                   12822:         if ($version eq $release) {
1.1172.2.17  raeburn  12823:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12824:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12825:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12826:                     if ($webconfdir eq '/etc/apache2') {
                   12827:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12828:                     }
                   12829:                 }
1.1172.2.34  raeburn  12830:                 $chksum{$file} = $shasum;
                   12831:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12832:             }
                   12833:             if (ref($hashref) eq 'HASH') {
                   12834:                 %{$hashref} = (
                   12835:                                 sums     => \%chksum,
                   12836:                                 versions => \%revnum,
                   12837:                               );
                   12838:             }
                   12839:         }
                   12840:     }
1.869     albertel 12841:     return;
1.852     albertel 12842: }
1.1172.2.17  raeburn  12843: 
                   12844: sub fetch_dns_checksums {
                   12845:     my %checksums;
1.1172.2.34  raeburn  12846:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12847:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12848:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12849:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12850:              \%checksums);
                   12851:     return \%checksums;
                   12852: }
                   12853: 
1.327     albertel 12854: # ------------------------------------------------------------ Read domain file
                   12855: {
1.852     albertel 12856:     my $loaded;
1.846     albertel 12857:     my %domain;
                   12858: 
1.852     albertel 12859:     sub parse_domain_tab {
                   12860: 	my ($lines) = @_;
                   12861: 	foreach my $line (@$lines) {
                   12862: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12863: 
1.846     albertel 12864: 	    chomp($line);
1.852     albertel 12865: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12866: 	    my %this_domain;
                   12867: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12868: 			       'lang_def', 'city', 'longi', 'lati',
                   12869: 			       'primary') {
                   12870: 		$this_domain{$field} = shift(@elements);
                   12871: 	    }
                   12872: 	    $domain{$name} = \%this_domain;
1.852     albertel 12873: 	}
                   12874:     }
1.864     albertel 12875: 
                   12876:     sub reset_domain_info {
                   12877: 	undef($loaded);
                   12878: 	undef(%domain);
                   12879:     }
                   12880: 
1.852     albertel 12881:     sub load_domain_tab {
1.1172.2.70  raeburn  12882: 	my ($ignore_cache,$nocache) = @_;
                   12883: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12884: 	my $fh;
1.1172.2.96  raeburn  12885: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 12886: 	    my @lines = <$fh>;
                   12887: 	    &parse_domain_tab(\@lines);
1.448     albertel 12888: 	}
1.852     albertel 12889: 	close($fh);
                   12890: 	$loaded = 1;
1.327     albertel 12891:     }
1.846     albertel 12892: 
                   12893:     sub domain {
1.852     albertel 12894: 	&load_domain_tab() if (!$loaded);
                   12895: 
1.846     albertel 12896: 	my ($name,$what) = @_;
                   12897: 	return if ( !exists($domain{$name}) );
                   12898: 
                   12899: 	if (!$what) {
                   12900: 	    return $domain{$name}{'description'};
                   12901: 	}
                   12902: 	return $domain{$name}{$what};
                   12903:     }
1.974     raeburn  12904: 
                   12905:     sub domain_info {
                   12906:         &load_domain_tab() if (!$loaded);
                   12907:         return %domain;
                   12908:     }
                   12909: 
1.327     albertel 12910: }
                   12911: 
                   12912: 
1.1       albertel 12913: # ------------------------------------------------------------- Read hosts file
                   12914: {
1.838     albertel 12915:     my %hostname;
1.844     albertel 12916:     my %hostdom;
1.845     albertel 12917:     my %libserv;
1.852     albertel 12918:     my $loaded;
1.888     albertel 12919:     my %name_to_host;
1.1074    raeburn  12920:     my %internetdom;
1.1107    raeburn  12921:     my %LC_dns_serv;
1.852     albertel 12922: 
                   12923:     sub parse_hosts_tab {
                   12924: 	my ($file) = @_;
                   12925: 	foreach my $configline (@$file) {
                   12926: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12927:             chomp($configline);
                   12928: 	    if ($configline =~ /^\^/) {
                   12929:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12930:                     $LC_dns_serv{$1} = 1;
                   12931:                 }
                   12932:                 next;
                   12933:             }
1.1074    raeburn  12934: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12935: 	    $name=~s/\s//g;
                   12936: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  12937:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   12938:                     my $curr = $hostname{$id};
                   12939:                     my $skip;
                   12940:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   12941:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   12942:                             $skip = 1;
                   12943:                         } else {
                   12944:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   12945:                         }
                   12946:                     }
                   12947:                     unless ($skip) {
                   12948:                         push(@{$name_to_host{$name}},$id);
                   12949:                     }
                   12950:                 } else {
                   12951:                     push(@{$name_to_host{$name}},$id);
                   12952:                 }
1.852     albertel 12953: 		$hostname{$id}=$name;
                   12954: 		$hostdom{$id}=$domain;
                   12955: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12956:                 if (defined($protocol)) {
                   12957:                     if ($protocol eq 'https') {
                   12958:                         $protocol{$id} = $protocol;
                   12959:                     } else {
                   12960:                         $protocol{$id} = 'http'; 
                   12961:                     }
1.968     raeburn  12962:                 } else {
1.969     raeburn  12963:                     $protocol{$id} = 'http';
1.968     raeburn  12964:                 }
1.1074    raeburn  12965:                 if (defined($intdom)) {
                   12966:                     $internetdom{$id} = $intdom;
                   12967:                 }
1.852     albertel 12968: 	    }
                   12969: 	}
                   12970:     }
1.864     albertel 12971:     
                   12972:     sub reset_hosts_info {
1.897     albertel 12973: 	&purge_remembered();
1.864     albertel 12974: 	&reset_domain_info();
                   12975: 	&reset_hosts_ip_info();
1.892     albertel 12976: 	undef(%name_to_host);
1.864     albertel 12977: 	undef(%hostname);
                   12978: 	undef(%hostdom);
                   12979: 	undef(%libserv);
                   12980: 	undef($loaded);
                   12981:     }
1.1       albertel 12982: 
1.852     albertel 12983:     sub load_hosts_tab {
1.1172.2.70  raeburn  12984: 	my ($ignore_cache,$nocache) = @_;
                   12985: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  12986: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 12987: 	my @config = <$config>;
                   12988: 	&parse_hosts_tab(\@config);
                   12989: 	close($config);
                   12990: 	$loaded=1;
1.1       albertel 12991:     }
1.852     albertel 12992: 
1.838     albertel 12993:     sub hostname {
1.852     albertel 12994: 	&load_hosts_tab() if (!$loaded);
                   12995: 
1.838     albertel 12996: 	my ($lonid) = @_;
                   12997: 	return $hostname{$lonid};
                   12998:     }
1.845     albertel 12999: 
1.838     albertel 13000:     sub all_hostnames {
1.852     albertel 13001: 	&load_hosts_tab() if (!$loaded);
                   13002: 
1.838     albertel 13003: 	return %hostname;
                   13004:     }
1.845     albertel 13005: 
1.888     albertel 13006:     sub all_names {
1.1172.2.70  raeburn  13007:         my ($ignore_cache,$nocache) = @_;
                   13008: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13009: 
                   13010: 	return %name_to_host;
                   13011:     }
                   13012: 
1.974     raeburn  13013:     sub all_host_domain {
                   13014:         &load_hosts_tab() if (!$loaded);
                   13015:         return %hostdom;
                   13016:     }
                   13017: 
1.845     albertel 13018:     sub is_library {
1.852     albertel 13019: 	&load_hosts_tab() if (!$loaded);
                   13020: 
1.845     albertel 13021: 	return exists($libserv{$_[0]});
                   13022:     }
                   13023: 
                   13024:     sub all_library {
1.852     albertel 13025: 	&load_hosts_tab() if (!$loaded);
                   13026: 
1.845     albertel 13027: 	return %libserv;
                   13028:     }
                   13029: 
1.1062    droeschl 13030:     sub unique_library {
                   13031: 	#2x reverse removes all hostnames that appear more than once
                   13032:         my %unique = reverse &all_library();
                   13033:         return reverse %unique;
                   13034:     }
                   13035: 
1.841     albertel 13036:     sub get_servers {
1.852     albertel 13037: 	&load_hosts_tab() if (!$loaded);
                   13038: 
1.841     albertel 13039: 	my ($domain,$type) = @_;
                   13040: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13041: 	                                          : %hostname;
                   13042: 	my %result;
1.842     albertel 13043: 	if (ref($domain) eq 'ARRAY') {
                   13044: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13045: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13046: 		    $result{$host} = $hostname;
                   13047: 		}
                   13048: 	    }
                   13049: 	} else {
                   13050: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13051: 		if ($hostdom{$host} eq $domain) {
                   13052: 		    $result{$host} = $hostname;
                   13053: 		}
1.841     albertel 13054: 	    }
                   13055: 	}
                   13056: 	return %result;
                   13057:     }
1.845     albertel 13058: 
1.1062    droeschl 13059:     sub get_unique_servers {
                   13060:         my %unique = reverse &get_servers(@_);
                   13061: 	return reverse %unique;
                   13062:     }
                   13063: 
1.844     albertel 13064:     sub host_domain {
1.852     albertel 13065: 	&load_hosts_tab() if (!$loaded);
                   13066: 
1.844     albertel 13067: 	my ($lonid) = @_;
                   13068: 	return $hostdom{$lonid};
                   13069:     }
                   13070: 
1.841     albertel 13071:     sub all_domains {
1.852     albertel 13072: 	&load_hosts_tab() if (!$loaded);
                   13073: 
1.841     albertel 13074: 	my %seen;
                   13075: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13076: 	return @uniq;
                   13077:     }
1.1074    raeburn  13078: 
                   13079:     sub internet_dom {
                   13080:         &load_hosts_tab() if (!$loaded);
                   13081: 
                   13082:         my ($lonid) = @_;
                   13083:         return $internetdom{$lonid};
                   13084:     }
1.1107    raeburn  13085: 
                   13086:     sub is_LC_dns {
                   13087:         &load_hosts_tab() if (!$loaded);
                   13088: 
                   13089:         my ($hostname) = @_;
                   13090:         return exists($LC_dns_serv{$hostname});
                   13091:     }
                   13092: 
1.1       albertel 13093: }
                   13094: 
1.847     albertel 13095: { 
                   13096:     my %iphost;
1.856     albertel 13097:     my %name_to_ip;
                   13098:     my %lonid_to_ip;
1.869     albertel 13099: 
1.847     albertel 13100:     sub get_hosts_from_ip {
                   13101: 	my ($ip) = @_;
                   13102: 	my %iphosts = &get_iphost();
                   13103: 	if (ref($iphosts{$ip})) {
                   13104: 	    return @{$iphosts{$ip}};
                   13105: 	}
                   13106: 	return;
1.839     albertel 13107:     }
1.864     albertel 13108:     
                   13109:     sub reset_hosts_ip_info {
                   13110: 	undef(%iphost);
                   13111: 	undef(%name_to_ip);
                   13112: 	undef(%lonid_to_ip);
                   13113:     }
1.856     albertel 13114: 
                   13115:     sub get_host_ip {
                   13116: 	my ($lonid) = @_;
                   13117: 	if (exists($lonid_to_ip{$lonid})) {
                   13118: 	    return $lonid_to_ip{$lonid};
                   13119: 	}
                   13120: 	my $name=&hostname($lonid);
                   13121:    	my $ip = gethostbyname($name);
                   13122: 	return if (!$ip || length($ip) ne 4);
                   13123: 	$ip=inet_ntoa($ip);
                   13124: 	$name_to_ip{$name}   = $ip;
                   13125: 	$lonid_to_ip{$lonid} = $ip;
                   13126: 	return $ip;
                   13127:     }
1.847     albertel 13128:     
                   13129:     sub get_iphost {
1.1172.2.70  raeburn  13130: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13131: 
1.869     albertel 13132: 	if (!$ignore_cache) {
                   13133: 	    if (%iphost) {
                   13134: 		return %iphost;
                   13135: 	    }
                   13136: 	    my ($ip_info,$cached)=
                   13137: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13138: 	    if ($cached) {
                   13139: 		%iphost      = %{$ip_info->[0]};
                   13140: 		%name_to_ip  = %{$ip_info->[1]};
                   13141: 		%lonid_to_ip = %{$ip_info->[2]};
                   13142: 		return %iphost;
                   13143: 	    }
                   13144: 	}
1.894     albertel 13145: 
                   13146: 	# get yesterday's info for fallback
                   13147: 	my %old_name_to_ip;
                   13148: 	my ($ip_info,$cached)=
                   13149: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13150: 	if ($cached) {
                   13151: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13152: 	}
                   13153: 
1.1172.2.70  raeburn  13154: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13155: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13156: 	    my $ip;
                   13157: 	    if (!exists($name_to_ip{$name})) {
                   13158: 		$ip = gethostbyname($name);
                   13159: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13160: 		    if (defined($old_name_to_ip{$name})) {
                   13161: 			$ip = $old_name_to_ip{$name};
                   13162: 			&logthis("Can't find $name defaulting to old $ip");
                   13163: 		    } else {
                   13164: 			&logthis("Name $name no IP found");
                   13165: 			next;
                   13166: 		    }
                   13167: 		} else {
                   13168: 		    $ip=inet_ntoa($ip);
1.847     albertel 13169: 		}
                   13170: 		$name_to_ip{$name} = $ip;
                   13171: 	    } else {
                   13172: 		$ip = $name_to_ip{$name};
1.653     albertel 13173: 	    }
1.888     albertel 13174: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13175: 		$lonid_to_ip{$id} = $ip;
                   13176: 	    }
                   13177: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13178: 	}
1.1172.2.70  raeburn  13179:         unless ($nocache) {
                   13180: 	    &do_cache_new('iphost','iphost',
                   13181: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13182: 		          48*60*60);
                   13183:         }
1.869     albertel 13184: 
1.847     albertel 13185: 	return %iphost;
1.598     albertel 13186:     }
                   13187: 
1.992     raeburn  13188:     #
                   13189:     #  Given a DNS returns the loncapa host name for that DNS 
                   13190:     # 
                   13191:     sub host_from_dns {
                   13192:         my ($dns) = @_;
                   13193:         my @hosts;
                   13194:         my $ip;
                   13195: 
1.993     raeburn  13196:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13197:             $ip = $name_to_ip{$dns};
                   13198:         }
                   13199:         if (!$ip) {
                   13200:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13201:             if (length($ip) == 4) { 
                   13202: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13203:             }
                   13204:         }
                   13205:         if ($ip) {
                   13206: 	    @hosts = get_hosts_from_ip($ip);
                   13207: 	    return $hosts[0];
                   13208:         }
                   13209:         return undef;
1.986     foxr     13210:     }
1.992     raeburn  13211: 
1.1074    raeburn  13212:     sub get_internet_names {
                   13213:         my ($lonid) = @_;
                   13214:         return if ($lonid eq '');
                   13215:         my ($idnref,$cached)=
                   13216:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13217:         if ($cached) {
                   13218:             return $idnref;
                   13219:         }
                   13220:         my $ip = &get_host_ip($lonid);
                   13221:         my @hosts = &get_hosts_from_ip($ip);
                   13222:         my %iphost = &get_iphost();
                   13223:         my (@idns,%seen);
                   13224:         foreach my $id (@hosts) {
                   13225:             my $dom = &host_domain($id);
                   13226:             my $prim_id = &domain($dom,'primary');
                   13227:             my $prim_ip = &get_host_ip($prim_id);
                   13228:             next if ($seen{$prim_ip});
                   13229:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13230:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13231:                     my $intdom = &internet_dom($id);
                   13232:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13233:                         push(@idns,$intdom);
                   13234:                     }
                   13235:                 }
                   13236:             }
                   13237:             $seen{$prim_ip} = 1;
                   13238:         }
1.1172.2.23  raeburn  13239:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13240:     }
                   13241: 
1.986     foxr     13242: }
                   13243: 
1.1079    raeburn  13244: sub all_loncaparevs {
1.1172.2.39  raeburn  13245:     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 2.11);
1.1079    raeburn  13246: }
                   13247: 
1.1172.2.27  raeburn  13248: # ------------------------------------------------------- Read loncaparev table
                   13249: {
                   13250:     sub load_loncaparevs {
                   13251:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13252:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13253:                 while (my $configline=<$config>) {
                   13254:                     chomp($configline);
                   13255:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13256:                     $loncaparevs{$hostid}=$loncaparev;
                   13257:                 }
                   13258:                 close($config);
                   13259:             }
                   13260:         }
                   13261:     }
                   13262: }
                   13263: 
                   13264: # ----------------------------------------------------- Read serverhostID table
                   13265: {
                   13266:     sub load_serverhomeIDs {
                   13267:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13268:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13269:                 while (my $configline=<$config>) {
                   13270:                     chomp($configline);
                   13271:                     my ($name,$id)=split(/:/,$configline);
                   13272:                     $serverhomeIDs{$name}=$id;
                   13273:                 }
                   13274:                 close($config);
                   13275:             }
                   13276:         }
                   13277:     }
                   13278: }
                   13279: 
                   13280: 
1.862     albertel 13281: BEGIN {
                   13282: 
                   13283: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13284:     unless ($readit) {
                   13285: {
                   13286:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13287:     %perlvar = (%perlvar,%{$configvars});
                   13288: }
                   13289: 
                   13290: 
1.1       albertel 13291: # ------------------------------------------------------ Read spare server file
                   13292: {
1.1172.2.96  raeburn  13293:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13294: 
                   13295:     while (my $configline=<$config>) {
                   13296:        chomp($configline);
1.284     matthew  13297:        if ($configline) {
1.784     albertel 13298: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13299: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13300: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13301:        }
                   13302:     }
1.448     albertel 13303:     close($config);
1.1       albertel 13304: }
1.11      www      13305: # ------------------------------------------------------------ Read permissions
                   13306: {
1.1172.2.96  raeburn  13307:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13308: 
                   13309:     while (my $configline=<$config>) {
1.448     albertel 13310: 	chomp($configline);
                   13311: 	if ($configline) {
                   13312: 	    my ($role,$perm)=split(/ /,$configline);
                   13313: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13314: 	}
1.11      www      13315:     }
1.448     albertel 13316:     close($config);
1.11      www      13317: }
                   13318: 
                   13319: # -------------------------------------------- Read plain texts for permissions
                   13320: {
1.1172.2.96  raeburn  13321:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13322: 
                   13323:     while (my $configline=<$config>) {
1.448     albertel 13324: 	chomp($configline);
                   13325: 	if ($configline) {
1.742     raeburn  13326: 	    my ($short,@plain)=split(/:/,$configline);
                   13327:             %{$prp{$short}} = ();
                   13328: 	    if (@plain > 0) {
                   13329:                 $prp{$short}{'std'} = $plain[0];
                   13330:                 for (my $i=1; $i<@plain; $i++) {
                   13331:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13332:                 }
                   13333:             }
1.448     albertel 13334: 	}
1.135     www      13335:     }
1.448     albertel 13336:     close($config);
1.135     www      13337: }
                   13338: 
                   13339: # ---------------------------------------------------------- Read package table
                   13340: {
1.1172.2.96  raeburn  13341:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13342: 
                   13343:     while (my $configline=<$config>) {
1.483     albertel 13344: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13345: 	chomp($configline);
                   13346: 	my ($short,$plain)=split(/:/,$configline);
                   13347: 	my ($pack,$name)=split(/\&/,$short);
                   13348: 	if ($plain ne '') {
                   13349: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13350: 	    $packagetab{$short}=$plain; 
                   13351: 	}
1.11      www      13352:     }
1.448     albertel 13353:     close($config);
1.329     matthew  13354: }
                   13355: 
1.1172.2.27  raeburn  13356: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13357: 
1.1172.2.27  raeburn  13358: &load_loncaparevs();
                   13359: 
                   13360: # ------------------------------------------------------- Read serverhostID table
                   13361: 
                   13362: &load_serverhomeIDs();
1.1074    raeburn  13363: 
1.1172.2.27  raeburn  13364: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13365: {
                   13366:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13367:     if (-e $file) {
                   13368:         my $parser = HTML::LCParser->new($file);
                   13369:         while (my $token = $parser->get_token()) {
                   13370:             if ($token->[0] eq 'S') {
                   13371:                 my $item = $token->[1];
                   13372:                 my $name = $token->[2]{'name'};
                   13373:                 my $value = $token->[2]{'value'};
                   13374:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13375:                     my $release = $parser->get_text();
                   13376:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13377:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13378:                 }
                   13379:             }
                   13380:         }
                   13381:     }
1.1073    raeburn  13382: }
                   13383: 
1.1138    raeburn  13384: # ---------------------------------------------------------- Read managers table
                   13385: {
                   13386:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13387:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13388:             while (my $configline=<$config>) {
                   13389:                 chomp($configline);
                   13390:                 next if ($configline =~ /^\#/);
                   13391:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13392:                     $managerstab{$configline} = 1;
                   13393:                 }
                   13394:             }
                   13395:             close($config);
                   13396:         }
                   13397:     }
                   13398: }
                   13399: 
1.329     matthew  13400: # ------------- set up temporary directory
                   13401: {
1.1117    foxr     13402:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13403: 
1.11      www      13404: }
                   13405: 
1.794     albertel 13406: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13407: 				'compress_threshold'=> 20_000,
                   13408:  			        });
1.185     www      13409: 
1.281     www      13410: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13411: $dumpcount=0;
1.958     www      13412: $locknum=0;
1.22      www      13413: 
1.163     harris41 13414: &logtouch();
1.672     albertel 13415: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13416: $readit=1;
1.564     albertel 13417:     {
                   13418: 	use integer;
                   13419: 	my $test=(2**32)+1;
1.568     albertel 13420: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13421: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13422:     }
1.195     www      13423: }
1.1       albertel 13424: }
1.179     www      13425: 
1.1       albertel 13426: 1;
1.191     harris41 13427: __END__
                   13428: 
1.243     albertel 13429: =pod
                   13430: 
1.191     harris41 13431: =head1 NAME
                   13432: 
1.243     albertel 13433: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13434: 
                   13435: =head1 SYNOPSIS
                   13436: 
1.243     albertel 13437: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13438: 
                   13439:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13440: 
1.243     albertel 13441: Common parameters:
                   13442: 
                   13443: =over 4
                   13444: 
                   13445: =item *
                   13446: 
                   13447: $uname : an internal username (if $cname expecting a course Id specifically)
                   13448: 
                   13449: =item *
                   13450: 
                   13451: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13452: 
                   13453: =item *
                   13454: 
                   13455: $symb : a resource instance identifier
                   13456: 
                   13457: =item *
                   13458: 
                   13459: $namespace : the name of a .db file that contains the data needed or
                   13460: being set.
                   13461: 
                   13462: =back
                   13463: 
1.394     bowersj2 13464: =head1 OVERVIEW
1.191     harris41 13465: 
1.394     bowersj2 13466: lonnet provides subroutines which interact with the
                   13467: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13468: about classes, users, and resources.
1.243     albertel 13469: 
                   13470: For many of these objects you can also use this to store data about
                   13471: them or modify them in various ways.
1.191     harris41 13472: 
1.394     bowersj2 13473: =head2 Symbs
1.191     harris41 13474: 
1.394     bowersj2 13475: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13476: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13477: map, the resource number of the resource in the map, and the URL of
                   13478: the resource itself. The latter is somewhat redundant, but might help
                   13479: if maps change.
                   13480: 
                   13481: An example is
                   13482: 
                   13483:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13484: 
                   13485: The respective map entry is
                   13486: 
                   13487:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13488:   title="Problem 2">
                   13489:  </resource>
                   13490: 
                   13491: Symbs are used by the random number generator, as well as to store and
                   13492: restore data specific to a certain instance of for example a problem.
                   13493: 
                   13494: =head2 Storing And Retrieving Data
                   13495: 
                   13496: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13497: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13498: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13499: is is the non-critical message twin of cstore. These functions are for
                   13500: handlers to store a perl hash to a user's permanent data space in an
                   13501: easy manner, and to retrieve it again on another call. It is expected
                   13502: that a handler would use this once at the beginning to retrieve data,
                   13503: and then again once at the end to send only the new data back.
                   13504: 
                   13505: The data is stored in the user's data directory on the user's
                   13506: homeserver under the ID of the course.
                   13507: 
                   13508: The hash that is returned by restore will have all of the previous
                   13509: value for all of the elements of the hash.
                   13510: 
                   13511: Example:
                   13512: 
                   13513:  #creating a hash
                   13514:  my %hash;
                   13515:  $hash{'foo'}='bar';
                   13516: 
                   13517:  #storing it
                   13518:  &Apache::lonnet::cstore(\%hash);
                   13519: 
                   13520:  #changing a value
                   13521:  $hash{'foo'}='notbar';
                   13522: 
                   13523:  #adding a new value
                   13524:  $hash{'bar'}='foo';
                   13525:  &Apache::lonnet::cstore(\%hash);
                   13526: 
                   13527:  #retrieving the hash
                   13528:  my %history=&Apache::lonnet::restore();
                   13529: 
                   13530:  #print the hash
                   13531:  foreach my $key (sort(keys(%history))) {
                   13532:    print("\%history{$key} = $history{$key}");
                   13533:  }
                   13534: 
                   13535: Will print out:
1.191     harris41 13536: 
1.394     bowersj2 13537:  %history{1:foo} = bar
                   13538:  %history{1:keys} = foo:timestamp
                   13539:  %history{1:timestamp} = 990455579
                   13540:  %history{2:bar} = foo
                   13541:  %history{2:foo} = notbar
                   13542:  %history{2:keys} = foo:bar:timestamp
                   13543:  %history{2:timestamp} = 990455580
                   13544:  %history{bar} = foo
                   13545:  %history{foo} = notbar
                   13546:  %history{timestamp} = 990455580
                   13547:  %history{version} = 2
                   13548: 
                   13549: Note that the special hash entries C<keys>, C<version> and
                   13550: C<timestamp> were added to the hash. C<version> will be equal to the
                   13551: total number of versions of the data that have been stored. The
                   13552: C<timestamp> attribute will be the UNIX time the hash was
                   13553: stored. C<keys> is available in every historical section to list which
                   13554: keys were added or changed at a specific historical revision of a
                   13555: hash.
                   13556: 
                   13557: B<Warning>: do not store the hash that restore returns directly. This
                   13558: will cause a mess since it will restore the historical keys as if the
                   13559: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13560: 
1.394     bowersj2 13561: Calling convention:
1.191     harris41 13562: 
1.1172.2.27  raeburn  13563:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13564:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13565: 
1.394     bowersj2 13566: For more detailed information, see lonnet specific documentation.
1.191     harris41 13567: 
1.394     bowersj2 13568: =head1 RETURN MESSAGES
1.191     harris41 13569: 
1.394     bowersj2 13570: =over 4
1.191     harris41 13571: 
1.394     bowersj2 13572: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13573: 
1.394     bowersj2 13574: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13575: when the connection is brought back up
1.191     harris41 13576: 
1.394     bowersj2 13577: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13578: for later delivery
1.191     harris41 13579: 
1.967     bisitz   13580: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13581: 
1.394     bowersj2 13582: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13583: that was requested
1.191     harris41 13584: 
1.243     albertel 13585: =back
1.191     harris41 13586: 
1.243     albertel 13587: =head1 PUBLIC SUBROUTINES
1.191     harris41 13588: 
1.243     albertel 13589: =head2 Session Environment Functions
1.191     harris41 13590: 
1.243     albertel 13591: =over 4
1.191     harris41 13592: 
1.394     bowersj2 13593: =item * 
                   13594: X<appenv()>
1.949     raeburn  13595: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13596: the user envirnoment file, and will be restored for each access this
1.620     albertel 13597: user makes during this session, also modifies the %env for the current
1.949     raeburn  13598: process. Optional rolesarrayref - if defined contains a reference to an array
                   13599: of roles which are exempt from the restriction on modifying user.role entries 
                   13600: in the user's environment.db and in %env.    
1.191     harris41 13601: 
                   13602: =item *
1.394     bowersj2 13603: X<delenv()>
1.987     raeburn  13604: B<delenv($delthis,$regexp)>: removes all items from the session
                   13605: environment file that begin with $delthis. If the 
                   13606: optional second arg - $regexp - is true, $delthis is treated as a 
                   13607: regular expression, otherwise \Q$delthis\E is used. 
                   13608: The values are also deleted from the current processes %env.
1.191     harris41 13609: 
1.795     albertel 13610: =item * get_env_multiple($name) 
                   13611: 
                   13612: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13613: values may be defined and end up as an array ref.
                   13614: 
                   13615: returns an array of values
                   13616: 
1.243     albertel 13617: =back
                   13618: 
                   13619: =head2 User Information
1.191     harris41 13620: 
1.243     albertel 13621: =over 4
1.191     harris41 13622: 
                   13623: =item *
1.394     bowersj2 13624: X<queryauthenticate()>
                   13625: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13626: authentication scheme
                   13627: 
                   13628: =item *
1.394     bowersj2 13629: X<authenticate()>
1.1073    raeburn  13630: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13631: authenticate user from domain's lib servers (first use the current
                   13632: one). C<$upass> should be the users password.
1.1073    raeburn  13633: $checkdefauth is optional (value is 1 if a check should be made to
                   13634:    authenticate user using default authentication method, and allow
                   13635:    account creation if username does not have account in the domain).
                   13636: $clientcancheckhost is optional (value is 1 if checking whether the
                   13637:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13638: 
                   13639: =item *
1.394     bowersj2 13640: X<homeserver()>
                   13641: B<homeserver($uname,$udom)>: find the server which has
                   13642: the user's directory and files (there must be only one), this caches
                   13643: the answer, and also caches if there is a borken connection.
1.191     harris41 13644: 
                   13645: =item *
1.394     bowersj2 13646: X<idget()>
                   13647: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13648: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13649: username, and only 1 username per ID in a specific domain) (returns
                   13650: hash: id=>name,id=>name)
1.191     harris41 13651: 
                   13652: =item *
1.394     bowersj2 13653: X<idrget()>
                   13654: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13655: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13656: 
                   13657: =item *
1.394     bowersj2 13658: X<idput()>
                   13659: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13660: 
                   13661: =item *
1.394     bowersj2 13662: X<rolesinit()>
1.1169    droeschl 13663: B<rolesinit($udom,$username)>: get user privileges.
                   13664: returns user role, first access and timer interval hashes
1.243     albertel 13665: 
                   13666: =item *
1.1171    droeschl 13667: X<privileged()>
                   13668: B<privileged($username,$domain)>: returns a true if user has a
                   13669: privileged and active role (i.e. su or dc), false otherwise.
                   13670: 
                   13671: =item *
1.551     albertel 13672: X<getsection()>
                   13673: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13674: course $cname, return section name/number or '' for "not in course"
                   13675: and '-1' for "no section"
                   13676: 
                   13677: =item *
1.394     bowersj2 13678: X<userenvironment()>
                   13679: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13680: passed in @what from the requested user's environment, returns a hash
                   13681: 
1.858     raeburn  13682: =item * 
                   13683: X<userlog_query()>
1.859     albertel 13684: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13685: activity.log file. %filters defines filters applied when parsing the
                   13686: log file. These can be start or end timestamps, or the type of action
                   13687: - log to look for Login or Logout events, check for Checkin or
                   13688: Checkout, role for role selection. The response is in the form
                   13689: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13690: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13691: 
1.243     albertel 13692: =back
                   13693: 
                   13694: =head2 User Roles
                   13695: 
                   13696: =over 4
                   13697: 
                   13698: =item *
                   13699: 
1.1172.2.65  raeburn  13700: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13701: returns codes for allowed actions.
                   13702: 
                   13703: The first argument is required, all others are optional.
                   13704: 
                   13705: $priv is the privilege being checked.
                   13706: $uri contains additional information about what is being checked for access (e.g.,
                   13707: URL, course ID etc.).
                   13708: $symb is the unique resource instance identifier in a course; if needed,
                   13709: but not provided, it will be retrieved via a call to &symbread().
                   13710: $role is the role for which a priv is being checked (only used if priv is evb).
                   13711: $clientip is the user's IP address (only used when checking for access to portfolio
                   13712: files).
                   13713: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13714: prevents recursive calls to &allowed.
                   13715: 
1.243     albertel 13716:  F: full access
                   13717:  U,I,K: authentication modes (cxx only)
                   13718:  '': forbidden
                   13719:  1: user needs to choose course
                   13720:  2: browse allowed
1.766     albertel 13721:  A: passphrase authentication needed
1.1172.2.65  raeburn  13722:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13723: 
                   13724: =item *
                   13725: 
1.1172.2.13  raeburn  13726: constructaccess($url,$setpriv) : check for access to construction space URL
                   13727: 
                   13728: See if the owner domain and name in the URL match those in the
                   13729: expected environment.  If so, return three element list
                   13730: ($ownername,$ownerdomain,$ownerhome).
                   13731: 
                   13732: Otherwise return the null string.
                   13733: 
                   13734: If second argument 'setpriv' is true, it assigns the privileges,
                   13735: and returns the same three element list, unless the owner has
                   13736: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13737: in which case the null string is returned.
                   13738: 
                   13739: =item *
                   13740: 
1.1172.2.84  raeburn  13741: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13742: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13743: for system, domain, and course level. $uname and $udom are optional (current
                   13744: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13745: 
                   13746: =item *
                   13747: 
1.988     raeburn  13748: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13749: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13750: $type is Course (default) or Community.
1.988     raeburn  13751: If $forcedefault evaluates to true, text returned will be default 
                   13752: text for $type. Otherwise, if this is a course, the text returned 
                   13753: will be a custom name for the role (if defined in the course's 
                   13754: environment).  If no custom name is defined the default is returned.
                   13755:    
1.832     raeburn  13756: =item *
                   13757: 
1.1172.2.23  raeburn  13758: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13759: All arguments are optional. Returns a hash of a roles, either for
                   13760: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13761: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13762: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13763: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13764: For each key, value is set to colon-separated start and end times for
                   13765: the role.  If no username and domain are specified, will default to
1.934     raeburn  13766: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13767: of role statuses (active, future or previous), roles 
                   13768: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13769: to restrict the list of roles reported. If no array ref is 
                   13770: provided for types, will default to return only active roles.
1.834     albertel 13771: 
1.1172.2.13  raeburn  13772: =item *
                   13773: 
                   13774: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13775: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13776: 
                   13777: Additional optional arguments are: $type (if role checking is to be restricted
                   13778: to certain user status types -- previous (expired roles), active (currently
                   13779: available roles) or future (roles available in the future), and
                   13780: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13781: have active Domain Coordinator role in course's domain or in additional
                   13782: domains (specified in 'Domains to check for privileged users' in course
                   13783: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13784: 
                   13785: =item *
                   13786: 
                   13787: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13788: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13789: $possdomains and $possroles are optional array refs -- to domains to check and
                   13790: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13791: users' roles.db to check for a dc or su role in any domain. This can be
                   13792: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13793: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13794: this then allows &privileged_by_domain() to be used, which caches the identity
                   13795: of privileged users, eliminating the need for repeated calls to &dump().
                   13796: 
                   13797: =item *
                   13798: 
                   13799: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13800: where the outer hash keys are domains specified in the $possdomains array ref,
                   13801: next inner hash keys are privileged roles specified in the $roles array ref,
                   13802: and the innermost hash contains key = value pairs for username:domain = end:start
                   13803: for active or future "privileged" users with that role in that domain. To avoid
                   13804: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13805: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13806: 
1.243     albertel 13807: =back
                   13808: 
                   13809: =head2 User Modification
                   13810: 
                   13811: =over 4
                   13812: 
                   13813: =item *
                   13814: 
1.957     raeburn  13815: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13816: user for the level given by URL.  Optional start and end dates (leave empty
                   13817: string or zero for "no date")
1.191     harris41 13818: 
                   13819: =item *
                   13820: 
1.243     albertel 13821: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13822: change a users, password, possible return values are: ok,
                   13823: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13824: refused
1.191     harris41 13825: 
                   13826: =item *
                   13827: 
1.243     albertel 13828: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13829: 
                   13830: =item *
                   13831: 
1.1058    raeburn  13832: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13833:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13834: 
                   13835: will update user information (firstname,middlename,lastname,generation,
                   13836: permanentemail), and if forceid is true, student/employee ID also.
                   13837: A user's institutional affiliation(s) can also be updated.
                   13838: User information fields will not be overwritten with empty entries 
                   13839: unless the field is included in the $candelete array reference.
                   13840: This array is included when a single user is modified via "Manage Users",
                   13841: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13842: 
                   13843: =item *
                   13844: 
1.286     matthew  13845: modifystudent
                   13846: 
1.957     raeburn  13847: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13848: The course id is resolved based on the current user's environment.  
                   13849: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13850: associated with a course.
                   13851: 
1.297     matthew  13852: This call is essentially a wrapper for lonnet::modifyuser and
                   13853: lonnet::modify_student_enrollment
1.286     matthew  13854: 
                   13855: Inputs: 
                   13856: 
                   13857: =over 4
                   13858: 
1.957     raeburn  13859: =item B<$udom> Student's loncapa domain
1.286     matthew  13860: 
1.957     raeburn  13861: =item B<$uname> Student's loncapa login name
1.286     matthew  13862: 
1.964     bisitz   13863: =item B<$uid> Student/Employee ID
1.286     matthew  13864: 
1.957     raeburn  13865: =item B<$umode> Student's authentication mode
1.286     matthew  13866: 
1.957     raeburn  13867: =item B<$upass> Student's password
1.286     matthew  13868: 
1.957     raeburn  13869: =item B<$first> Student's first name
1.286     matthew  13870: 
1.957     raeburn  13871: =item B<$middle> Student's middle name
1.286     matthew  13872: 
1.957     raeburn  13873: =item B<$last> Student's last name
1.286     matthew  13874: 
1.957     raeburn  13875: =item B<$gene> Student's generation
1.286     matthew  13876: 
1.957     raeburn  13877: =item B<$usec> Student's section in course
1.286     matthew  13878: 
                   13879: =item B<$end> Unix time of the roles expiration
                   13880: 
                   13881: =item B<$start> Unix time of the roles start date
                   13882: 
                   13883: =item B<$forceid> If defined, allow $uid to be changed
                   13884: 
                   13885: =item B<$desiredhome> server to use as home server for student
                   13886: 
1.957     raeburn  13887: =item B<$email> Student's permanent e-mail address
                   13888: 
                   13889: =item B<$type> Type of enrollment (auto or manual)
                   13890: 
1.963     raeburn  13891: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13892: 
                   13893: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13894: 
1.963     raeburn  13895: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13896: 
1.963     raeburn  13897: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13898: 
1.1172.2.19  raeburn  13899: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13900: 
                   13901: =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  13902: 
1.286     matthew  13903: =back
1.297     matthew  13904: 
                   13905: =item *
                   13906: 
                   13907: modify_student_enrollment
                   13908: 
1.1172.2.31  raeburn  13909: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13910: 'role.request.course' must be defined for this function to proceed.
                   13911: 
                   13912: Inputs:
                   13913: 
                   13914: =over 4
                   13915: 
1.1172.2.31  raeburn  13916: =item $udom, student's domain
1.297     matthew  13917: 
1.1172.2.31  raeburn  13918: =item $uname, student's name
1.297     matthew  13919: 
1.1172.2.31  raeburn  13920: =item $uid, student's user id
1.297     matthew  13921: 
1.1172.2.31  raeburn  13922: =item $first, student's first name
1.297     matthew  13923: 
                   13924: =item $middle
                   13925: 
                   13926: =item $last
                   13927: 
                   13928: =item $gene
                   13929: 
                   13930: =item $usec
                   13931: 
                   13932: =item $end
                   13933: 
                   13934: =item $start
                   13935: 
1.957     raeburn  13936: =item $type
                   13937: 
                   13938: =item $locktype
                   13939: 
                   13940: =item $cid
                   13941: 
                   13942: =item $selfenroll
                   13943: 
                   13944: =item $context
                   13945: 
1.1172.2.19  raeburn  13946: =item $credits, number of credits student will earn from this class
                   13947: 
1.1172.2.76  raeburn  13948: =item $instsec, institutional course section code for student
                   13949: 
1.297     matthew  13950: =back
                   13951: 
1.191     harris41 13952: 
                   13953: =item *
                   13954: 
1.243     albertel 13955: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13956: custom role; give a custom role to a user for the level given by URL.  Specify
                   13957: name and domain of role author, and role name
1.191     harris41 13958: 
                   13959: =item *
                   13960: 
1.243     albertel 13961: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13962: 
                   13963: =item *
                   13964: 
1.243     albertel 13965: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13966: 
                   13967: =back
                   13968: 
                   13969: =head2 Course Infomation
                   13970: 
                   13971: =over 4
1.191     harris41 13972: 
                   13973: =item *
                   13974: 
1.1118    foxr     13975: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13976: specified course id, including all environment settings for the
                   13977: course, the description of the course will be in the hash under the
                   13978: key 'description'
1.191     harris41 13979: 
1.1118    foxr     13980: $options is an optional parameter that if supplied is a hash reference that controls
                   13981: what how this function works.  It has the following key/values:
                   13982: 
                   13983: =over 4
                   13984: 
                   13985: =item freshen_cache
                   13986: 
                   13987: If defined, and the environment cache for the course is valid, it is 
                   13988: returned in the returned hash.
                   13989: 
                   13990: =item one_time
                   13991: 
                   13992: If defined, the last cache time is set to _now_
                   13993: 
                   13994: =item user
                   13995: 
                   13996: If defined, the supplied username is used instead of the current user.
                   13997: 
                   13998: 
                   13999: =back
                   14000: 
1.191     harris41 14001: =item *
                   14002: 
1.624     albertel 14003: resdata($name,$domain,$type,@which) : request for current parameter
                   14004: setting for a specific $type, where $type is either 'course' or 'user',
                   14005: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14006: answers for 10 minutes.
1.243     albertel 14007: 
1.877     foxr     14008: =item *
                   14009: 
                   14010: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14011: data base, returning a hash that is keyed by the resource name and has
                   14012: values that are the resource value.  I believe that the timestamps and
                   14013: versions are also returned.
                   14014: 
1.1172.2.31  raeburn  14015: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14016: supplemental content area. This routine caches the number of files for
                   14017: 10 minutes.
                   14018: 
1.243     albertel 14019: =back
                   14020: 
                   14021: =head2 Course Modification
                   14022: 
                   14023: =over 4
1.191     harris41 14024: 
                   14025: =item *
                   14026: 
1.243     albertel 14027: writecoursepref($courseid,%prefs) : write preferences (environment
                   14028: database) for a course
1.191     harris41 14029: 
                   14030: =item *
                   14031: 
1.1011    raeburn  14032: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14033: 
                   14034: =item *
                   14035: 
1.1038    raeburn  14036: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14037: 
1.1167    droeschl 14038: =item *
                   14039: 
                   14040: is_course($courseid), is_course($cdom, $cnum)
                   14041: 
                   14042: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14043: two component version $cdom, $cnum. It checks if the specified course exists.
                   14044: 
                   14045: Returns:
                   14046:     undef if the course doesn't exist, otherwise
                   14047:     in scalar context the combined courseid.
                   14048:     in list context the two components of the course identifier, domain and 
                   14049:     courseid.    
                   14050: 
1.243     albertel 14051: =back
                   14052: 
                   14053: =head2 Resource Subroutines
                   14054: 
                   14055: =over 4
1.191     harris41 14056: 
                   14057: =item *
                   14058: 
1.243     albertel 14059: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14060: 
                   14061: =item *
                   14062: 
1.243     albertel 14063: repcopy($filename) : subscribes to the requested file, and attempts to
                   14064: replicate from the owning library server, Might return
1.607     raeburn  14065: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14066: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14067: resource. Expects the local filesystem pathname
                   14068: (/home/httpd/html/res/....)
                   14069: 
                   14070: =back
                   14071: 
                   14072: =head2 Resource Information
                   14073: 
                   14074: =over 4
1.191     harris41 14075: 
                   14076: =item *
                   14077: 
1.1172.2.28  raeburn  14078: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14079: and returns the value of a variety of different possible values,
                   14080: $varname should be a request string, and the other parameters can be
                   14081: used to specify who and what one is asking about. Ordinarily, $cid 
                   14082: does not need to be specified, as it is retrived from 
                   14083: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14084: within lonuserstate::loadmap() when initializing a course, before
                   14085: $env{'request.course.id'} has been set, so it needs to be provided
                   14086: in that one case.
1.243     albertel 14087: 
                   14088: Possible values for $varname are environment.lastname (or other item
                   14089: from the envirnment hash), user.name (or someother aspect about the
                   14090: user), resource.0.maxtries (or some other part and parameter of a
                   14091: resource)
1.204     albertel 14092: 
                   14093: =item *
                   14094: 
1.243     albertel 14095: directcondval($number) : get current value of a condition; reads from a state
                   14096: string
1.204     albertel 14097: 
                   14098: =item *
                   14099: 
1.243     albertel 14100: condval($condidx) : value of condition index based on state
1.204     albertel 14101: 
                   14102: =item *
                   14103: 
1.243     albertel 14104: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14105: resource's metadata, $what should be either a specific key, or either
                   14106: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14107: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14108: 
                   14109: this function automatically caches all requests
1.191     harris41 14110: 
                   14111: =item *
                   14112: 
1.243     albertel 14113: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14114: network of library servers; returns file handle of where SQL and regex results
                   14115: will be stored for query
1.191     harris41 14116: 
                   14117: =item *
                   14118: 
1.1172.2.66  raeburn  14119: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14120: return symbolic list entry (all arguments optional).
                   14121: 
                   14122: Args: filename is the filename (including path) for the file for which a symb
                   14123: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14124: to check access status if more than one resource was found in the bighash
                   14125: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14126: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14127: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14128: cause possible symbs to be checked to determine if they are subject to content
                   14129: blocking, if so they will not be included as possible symbs; possibles is a
                   14130: ref to a hash, which, as a side effect, will be populated with all possible
                   14131: symbs (content blocking not tested).
                   14132: 
1.243     albertel 14133: returns the data handle
1.191     harris41 14134: 
                   14135: =item *
                   14136: 
1.1172.2.17  raeburn  14137: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14138: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14139: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14140: on failure, user must be in a course, as it assumes the existence of
                   14141: the course initial hash, and uses $env('request.course.id'}.  The third
                   14142: arg is an optional reference to a scalar.  If this arg is passed in the
                   14143: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14144: encrypted; otherwise it will be null.
1.243     albertel 14145: 
1.191     harris41 14146: =item *
                   14147: 
1.243     albertel 14148: symbclean($symb) : removes versions numbers from a symb, returns the
                   14149: cleaned symb
1.191     harris41 14150: 
                   14151: =item *
                   14152: 
1.243     albertel 14153: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14154: course map, user must be in a course for it to work.
1.191     harris41 14155: 
                   14156: =item *
                   14157: 
1.243     albertel 14158: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14159: 
                   14160: =item *
                   14161: 
1.243     albertel 14162: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14163: a random seed, all arguments are optional, if they aren't sent it uses the
                   14164: environment to derive them. Note: if symb isn't sent and it can't get one
                   14165: from &symbread it will use the current time as its return value
1.191     harris41 14166: 
                   14167: =item *
                   14168: 
1.243     albertel 14169: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14170: unfakeable, receipt
1.191     harris41 14171: 
                   14172: =item *
                   14173: 
1.620     albertel 14174: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14175: 
                   14176: =item *
                   14177: 
1.243     albertel 14178: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14179: 
                   14180: =item *
                   14181: 
1.243     albertel 14182: 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 14183: 
                   14184: =item *
                   14185: 
1.243     albertel 14186: 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 14187: 
                   14188: =item *
                   14189: 
1.243     albertel 14190: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14191: 
                   14192: =item *
                   14193: 
1.243     albertel 14194: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14195: forcing spreadsheet to reevaluate the resource scores next time.
                   14196: 
1.1172.2.13  raeburn  14197: =item *
                   14198: 
                   14199: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14200: when viewing in course context.
                   14201: 
                   14202:  input: six args -- filename (decluttered), course number, course domain,
                   14203:                     url, symb (if registered) and group (if this is a
                   14204:                     group item -- e.g., bulletin board, group page etc.).
                   14205: 
                   14206:  output: array of five scalars --
                   14207:          $cfile -- url for file editing if editable on current server
                   14208:          $home -- homeserver of resource (i.e., for author if published,
                   14209:                                           or course if uploaded.).
                   14210:          $switchserver --  1 if server switch will be needed.
                   14211:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14212:          $forceview -- 1 if icon/link should be to go to view mode
                   14213: 
                   14214: =item *
                   14215: 
                   14216: is_course_upload($file,$cnum,$cdom)
                   14217: 
                   14218: Used in course context to determine if current file was uploaded to
                   14219: the course (i.e., would be found in /userfiles/docs on the course's
                   14220: homeserver.
                   14221: 
                   14222:   input: 3 args -- filename (decluttered), course number and course domain.
                   14223:   output: boolean -- 1 if file was uploaded.
                   14224: 
1.243     albertel 14225: =back
                   14226: 
                   14227: =head2 Storing/Retreiving Data
                   14228: 
                   14229: =over 4
1.191     harris41 14230: 
                   14231: =item *
                   14232: 
1.1172.2.64  raeburn  14233: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14234: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14235: the remaining args aren't required and if they aren't passed or are '' they will
                   14236: be derived from the env (with the exception of $laststore, which is an
                   14237: optional arg used when a user's submission is stored in grading).
                   14238: $laststore is $version=$timestamp, where $version is the most recent version
                   14239: number retrieved for the corresponding $symb in the $namespace db file, and
                   14240: $timestamp is the timestamp for that transaction (UNIX time).
                   14241: $laststore is currently only passed when cstore() is called by
                   14242: structuretags::finalize_storage().
1.191     harris41 14243: 
                   14244: =item *
                   14245: 
1.1172.2.64  raeburn  14246: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14247: but uses critical subroutine
1.191     harris41 14248: 
                   14249: =item *
                   14250: 
1.243     albertel 14251: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14252: all args are optional
1.191     harris41 14253: 
                   14254: =item *
                   14255: 
1.717     albertel 14256: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14257: dumps the complete (or key matching regexp) namespace into a hash
                   14258: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14259: normally &store()ed into
                   14260: 
                   14261: $range should be either an integer '100' (give me the first 100
                   14262:                                            matching records)
                   14263:               or be  two integers sperated by a - with no spaces
                   14264:                  '30-50' (give me the 30th through the 50th matching
                   14265:                           records)
                   14266: 
                   14267: 
                   14268: =item *
                   14269: 
1.1172.2.59  raeburn  14270: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14271: replaces a &store() version of data with a replacement set of data
                   14272: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14273: reference. If $tolog is true, the transaction is logged in the courselog
                   14274: with an action=PUTSTORE.
1.717     albertel 14275: 
                   14276: =item *
                   14277: 
1.243     albertel 14278: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14279: works very similar to store/cstore, but all data is stored in a
                   14280: temporary location and can be reset using tmpreset, $storehash should
                   14281: be a hash reference, returns nothing on success
1.191     harris41 14282: 
                   14283: =item *
                   14284: 
1.243     albertel 14285: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14286: similar to restore, but all data is stored in a temporary location and
                   14287: can be reset using tmpreset. Returns a hash of values on success,
                   14288: error string otherwise.
1.191     harris41 14289: 
                   14290: =item *
                   14291: 
1.243     albertel 14292: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14293: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14294: 
                   14295: =item *
                   14296: 
1.243     albertel 14297: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14298: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14299: 
                   14300: =item *
                   14301: 
1.243     albertel 14302: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14303: namesp ($udom and $uname are optional)
1.191     harris41 14304: 
                   14305: =item *
                   14306: 
1.702     albertel 14307: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14308: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14309: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14310: 
1.702     albertel 14311: $range should be either an integer '100' (give me the first 100
                   14312:                                            matching records)
                   14313:               or be  two integers sperated by a - with no spaces
                   14314:                  '30-50' (give me the 30th through the 50th matching
                   14315:                           records)
1.449     matthew  14316: =item *
                   14317: 
                   14318: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14319: $store can be a scalar, an array reference, or if the amount to be 
                   14320: incremented is > 1, a hash reference.
                   14321: 
                   14322: ($udom and $uname are optional)
1.191     harris41 14323: 
                   14324: =item *
                   14325: 
1.243     albertel 14326: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14327: ($udom and $uname are optional)
1.191     harris41 14328: 
                   14329: =item *
                   14330: 
1.243     albertel 14331: cput($namespace,$storehash,$udom,$uname) : critical put
                   14332: ($udom and $uname are optional)
1.191     harris41 14333: 
                   14334: =item *
                   14335: 
1.748     albertel 14336: newput($namespace,$storehash,$udom,$uname) :
                   14337: 
                   14338: Attempts to store the items in the $storehash, but only if they don't
                   14339: currently exist, if this succeeds you can be certain that you have 
                   14340: successfully created a new key value pair in the $namespace db.
                   14341: 
                   14342: 
                   14343: Args:
                   14344:  $namespace: name of database to store values to
                   14345:  $storehash: hashref to store to the db
                   14346:  $udom: (optional) domain of user containing the db
                   14347:  $uname: (optional) name of user caontaining the db
                   14348: 
                   14349: Returns:
                   14350:  'ok' -> succeeded in storing all keys of $storehash
                   14351:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14352:                         least <key> already existed in the db (other
                   14353:                         requested keys may also already exist)
1.967     bisitz   14354:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14355:  'con_lost' -> unable to contact request server
                   14356:  'refused' -> action was not allowed by remote machine
                   14357: 
                   14358: 
                   14359: =item *
                   14360: 
1.243     albertel 14361: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14362: reference filled in from namesp (encrypts the return communication)
                   14363: ($udom and $uname are optional)
1.191     harris41 14364: 
                   14365: =item *
                   14366: 
1.243     albertel 14367: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14368: critical subroutine
                   14369: 
1.806     raeburn  14370: =item *
                   14371: 
1.860     raeburn  14372: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14373: array reference filled in from namespace found in domain level on either
                   14374: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14375: 
                   14376: =item *
                   14377: 
1.860     raeburn  14378: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14379: domain level either on specified domain server ($uhome) or primary domain 
                   14380: server ($udom and $uhome are optional)
1.806     raeburn  14381: 
1.943     raeburn  14382: =item * 
                   14383: 
1.1172.2.35  raeburn  14384: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14385: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14386: the target domain.
                   14387: 
                   14388: May also include additional key => value pairs for the following groups:
                   14389: 
                   14390: =over
                   14391: 
                   14392: =item
                   14393: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14394: 
                   14395: =over
                   14396: 
                   14397: =item defaultquota, authorquota
                   14398: 
                   14399: =back
                   14400: 
                   14401: =item
                   14402: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14403: portfolio for users).
                   14404: 
                   14405: =over
                   14406: 
                   14407: =item
                   14408: aboutme, blog, webdav, portfolio
                   14409: 
                   14410: =back
                   14411: 
                   14412: =item
                   14413: requestcourses: ability to request courses, and how requests are processed.
                   14414: 
                   14415: =over
                   14416: 
                   14417: =item
1.1172.2.37  raeburn  14418: official, unofficial, community, textbook
1.1172.2.35  raeburn  14419: 
                   14420: =back
                   14421: 
                   14422: =item
                   14423: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14424: 
                   14425: =over
                   14426: 
                   14427: =item
1.1172.2.44  raeburn  14428: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14429: 
                   14430: =back
                   14431: 
                   14432: =item
                   14433: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14434: for course's uploaded content.
                   14435: 
                   14436: =over
                   14437: 
                   14438: =item
1.1172.2.68  raeburn  14439: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14440: communityquota, textbookquota
1.1172.2.35  raeburn  14441: 
                   14442: =back
                   14443: 
                   14444: =item
                   14445: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14446: on your servers.
                   14447: 
                   14448: =over
                   14449: 
                   14450: =item
                   14451: remotesessions, hostedsessions
                   14452: 
                   14453: =back
                   14454: 
                   14455: =back
                   14456: 
                   14457: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14458: utility to create a configuration.db file on a domain's primary library server
                   14459: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14460: -- corresponding values are authentication type (internal, krb4, krb5,
                   14461: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14462: will be available. Values are retrieved from cache (if current), unless the
                   14463: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14464: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14465: 
                   14466: Typical usage:
1.943     raeburn  14467: 
1.1172.2.35  raeburn  14468: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14469: 
1.243     albertel 14470: =back
                   14471: 
                   14472: =head2 Network Status Functions
                   14473: 
                   14474: =over 4
1.191     harris41 14475: 
                   14476: =item *
                   14477: 
1.1137    raeburn  14478: dirlist() : return directory list based on URI (first arg).
                   14479: 
                   14480: Inputs: 1 required, 5 optional.
                   14481: 
                   14482: =over
                   14483: 
                   14484: =item 
                   14485: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14486: 
                   14487: =item
                   14488: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14489: 
                   14490: =item
                   14491: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14492: 
                   14493: =item
                   14494: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14495: 
                   14496: =item
                   14497: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14498: 
                   14499: =item 
                   14500: $alternateRoot - path to prepend in place of path from $uri.
                   14501: 
                   14502: =back
                   14503: 
                   14504: Returns: Array of up to two items.
                   14505: 
                   14506: =over
                   14507: 
                   14508: a reference to an array of files/subdirectories
                   14509: 
                   14510: =over
                   14511: 
                   14512: Each element in the array of files/subdirectories is a & separated list of
                   14513: item name and the result of running stat on the item.  If dirlist was requested
                   14514: for a file instead of a directory, the item name will be ''. For a directory 
                   14515: listing, if the item is a metadata file, the element will end &N&M 
                   14516: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14517: default copyright set (1).  
                   14518: 
                   14519: =back
                   14520: 
                   14521: a scalar containing error condition (if encountered).
                   14522: 
                   14523: =over
                   14524: 
                   14525: =item 
                   14526: no_host (no homeserver identified for $username:$domain).
                   14527: 
                   14528: =item 
                   14529: no_such_host (server contacted for listing not identified as valid host).
                   14530: 
                   14531: =item 
                   14532: con_lost (connection to remote server failed).
                   14533: 
                   14534: =item 
                   14535: refused (invalid $username:$domain received on lond side).
                   14536: 
                   14537: =item 
                   14538: no_such_dir (directory at specified path on lond side does not exist). 
                   14539: 
                   14540: =item 
                   14541: empty (directory at specified path on lond side is empty).
                   14542: 
                   14543: =over
                   14544: 
                   14545: This is currently not encountered because the &ls3, &ls2, 
                   14546: &ls (_handler) routines on the lond side do not filter out
                   14547: . and .. from a directory listing. 
                   14548: 
                   14549: =back
                   14550: 
                   14551: =back
                   14552: 
                   14553: =back
1.191     harris41 14554: 
                   14555: =item *
                   14556: 
1.243     albertel 14557: spareserver() : find server with least workload from spare.tab
                   14558: 
1.986     foxr     14559: 
                   14560: =item *
                   14561: 
                   14562: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14563: if there is no corresponding loncapa host.
                   14564: 
1.243     albertel 14565: =back
                   14566: 
1.986     foxr     14567: 
1.243     albertel 14568: =head2 Apache Request
                   14569: 
                   14570: =over 4
1.191     harris41 14571: 
                   14572: =item *
                   14573: 
1.243     albertel 14574: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14575: localhost, posts hash
                   14576: 
                   14577: =back
                   14578: 
                   14579: =head2 Data to String to Data
                   14580: 
                   14581: =over 4
1.191     harris41 14582: 
                   14583: =item *
                   14584: 
1.243     albertel 14585: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14586: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14587: 
                   14588: =item *
                   14589: 
1.243     albertel 14590: hashref2str($hashref) : convert a hashref into a string complete with
                   14591: escaping and '=' and '&' separators, supports elements that are
                   14592: arrayrefs and hashrefs
1.191     harris41 14593: 
                   14594: =item *
                   14595: 
1.243     albertel 14596: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14597: with escaping and '&' separators, supports elements that are arrayrefs
                   14598: and hashrefs
1.191     harris41 14599: 
                   14600: =item *
                   14601: 
1.243     albertel 14602: str2hash($string) : convert string to hash using unescaping and
                   14603: splitting on '=' and '&', supports elements that are arrayrefs and
                   14604: hashrefs
1.191     harris41 14605: 
                   14606: =item *
                   14607: 
1.243     albertel 14608: str2array($string) : convert string to hash using unescaping and
                   14609: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14610: 
                   14611: =back
                   14612: 
                   14613: =head2 Logging Routines
                   14614: 
                   14615: 
                   14616: These routines allow one to make log messages in the lonnet.log and
                   14617: lonnet.perm logfiles.
1.191     harris41 14618: 
1.1119    foxr     14619: =over 4
                   14620: 
1.191     harris41 14621: =item *
                   14622: 
1.243     albertel 14623: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14624: 
                   14625: =item *
                   14626: 
1.243     albertel 14627: logthis() : append message to the normal lonnet.log file, it gets
                   14628: preiodically rolled over and deleted.
1.191     harris41 14629: 
                   14630: =item *
                   14631: 
1.243     albertel 14632: logperm() : append a permanent message to lonnet.perm.log, this log
                   14633: file never gets deleted by any automated portion of the system, only
                   14634: messages of critical importance should go in here.
                   14635: 
1.1119    foxr     14636: 
1.243     albertel 14637: =back
                   14638: 
                   14639: =head2 General File Helper Routines
                   14640: 
                   14641: =over 4
1.191     harris41 14642: 
                   14643: =item *
                   14644: 
1.481     raeburn  14645: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14646: (a) files in /uploaded
                   14647:   (i) If a local copy of the file exists - 
                   14648:       compares modification date of local copy with last-modified date for 
                   14649:       definitive version stored on home server for course. If local copy is 
                   14650:       stale, requests a new version from the home server and stores it. 
                   14651:       If the original has been removed from the home server, then local copy 
                   14652:       is unlinked.
                   14653:   (ii) If local copy does not exist -
                   14654:       requests the file from the home server and stores it. 
                   14655:   
                   14656:   If $caller is 'uploadrep':  
                   14657:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14658:     for request for files originally uploaded via DOCS. 
                   14659:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14660:   
                   14661:   Otherwise:
                   14662:      This indicates a call from the content generation phase of the request.
                   14663:      -  returns the entire contents of the file or -1.
                   14664:      
                   14665: (b) files in /res
                   14666:    - returns the entire contents of a file or -1; 
                   14667:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14668: 
1.712     albertel 14669: 
                   14670: =item *
                   14671: 
                   14672: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14673:                   reference
                   14674: 
                   14675: returns either a stat() list of data about the file or an empty list
                   14676: if the file doesn't exist or couldn't find out about it (connection
                   14677: problems or user unknown)
                   14678: 
1.191     harris41 14679: =item *
                   14680: 
1.243     albertel 14681: filelocation($dir,$file) : returns file system location of a file
                   14682: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14683: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14684: and a file of ../bob will become /a/bob)
1.191     harris41 14685: 
                   14686: =item *
                   14687: 
                   14688: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14689: filelocation except for hrefs
                   14690: 
                   14691: =item *
                   14692: 
1.1172.2.49  raeburn  14693: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14694: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14695: 
1.243     albertel 14696: =back
                   14697: 
1.608     albertel 14698: =head2 Usererfile file routines (/uploaded*)
                   14699: 
                   14700: =over 4
                   14701: 
                   14702: =item *
                   14703: 
                   14704: userfileupload(): main rotine for putting a file in a user or course's
                   14705:                   filespace, arguments are,
                   14706: 
1.620     albertel 14707:  formname - required - this is the name of the element in $env where the
1.608     albertel 14708:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14709:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14710:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14711:  context - if coursedoc, store the file in the course of the active role
                   14712:              of the current user; 
                   14713:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14714:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14715:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14716:          if undefined, it will be placed in "unknown"
                   14717: 
                   14718:  (This routine calls clean_filename() to remove any dangerous
                   14719:  characters from the filename, and then calls finuserfileupload() to
                   14720:  complete the transaction)
                   14721: 
                   14722:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14723:  and /adm/notfound.html if unsuccessful
                   14724: 
                   14725: =item *
                   14726: 
                   14727: clean_filename(): routine for cleaing a filename up for storage in
                   14728:                  userfile space, argument is:
                   14729: 
                   14730:  filename - proposed filename
                   14731: 
                   14732: returns: the new clean filename
                   14733: 
                   14734: =item *
                   14735: 
1.1090    raeburn  14736: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14737: userspace, probably shouldn't be called directly
                   14738: 
                   14739:   docuname: username or courseid of destination for the file
                   14740:   docudom: domain of user/course of destination for the file
                   14741:   formname: same as for userfileupload()
1.1090    raeburn  14742:   fname: filename (including subdirectories) for the file
                   14743:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14744:   allfiles: reference to hash used to store objects found by parser
                   14745:   codebase: reference to hash used for codebases of java objects found by parser
                   14746:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14747:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14748:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14749:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14750:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14751:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14752:   mimetype: reference to scalar to accommodate mime type determined
                   14753:             from File::MMagic if $parser = parse.
1.608     albertel 14754: 
                   14755:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14756:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14757:  was 'overwrite').
                   14758:  
1.608     albertel 14759: 
                   14760: =item *
                   14761: 
                   14762: renameuserfile(): renames an existing userfile to a new name
                   14763: 
                   14764:   Args:
                   14765:    docuname: username or courseid of destination for the file
                   14766:    docudom: domain of user/course of destination for the file
                   14767:    old: current file name (including any subdirs under userfiles)
                   14768:    new: desired file name (including any subdirs under userfiles)
                   14769: 
                   14770: =item *
                   14771: 
                   14772: mkdiruserfile(): creates a directory is a userfiles dir
                   14773: 
                   14774:   Args:
                   14775:    docuname: username or courseid of destination for the file
                   14776:    docudom: domain of user/course of destination for the file
                   14777:    dir: dir to create (including any subdirs under userfiles)
                   14778: 
                   14779: =item *
                   14780: 
                   14781: removeuserfile(): removes a file that exists in userfiles
                   14782: 
                   14783:   Args:
                   14784:    docuname: username or courseid of destination for the file
                   14785:    docudom: domain of user/course of destination for the file
                   14786:    fname: filname to delete (including any subdirs under userfiles)
                   14787: 
                   14788: =item *
                   14789: 
                   14790: removeuploadedurl(): convience function for removeuserfile()
                   14791: 
                   14792:   Args:
                   14793:    url:  a full /uploaded/... url to delete
                   14794: 
1.747     albertel 14795: =item * 
                   14796: 
                   14797: get_portfile_permissions():
                   14798:   Args:
                   14799:     domain: domain of user or course contain the portfolio files
                   14800:     user: name of user or num of course contain the portfolio files
                   14801:   Returns:
                   14802:     hashref of a dump of the proper file_permissions.db
                   14803:    
                   14804: 
                   14805: =item * 
                   14806: 
                   14807: get_access_controls():
                   14808: 
                   14809: Args:
                   14810:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14811:   group: (optional) the group you want the files associated with
                   14812:   file: (optional) the file you want access info on
                   14813: 
                   14814: Returns:
1.749     raeburn  14815:     a hash (keys are file names) of hashes containing
                   14816:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14817:         values are XML containing access control settings (see below) 
1.747     albertel 14818: 
                   14819: Internal notes:
                   14820: 
1.749     raeburn  14821:  access controls are stored in file_permissions.db as key=value pairs.
                   14822:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14823:         where scope -> public,guest,course,group,domains or users.
                   14824:               end -> UNIX time for end of access (0 -> no end date)
                   14825:               start -> UNIX time for start of access
                   14826: 
                   14827:     value -> XML description of access control
                   14828:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14829:             <start></start>
                   14830:             <end></end>
                   14831: 
                   14832:             <password></password>  for scope type = guest
                   14833: 
                   14834:             <domain></domain>     for scope type = course or group
                   14835:             <number></number>
                   14836:             <roles id="">
                   14837:              <role></role>
                   14838:              <access></access>
                   14839:              <section></section>
                   14840:              <group></group>
                   14841:             </roles>
                   14842: 
                   14843:             <dom></dom>         for scope type = domains
                   14844: 
                   14845:             <users>             for scope type = users
                   14846:              <user>
                   14847:               <uname></uname>
                   14848:               <udom></udom>
                   14849:              </user>
                   14850:             </users>
                   14851:            </scope> 
                   14852:               
                   14853:  Access data is also aggregated for each file in an additional key=value pair:
                   14854:  key -> path to file/file_name\0accesscontrol 
                   14855:  value -> reference to hash
                   14856:           hash contains key = value pairs
                   14857:           where key = uniqueID:scope_end_start
                   14858:                 value = UNIX time record was last updated
                   14859: 
                   14860:           Used to improve speed of look-ups of access controls for each file.  
                   14861:  
                   14862:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14863: 
1.1172.2.13  raeburn  14864: =item *
                   14865: 
1.749     raeburn  14866: modify_access_controls():
                   14867: 
                   14868: Modifies access controls for a portfolio file
                   14869: Args
                   14870: 1. file name
                   14871: 2. reference to hash of required changes,
                   14872: 3. domain
                   14873: 4. username
                   14874:   where domain,username are the domain of the portfolio owner 
                   14875:   (either a user or a course) 
                   14876: 
                   14877: Returns:
                   14878: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14879: 2. result of deletions ('ok' or 'error', with error message).
                   14880: 3. reference to hash of any new or updated access controls.
                   14881: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14882:    key = integer (inbound ID)
1.1172.2.13  raeburn  14883:    value = uniqueID
                   14884: 
                   14885: =item *
                   14886: 
                   14887: get_timebased_id():
                   14888: 
                   14889: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14890: course via the Course Editor (e.g., folders, composite pages,
                   14891: group bulletin boards).
                   14892: 
                   14893: Args: (first three required; six others optional)
                   14894: 
                   14895: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14896:    docssequence, or name of group
                   14897: 
                   14898: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14899:    e.g., num, boardids
                   14900: 
                   14901: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14902:    file will be named nohist_namespace.db
                   14903: 
                   14904: 4. cdom: domain of course; default is current course domain from %env
                   14905: 
                   14906: 5. cnum: course number; default is current course number from %env
                   14907: 
                   14908: 6. idtype: set to concat if an additional digit is to be appended to the
                   14909:    unix timestamp to form the suffix, if the plain timestamp is already
                   14910:    in use.  Default is to not do this, but simply increment the unix
                   14911:    timestamp by 1 until a unique key is obtained.
                   14912: 
                   14913: 7. who: holder of locking key; defaults to user:domain for user.
                   14914: 
                   14915: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14916:    retrying); default is 3.
                   14917: 
                   14918: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14919: 
                   14920: Returns:
                   14921: 
                   14922: 1. suffix obtained (numeric)
                   14923: 
                   14924: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14925: 
                   14926: 3. error: contains (localized) error message if an error occurred.
                   14927: 
1.747     albertel 14928: 
1.608     albertel 14929: =back
                   14930: 
1.243     albertel 14931: =head2 HTTP Helper Routines
                   14932: 
                   14933: =over 4
                   14934: 
1.191     harris41 14935: =item *
                   14936: 
                   14937: escape() : unpack non-word characters into CGI-compatible hex codes
                   14938: 
                   14939: =item *
                   14940: 
                   14941: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14942: 
1.243     albertel 14943: =back
                   14944: 
                   14945: =head1 PRIVATE SUBROUTINES
                   14946: 
                   14947: =head2 Underlying communication routines (Shouldn't call)
                   14948: 
                   14949: =over 4
                   14950: 
                   14951: =item *
                   14952: 
                   14953: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14954: 
                   14955: =item *
                   14956: 
                   14957: reply() : uses subreply to send a message to remote machine, logs all failures
                   14958: 
                   14959: =item *
                   14960: 
                   14961: critical() : passes a critical message to another server; if cannot
                   14962: get through then place message in connection buffer directory and
                   14963: returns con_delayed, if incapable of saving message, returns
                   14964: con_failed
                   14965: 
                   14966: =item *
                   14967: 
                   14968: reconlonc() : tries to reconnect lonc client processes.
                   14969: 
                   14970: =back
                   14971: 
                   14972: =head2 Resource Access Logging
                   14973: 
                   14974: =over 4
                   14975: 
                   14976: =item *
                   14977: 
                   14978: flushcourselogs() : flush (save) buffer logs and access logs
                   14979: 
                   14980: =item *
                   14981: 
                   14982: courselog($what) : save message for course in hash
                   14983: 
                   14984: =item *
                   14985: 
                   14986: courseacclog($what) : save message for course using &courselog().  Perform
                   14987: special processing for specific resource types (problems, exams, quizzes, etc).
                   14988: 
1.191     harris41 14989: =item *
                   14990: 
                   14991: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14992: as a PerlChildExitHandler
1.243     albertel 14993: 
                   14994: =back
                   14995: 
                   14996: =head2 Other
                   14997: 
                   14998: =over 4
                   14999: 
                   15000: =item *
                   15001: 
                   15002: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15003: 
                   15004: =back
                   15005: 
                   15006: =cut
1.877     foxr     15007: 

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